[
    {
        "title": "Stone Game V",
        "algo_input": "There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\n\nIn each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\n\nThe game ends when there is only one stone remaining. Alice's is initially zero.\n\nReturn the maximum score that Alice can obtain.\n\n \nExample 1:\n\nInput: stoneValue = [6,2,3,4,5,5]\nOutput: 18\nExplanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n\n\nExample 2:\n\nInput: stoneValue = [7,7,7,7,7,7,7]\nOutput: 28\n\n\nExample 3:\n\nInput: stoneValue = [4]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= stoneValue.length <= 500\n\t1 <= stoneValue[i] <= 106\n\n",
        "solution_py": "from collections import defaultdict\nfrom itertools import accumulate\n\nclass Solution:\n\n    def stoneGameV(self, stoneValue: List[int]) -> int:\n        n = len(stoneValue)\n        dp = [[0]*n for _ in range(n)]\n        left = [[0]*n for _ in range(n)]\n        prefix = list(accumulate(stoneValue))\n        prefix = [0]+prefix+[prefix[-1]]\n\n        def sum(i,j):\n            return prefix[j+1]-prefix[i]\n\n        row_idx = [i for i in range(n)]\n        for i in range(n):\n            left[i][i] = stoneValue[i]\n        for d in range(1,n):\n            for i in range(n-d):\n                j = i+d\n                while sum(i,row_idx[i]) < sum(row_idx[i]+1,j):\n                    row_idx[i] +=1\n                if sum(i, row_idx[i]) == sum(row_idx[i]+1,j):\n                    dp[i][j] = max(left[i][row_idx[i]], left[j][row_idx[i]+1])\n                else:\n                    if row_idx[i] == i:\n                        dp[i][j] = left[j][i+1]\n                    elif row_idx[i] == j:\n                        dp[i][j] = left[i][j-1]\n                    else:\n                        dp[i][j] = max(left[i][row_idx[i]-1], left[j][row_idx[i]+1])\n                left[j][i] = max(left[j][i+1],sum(i,j)+dp[i][j])\n                left[i][j] = max(left[i][j-1],sum(i,j)+dp[i][j])\n        return dp[0][n-1]",
        "solution_js": "var stoneGameV = function(stoneValue) {\n    // Find the stoneValue array's prefix sum\n    let prefix = Array(stoneValue.length).fill(0);\n    for (let i = 0; i < stoneValue.length; i++) {\n        prefix[i] = stoneValue[i] + (prefix[i - 1] || 0);\n    }\n\n    let dp = Array(stoneValue.length).fill().map(() => Array(stoneValue.length).fill(0));\n\n    function game(start, end) {\n        if (dp[start][end]) return dp[start][end];\n        if (start === end) return 0;\n\n        let max = 0;\n        for (let i = start + 1; i <= end; i++) {\n            let sumL = prefix[i - 1] - (prefix[start - 1] || 0);\n            let sumR = prefix[end] - (prefix[i - 1] || 0);\n            if (sumL > sumR) {\n                max = Math.max(max, sumR + game(i, end));\n            } else if (sumL < sumR) {\n                max = Math.max(max, sumL + game(start, i - 1));\n            } else {\n                // If tied, check both rows\n                let left = sumR + game(i, end);\n                let right = sumL + game(start, i - 1);\n                max = Math.max(max, left, right);\n            }\n        } return dp[start][end] = max;\n    }\n\n    return game(0, stoneValue.length - 1);\n};",
        "solution_java": "class Solution {\n    int dp[][];\n    public int fnc(int a[], int i, int j, int sum){\n        //System.out.println(i+\" \"+j);\n        int n=a.length;\n        if(i>j)\n            return 0;\n        if(j>n)\n            return 0;\n        if(i==j){\n            dp[i][j]=-1;\n            return 0;\n        }\n        if(dp[i][j]!=0)\n            return dp[i][j];\n\n   int temp=0;\n        int ans=Integer.MIN_VALUE;\n\n        for(int index=i;index<=j;index++){\n            temp+=a[index];\n            if(temp>sum-temp){\n                ans=Math.max(ans,((sum-temp)+fnc(a,index+1,j,sum-temp)));\n            }\n            else if(temp<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}",
        "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};"
    },
    {
        "title": "Power of Two",
        "algo_input": "Given an integer n, return true if it is a power of two. Otherwise, return false.\n\nAn integer n is a power of two, if there exists an integer x such that n == 2x.\n\n&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?",
        "solution_py": "class Solution:\n    def isPowerOfTwo(self, n: int) -> bool:\n        \n         if n == 0: return False\n        \n         k = n\n         while k != 1:\n             if k % 2 != 0:\n                 return False\n             k = k // 2\n            \n            \n         return True\n\n        count = 0\n        for i in range(33):\n            mask = 1 << i\n            \n            if mask & n:\n                count += 1\n                \n            if count > 1:\n                return False\n                \n        if count == 1:\n            return True\n        return False\n\t\t",
        "solution_js": "var isPowerOfTwo = function(n) {\n    let i=1;\n    while(i<n){\n        i*=2\n    }return i===n\n};",
        "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}",
        "solution_c": "class Solution {\npublic:\n    bool isPowerOfTwo(int n) {\n        if(n==0) return false;\n        while(n%2==0) n/=2;\n        return n==1;\n    }\n};"
    },
    {
        "title": "N-Queens",
        "algo_input": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n\nGiven an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.\n\n&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",
        "solution_py": "class Solution:\n    def solveNQueens(self, n: int) -> List[List[str]]:\n        coord = self.findNextRows(0, n)\n        ans = []\n        for c in coord:\n            temp = []\n            for j in c:\n                temp.append(\".\"*j+\"Q\"+\".\"*(n-j-1))\n            ans.append(temp)\n        return ans\n                        \n    def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()):\n\t\t'''\n\t\th_occ: occupied horizontal coordinate\n\t\td_occ: occupied diagonal\n\t\tad_occ: occupied anti-diagonal\n\t\t'''\n        ans = []\n        if i==n:\n            return [[]]\n        for j in range(n):\n             if (j not in h_occ) and (j-i not in d_occ) and ((j-n+1)+i not in ad_occ):\n                    h_occ.add(j)\n                    d_occ.add(j-i)\n                    ad_occ.add((j-n+1)+i)\n                    temp = self.findNextRows(i+1, n, h_occ, d_occ, ad_occ)\n                    h_occ.remove(j)\n                    d_occ.remove(j-i)\n                    ad_occ.remove((j-n+1)+i)\n                    ans += [[j]+l for l in temp]\n        return ans\n                \n                ",
        "solution_js": "// time O(n!) | space O(n^n)\nvar solveNQueens = function(n) {\n    let res = [];\n    \n    function backtrack(board, r) {\n        if (r === n) {\n            // - 1 to account for adding a Q that takes up a space\n            res.push(board.map((c) => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)));\n            return;\n        }\n        \n        for (let c = 0; c < n; c++) {\n            // bc is the current element\n            // br is the index of the element bc\n            //\n            // bc === c | checks row and col\n            // bc === c - r + br | checks lower diagonal\n            // bc === c + r - br | checks upper diagonal\n            if (!board.some((bc, br) => bc === c || bc === c - r + br || bc === c + r - br)) {\n                backtrack(board.concat(c), r + 1);\n            }\n        }\n    }\n    \n    backtrack([], 0);\n    \n    return res;\n};",
        "solution_java": "Simple backtracking logic, try out each row and col and check position is valid or not.\n\nsince we are going row one by one, there is no way queen is placed in that row.\n\nso, we need to check col, diagonals for valid position.\n\n// col is straightforward flag for each column\n\n// dia1\n// 0 1 2 3\n// 1 2 3 4\n// 2 3 4 5\n// 3 4 5 6\n\n// dia2\n// 0 -1 -2 -3\n// 1  0 -1 -2\n// 2  1  0 -1\n// 3  2  1  0\n\nnegative numbers are not allowed as index, so we add n - 1 to diagonal2.\n\nclass Solution {\n    List<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}",
        "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};"
    },
    {
        "title": "Check if Array Is Sorted and Rotated",
        "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",
        "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",
        "solution_js": "var check = function(nums) {\n  let decreased = false\n  for (let i = 1; i < nums.length; i += 1) {\n    if (nums[i] < nums[i - 1]) {\n      if (decreased) {\n        return false\n      }\n      decreased = true\n    }\n  }\n  return decreased ? nums[0] >= nums[nums.length - 1] : true\n};",
        "solution_java": "class Solution {\n    public boolean check(int[] nums) {\n        // here we compare all the neighbouring elemnts and check whether they are in somewhat sorted\n        // there will be a small change due to rotation in the array at only one place.\n        // so if there are irregularities more than once, return false\n        // else return true;\n        int irregularities = 0;\n        int length = nums.length;\n        for (int i=0; i<length; i++) {\n            if (nums[i] > nums[(i + 1) % length])\n                irregularities += 1;\n        }\n        return irregularities > 1 ? false : true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool check(vector<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};"
    },
    {
        "title": "Special Positions in a Binary Matrix",
        "algo_input": "Given an m x n binary matrix mat, return the number of special positions in mat.\n\nA position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).\n\n&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",
        "solution_py": "class Solution(object):\n    def numSpecial(self, mat):\n        \"\"\"\n        :type mat: List[List[int]]\n        :rtype: int\n        \"\"\"\n        r=len(mat)\n        c=len(mat[0])\n        \n        r_c={}\n        l_c={}\n        \n        for i in range(r):\n            flag=0\n            for j in range(c):\n                if(mat[i][j]==1):\n                    flag+=1\n            r_c[i]=flag\n        for i in range(c):\n            flag=0\n            for j in range(r):\n                if(mat[j][i]==1):\n                    flag+=1\n            l_c[i]=flag\n        ret=0\n        for i in range(r):\n            for j in range(c):\n                if(mat[i][j]==1 and l_c[j]==1 and r_c[i]==1):\n                    ret+=1\n        return ret",
        "solution_js": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nvar numSpecial = function(mat) {\n    let specialPostions = [];\n    for(let i in mat){\n        for(let j in mat[i]){\n            if(mat[i][j] == 1 ){\n                let horizontalOnes = 0;\n                let verticalOnes = 0;\n                    \n                for(let k in mat[i]){\n                    if(k != j &&  mat[i][k] == 1){\n                        horizontalOnes++;\n                    }\n                }\n                    \n                for(let k = 0 ; k < mat.length ; k++ ){\n                    if(k != i && mat[k][j] == 1){\n                        verticalOnes++;\n                    }\n                }\n                    \n                if(horizontalOnes == 0 && verticalOnes == 0){\n                    specialPostions.push([i,j]);\n                }\n                \n            }\n        }\n    }\n    \n    return specialPostions.length;\n    \n};",
        "solution_java": "class Solution {\n    public int numSpecial(int[][] mat) {\n      int count=0;\n        for(int i=0;i<mat.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}",
        "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};"
    },
    {
        "title": "Design Circular Deque",
        "algo_input": "Design your implementation of the circular double-ended queue (deque).\n\nImplement the MyCircularDeque class:\n\n\n\tMyCircularDeque(int k) Initializes the deque with a maximum size of k.\n\tboolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.\n\tint getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.\n\tint getRear() Returns the last item from Deque. Returns -1 if the deque is empty.\n\tboolean isEmpty() Returns true if the deque is empty, or false otherwise.\n\tboolean isFull() Returns true if the deque is full, or false otherwise.\n\n\n&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",
        "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};",
        "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};",
        "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};",
        "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};"
    },
    {
        "title": "Sum of All Subset XOR Totals",
        "algo_input": "The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.\n\n\n\tFor example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.\n\n\nGiven an array nums, return the sum of all XOR totals for every subset of nums.&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",
        "solution_py": "class Solution:\n    def subsetXORSum(self, nums: List[int]) -> int:\n        def sums(term, idx):\n            if idx == len(nums):\n                return term\n            return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)\n\n        return sums(0, 0)",
        "solution_js": "var subsetXORSum = function(nums) {\n    let output=[];\n    backtrack();\n    return output.reduce((a,b)=>a+b);\n    function backtrack(start = 0, arr=[nums[0]]){\n       output.push([...arr].reduce((a,b)=>a^b,0));\n       for(let i=start; i<nums.length; i++){\n            arr.push(nums[i]);\n            backtrack(i+1, arr);\n            arr.pop();\n       }\n    }\n};",
        "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}",
        "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};"
    },
    {
        "title": "Maximum Performance of a Team",
        "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",
        "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            ",
        "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};",
        "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}",
        "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}; "
    },
    {
        "title": "Minimum Number of Taps to Open to Water a Garden",
        "algo_input": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).\n\nThere are n + 1 taps located at points [0, 1, ..., n] in the garden.\n\nGiven an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.\n\nReturn the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n\n&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",
        "solution_py": "class Solution:\n    def minTaps(self, n: int, ranges: List[int]) -> int:\n        maxRanges = [0]\n        for i in range(len(ranges)):\n            minIdx = max(i - ranges[i], 0)\n            maxIdx = min(i + ranges[i], n)\n            idx = bisect_left(maxRanges, minIdx)\n            if idx == len(maxRanges) or maxIdx <= maxRanges[idx]: continue\n            if idx == len(maxRanges) - 1:\n                maxRanges.append(maxIdx)\n            else:\n                maxRanges[idx + 1] = max(maxRanges[idx + 1], maxIdx)\n        if maxRanges[-1] < n:\n            return -1\n        else:\n            return len(maxRanges) - 1",
        "solution_js": "var minTaps = function(n, ranges) {\n    let intervals = [];\n    for (let i = 0; i < ranges.length; i++) {\n        let l = i - ranges[i];\n        let r = i + ranges[i];\n        intervals.push([l, r]);\n    }\n\n    intervals.sort((a, b) => {\n        if (a[0] === b[0]) return b[1] - a[1];\n        return a[0] - b[0];\n    })\n\n    // Find the starting idx\n    let startIdx;\n    for (let i = 0; i < intervals.length; i++) {\n        let [s, e] = intervals[i];\n        if (s <= 0) {\n            if (startIdx === undefined) startIdx = i;\n            else if (intervals[startIdx][1] < e) startIdx = i;\n        } else break;\n    }\n    if (startIdx === undefined) return -1;\n\n    let q = [startIdx], openedTaps = 1;\n    while (q.length) {\n        let max;\n        while (q.length) {\n            let idx = q.pop();\n            let [start, end] = intervals[idx];\n            if (end >= n) return openedTaps;\n            for (let i = idx + 1; i < intervals.length; i++) {\n                let [nextStart, nextEnd] = intervals[i];\n                // If next interval's start is less than the current interval's end\n                if (nextStart <= end) {\n                    if (!max && nextEnd > end) max = {i, end: nextEnd};\n                    // If the next interval's end is greater than the current interval's end\n                    else if (max && nextEnd > max.end) max = {i, end: nextEnd};\n                }\n                else break;\n            }\n        }\n        if (max) {\n            q.push(max.i);\n            openedTaps++;\n        }\n    }\n\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int minTaps(int n, int[] ranges) {\n        Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new);\n        Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o]));\n        int ans = 1, cur = 0, end = 0;\n        for (int i = 0;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}",
        "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};"
    },
    {
        "title": "Next Greater Element III",
        "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",
        "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",
        "solution_js": "var nextGreaterElement = function(n) {\n\tconst MAX_VALUE = 2 ** 31 - 1;\n\tconst nums = `${n}`.split('');\n\tlet findPos;\n\n\tfor (let index = nums.length - 2; index >= 0; index--) {\n\t\tif (nums[index] < nums[index + 1]) {\n\t\t\tfindPos = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (findPos === undefined) return -1;\n\tfor (let index = nums.length - 1; index >= 0; index--) {\n\t\tif (nums[index] > nums[findPos]) {\n\t\t\t[nums[index], nums[findPos]] = [nums[findPos], nums[index]];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst mantissa = nums.slice(findPos + 1).sort((a, b) => a - b).join('');\n\tconst result = Number(nums.slice(0, findPos + 1).join('') + mantissa);\n\treturn result > MAX_VALUE ? -1 : result;\n};",
        "solution_java": "class Solution {\n    public int nextGreaterElement(int n) {\n        char[] arr = (n + \"\").toCharArray();\n        \n        int i = arr.length - 1;\n        while(i > 0){\n            if(arr[i-1] >= arr[i]){\n                i--;\n            }else{\n                break;\n            }\n        }\n        if(i == 0){\n            return -1;\n        }\n        \n        int idx1 = i-1;\n        \n        int j = arr.length - 1;\n        while(j > idx1){\n            if(arr[j] > arr[idx1]){\n                break;\n            }\n            j--;\n        }\n        \n        //Swapping\n        swap(arr,idx1,j);\n        \n        //sorting\n        int left = idx1+1;\n        int right = arr.length-1;\n        while(left < right){\n            swap(arr,left,right);\n            left++;\n            right--;\n        }\n        \n        String result = new String(arr);\n        long val = Long.parseLong(result);\n        \n        return (val > Integer.MAX_VALUE ? -1 : (int)val);\n        \n    }\n    \n    void swap(char[]arr,int i,int j){\n        char temp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = temp;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int nextGreaterElement(int n) {\n       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};"
    },
    {
        "title": "The Time When the Network Becomes Idle",
        "algo_input": "There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.\n\nAll servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.\n\nThe server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.\n\nAt the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:\n\n\n\tIf it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.\n\tOtherwise, no more resending will occur from this server.\n\n\nThe network becomes idle when there are no messages passing between servers or arriving at servers.\n\nReturn the earliest second starting from which the network becomes idle.\n\n&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",
        "solution_py": "class Solution:\n    def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n\n        #Build Adjency List\n        adjList = defaultdict(list)\n\n        for source, target in edges:\n            adjList[source].append(target)\n            adjList[target].append(source)\n\n        #BFS to get the shortest route from node to master.\n        shortest = {}\n        queue = deque([(0,0)])\n        seen = set()\n        while queue:\n            currPos, currDist = queue.popleft()\n\n            if currPos in seen:\n                continue\n            seen.add(currPos)\n            shortest[currPos] = currDist\n\n            for nei in adjList[currPos]:\n                queue.append((nei, currDist+1))\n\n        #Calculate answer using shortest paths.\n        ans = 0\n        for index in range(1,len(patience)):\n            resendInterval = patience[index]\n\n            #The server will stop sending requests after it's been sent to the master node and back.\n            shutOffTime = (shortest[index] * 2)\n\n            # shutOffTime-1 == Last second the server can send a re-request.\n            lastSecond = shutOffTime-1\n\n            #Calculate the last time a packet is actually resent.\n            lastResentTime = (lastSecond//resendInterval)*resendInterval\n\n            # At the last resent time, the packet still must go through 2 more cycles to the master node and back.\n            lastPacketTime = lastResentTime + shutOffTime\n\n            ans = max(lastPacketTime, ans)\n\n        #Add +1, the current answer is the last time the packet is recieved by the target server (still active).\n        #We must return the first second the network is idle, therefore + 1\n        return ans + 1",
        "solution_js": "/**\n * @param {number[][]} edges\n * @param {number[]} patience\n * @return {number}\n */\nvar networkBecomesIdle = function(edges, patience) {\n  /*\n  Approach:\n  Lets call D is the distance from node to master\n  And last message sent from node is at T\n  Then last message will travel till D+T and network will be idal at D+T+1\n  */  \n    let edgesMap={},minDistanceFromMasterArr=[],ans=0,visited={};\n    for(let i=0;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Maximal Network Rank",
        "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",
        "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",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Pow(x, n)",
        "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",
        "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)",
        "solution_js": "var myPow = function(x, n) {\n    return x**n;\n};",
        "solution_java": "class Solution {\n    public double myPow(double x, int n) {\n        if (n == 0) return 1;\n        if (n == 1) return x;\n        else if (n == -1) return 1 / x;\n        double res = myPow(x, n / 2);\n        if (n % 2 == 0) return res * res;\n        else if (n % 2 == -1) return res * res * (1/x);\n        else return res * res * x;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double myPow(double x, int n) {\n        \n        if(n==0) return 1;      //anything to the power 0 is 1\n        \n        if(x==1 || n==1) return x;  //1 to the power anything = 1 or x to the power 1 = x\n        \n        double ans = 1;\n        \n        long long int a = abs(n);   //since int range is from -2147483648 to 2147483647, so it can't store absolute value of -2147483648\n        \n        if(n<0){    //as 2^(-2) = 1/2^2\n            if(a%2 == 0) ans = 1/myPow(x*x,a/2);\n            else ans = 1/(x * myPow(x,a-1));\n        }\n        else{\n            if(a%2 == 0) ans = myPow(x*x,a/2);\n            else ans = x * myPow(x,a-1);\n        }\n        \n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Game of Life",
        "algo_input": "According to&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",
        "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",
        "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};",
        "solution_java": "class Solution {\n    public void gameOfLife(int[][] board) {\n        int m = board.length, n = board[0].length;\n        int[][] next = new int[m][n];\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                next[i][j] = nextState(board, i, j, m, n);\n            }\n        }\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                board[i][j] = next[i][j];\n            }\n        }\n    }\n\n    public int nextState(int[][] board, int i, int j, int m, int n) {\n        int ones = 0;\n        for (int x = -1; x <=1; x++) {\n            for (int y = -1; y <= 1; y++) {\n                if (x == 0 && y == 0) {\n                    continue;\n                }\n                int a = i + x, b = j + y;\n                if (a >= 0 && a < m) {\n                    if (b >= 0 && b < n) {\n                        ones += board[a][b];\n                    }\n                }\n            }\n        }\n        if (board[i][j] == 0) {\n            return ones == 3 ? 1 : 0;\n        } else {\n            if (ones == 2 || ones == 3) {\n                return 1;\n            } else {\n                return 0;\n            }\n        }\n    }\n}",
        "solution_c": "// Idea: Encode the value into 2-bit value, the first bit is the value of next state, and the second bit is the value of current state\nclass Solution {\npublic:\n    void gameOfLife(vector<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};"
    },
    {
        "title": "Get Maximum in Generated Array",
        "algo_input": "You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:\n\n\n\tnums[0] = 0\n\tnums[1] = 1\n\tnums[2 * i] = nums[i] when 2 &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",
        "solution_py": "class Solution:\n    def getMaximumGenerated(self, n):\n        nums = [0]*(n+2)\n        nums[1] = 1\n        for i in range(2, n+1):\n            nums[i] = nums[i//2] + nums[(i//2)+1] * (i%2)\n    \n        return max(nums[:n+1])",
        "solution_js": "var getMaximumGenerated = function(n) {\n    if (n === 0) return 0;\n    if (n === 1) return 1;\n    let arr = [0, 1];\n    let max = 0;\n    for (let i = 0; i < n; i++) {\n        if (2 <= 2 * i && 2 * i <= n) {\n            arr[2 * i] = arr[i]\n            if (arr[i] > max) max = arr[i];\n        }\n        if (2 <= 2 * i && 2 * i + 1 <= n) {\n            arr[2 * i + 1] = arr[i] + arr[i + 1]\n            if (arr[i] + arr[i + 1] > max) max = arr[i] + arr[i + 1];\n        };\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int getMaximumGenerated(int n) {\n        if(n==0 || n==1) return n;\n\n        int nums[]=new int [n+1];\n\n        nums[0]=0;\n        nums[1]=1;\n        int max=Integer.MIN_VALUE;\n\n        for(int i=2;i<=n;i++){\n            if(i%2==0){\n                nums[i]=nums[i/2];\n            }\n            else{\n                nums[i]=nums[i/2]+nums[i/2 + 1];\n            }\n            max=Math.max(max,nums[i]);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getMaximumGenerated(int n) {\n        // base cases\n        if (n < 2) return n;\n        // support variables\n        int arr[n + 1], m;\n        arr[0] = 0, arr[1] = 1;\n        // building arr\n        for (int i = 2; i <= n; i++) {\n            if (i % 2) arr[i] = arr[i / 2] + arr[i / 2 + 1];\n            else arr[i] = arr[i / 2];\n            // updating m\n            m = max(arr[i], m);\n        }\n        return m;\n    }\n};"
    },
    {
        "title": "Cells with Odd Values in a Matrix",
        "algo_input": "There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.\n\nFor each location indices[i], do both of the following:\n\n\n\tIncrement all the cells on row ri.\n\tIncrement all the cells on column ci.\n\n\nGiven m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.\n\n&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",
        "solution_py": "class Solution:\n    def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:\n        rows, cols = [False] * row, [False] * col\n\n        for index in indices:\n            rows[index[0]] = not rows[index[0]]\n            cols[index[1]] = not cols[index[1]]\n\n        count = 0\n        for i in rows:\n            for j in cols:\n                count += i ^ j\n\n        return count",
        "solution_js": "var oddCells = function(m, n, indices) {\n    const matrix = Array.from(Array(m), () => Array(n).fill(0));\n\n    let res = 0;\n    for (const [r, c] of indices) {\n        for (let i = 0; i < n; i++) {\n            // toggle 0/1 for even/odd\n            // another method: matrix[r][i] = 1 - matrix[r][i]\n            // or: matrix[r][i] = +!matrix[r][i]\n            matrix[r][i] ^= 1;\n            if (matrix[r][i]) res++; else res--;\n        }\n\n        for (let i = 0; i < m; i++) {\n            matrix[i][c] ^= 1;\n            if (matrix[i][c]) res++; else res--;\n        }\n    }\n\n    return res;\n};",
        "solution_java": "// --------------------- Solution 1 ---------------------\nclass Solution {\n    public int oddCells(int m, int n, int[][] indices) {\n        int[][] matrix = new int[m][n];\n        \n        for(int i = 0; i < indices.length; i++) {\n            int row = indices[i][0];\n            int col = indices[i][1];\n            \n            for(int j = 0; j < n; j++) {\n                matrix[row][j]++;\n            }\n            for(int j = 0; j < m; j++) {\n                matrix[j][col]++;\n            }\n        }\n        \n        int counter = 0;\n        for(int i = 0; i < m; i++) {\n            for(int j = 0; j < n; j++) {\n                if(matrix[i][j] % 2 != 0) {\n                    counter++;\n                }\n            }\n        }\n        \n        return counter;\n    }\n}\n\n// --------------------- Solution 2 ---------------------\nclass Solution {\n    public int oddCells(int m, int n, int[][] indices) {\n        int[] row = new int[m];\n        int[] col = new int[n];\n        \n        for(int i = 0; i < indices.length; i++) {\n            row[indices[i][0]]++;\n            col[indices[i][1]]++;\n        }\n        \n        int counter = 0;\n        for(int i : row) {\n            for(int j : col) {\n                counter += (i + j) % 2 == 0 ? 0 : 1;\n            }\n        }\n        \n        return counter;\n    }\n}",
        "solution_c": "static int x = []() {\nstd::ios::sync_with_stdio(false);\ncin.tie(nullptr);\nreturn 0; }();\n\nclass Solution { // tc: O(n+m) & sc: O(n+m)\npublic:\n    int oddCells(int n, int m, vector<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};"
    },
    {
        "title": "Largest Sum of Averages",
        "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",
        "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]",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Predict the Winner",
        "algo_input": "You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.\n\nPlayer 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.\n\nReturn true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.\n\n&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",
        "solution_py": "class Solution:\n    def PredictTheWinner(self, nums: List[int]) -> bool:\n        dp = [[-1] * len(nums) for _ in nums]\n        def get_score(i: int, j: int) -> int:\n            if i == j: \n                dp[i][j] = 0\n                return dp[i][j]\n            if i == j - 1:\n                dp[i][j] = nums[j] if nums[i] > nums[j] else nums[i]\n                return dp[i][j]\n            if dp[i][j] != -1:\n                return dp[i][j]\n\n            y1 = get_score(i + 1, j - 1)\n            y2 = get_score(i + 2, j)\n            y3 = get_score(i, j - 2)\n            res_y1 = y1 + nums[j] if y1 + nums[j] > y2 + nums[i+1] else y2 + nums[i+1]\n            res_y2 = y1 + nums[i] if y1 + nums[i] > y3 + nums[j-1] else y3 + nums[j-1]\n\n            dp[i][j] = min(res_y1, res_y2)\n            return dp[i][j]       \n                     \n        y = get_score(0, len(nums) - 1)\n        x = sum(nums) - y\n\n        return 0 if y > x else 1",
        "solution_js": "var PredictTheWinner = function(nums) {\n    const n = nums.length;\n    const dp = [];\n\n    for (let i = 0; i < n; i++) {\n        dp[i] = new Array(n).fill(0);\n        dp[i][i] = nums[i];\n    }\n\n    for (let len = 2; len <= n; len++) {\n        for (let start = 0; start < n - len + 1; start++) {\n            const end = start + len - 1;\n            dp[start][end] = Math.max(nums[start] - dp[start + 1][end], nums[end] - dp[start][end - 1]);\n        }\n    }\n\n    return dp[0][n - 1] >= 0;\n};",
        "solution_java": "class Solution {\n    public boolean PredictTheWinner(int[] nums) {\n        return predictTheWinner(nums, 0, nums.length-1,true,0, 0);\n    }\n   private boolean predictTheWinner(int[] nums, int start,int  end, boolean isP1Turn, long p1Score, long p2Score){\n        if(start > end){\n            return p1Score >= p2Score;\n        }\n\n        boolean firstTry;\n        boolean secondTry;\n        if(isP1Turn){\n             firstTry = predictTheWinner(nums, start +1 , end, false, p1Score + nums[start], p2Score);\n             secondTry = predictTheWinner(nums, start, end-1, false, p1Score + nums[end], p2Score);\n\n        }else{\n            firstTry = predictTheWinner(nums, start +1 , end, true, p1Score, p2Score + nums[start]);\n            secondTry = predictTheWinner(nums, start, end-1, true, p1Score , p2Score + nums[end]);\n\n        }\n        return isP1Turn ? (firstTry || secondTry) : (firstTry && secondTry);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool PredictTheWinner(vector<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};"
    },
    {
        "title": "Maximum Element After Decreasing and Rearranging",
        "algo_input": "You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:\n\n\n\tThe value of the first element in arr must be 1.\n\tThe absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) &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",
        "solution_py": "class Solution:\n    def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\t\tcounter = collections.Counter(arr)\n        available = sum(n > len(arr) for n in arr)\n        i = ans = len(arr)\n        while i > 0:\n            # This number is not in arr\n            if not counter[i]:\n                # Use another number to fill in its place. If we cannot, we have to decrease our max\n                if available: available -= 1               \n                else: ans -= 1\n            # Other occurences can be used for future.\n            else:\n                available += counter[i] - 1\n            i -= 1\n        return ans",
        "solution_js": "var maximumElementAfterDecrementingAndRearranging = function(arr) {\n    if (!arr.length) return 0\n    arr.sort((a, b) => a - b)\n    arr[0] = 1\n    for (let i = 1; i < arr.length; i++) {\n        if (Math.abs(arr[i] - arr[i - 1]) > 1) arr[i] = arr[i - 1] + 1\n    }\n    return arr.at(-1)\n};",
        "solution_java": "class Solution {\n    public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n      Arrays.sort(arr);\n      arr[0] = 1;\n      for(int i = 1;i<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}",
        "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};"
    },
    {
        "title": "Permutations",
        "algo_input": "Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.\n\n&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",
        "solution_py": "class Solution:\n    def permute(self, nums: List[int]) -> List[List[int]]:\n        return list(permutations(nums))",
        "solution_js": "var permute = function(nums) {\n    const output = [];\n    \n    const backtracking = (current, remaining) => {\n        if (!remaining.length) return output.push(current);\n\n        for (let i = 0; i < remaining.length; i++) {\n            const newCurrent = [...current];\n            const newRemaining = [...remaining];\n\n            newCurrent.push(newRemaining[i]);\n            newRemaining.splice(i, 1);\n\n            backtracking(newCurrent, newRemaining);\n        }\n    }\n    \n    backtracking([], nums);\n\n    return output;\n};",
        "solution_java": "class Solution {\n    List<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}",
        "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};"
    },
    {
        "title": "H-Index II",
        "algo_input": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations&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",
        "solution_py": "import bisect\n\nclass Solution:\n    def hIndex(self, citations: List[int]) -> int:\n        n = len(citations)\n        for h in range(n, -1, -1):\n            if h <= n - bisect.bisect_left(citations, h):\n                return h",
        "solution_js": "/**\n * The binary search solution.\n * \n * Time Complexity:  O(log(n))\n * Space Complexity: O(1)\n * \n * @param {number[]} citations\n * @return {number}\n */\nvar hIndex = function(citations) {\n\tconst n = citations.length\n\n\tlet l = 0\n\tlet r = n - 1\n\n\twhile (l <= r) {\n\t\tconst m = Math.floor((l + r) / 2)\n\n\t\tif (citations[m] > n - m) {\n\t\t\tr = m - 1\n\t\t\tcontinue\n\t\t}\n\n\t\tif (citations[m] < n - m) {\n\t\t\tl = m + 1\n\t\t\tcontinue\n\t\t}\n\n\t\treturn citations[m]\n\t}\n\n\treturn n - l\n}",
        "solution_java": "class Solution {\n    public int hIndex(int[] citations) {\n        int n=citations.length;\n        int res=0;\n        for(int i=0;i<n;i++)\n        {\n            if(citations[i]>=n-i)\n            {\n                return n-i;\n            }\n        }\n        return res;\n    }\n}",
        "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};"
    },
    {
        "title": "Clone Graph",
        "algo_input": "Given a reference of a node in a connected undirected graph.\n\nReturn a deep copy (clone) of the graph.\n\nEach node in the graph contains a value (int) and a list (List[Node]) of its neighbors.\n\nclass Node {\n    public int val;\n    public List&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",
        "solution_py": "    def cloneGraph(self, node: 'Node') -> 'Node':\n        \n        if node == None:\n            return None\n        \n        new_node = Node(node.val, [])\n        \n        visited = set()\n        \n        q = [[node, new_node]]\n        visited.add(node.val)\n        \n        adj_map = {}\n        \n        adj_map[node] = new_node\n        \n        while len(q) != 0:\n            \n            curr = q.pop(0)\n            \n            \n            for n in curr[0].neighbors:\n                \n                # if n.val not in visited:\n                if n not in adj_map and n is not None:\n                    new = Node(n.val, [])\n                    curr[1].neighbors.append(new)\n                    adj_map[n] = new\n                else:\n                    curr[1].neighbors.append(adj_map[n])\n                    \n                if n.val not in visited:\n                    q.append([n, adj_map[n]])\n                    visited.add(n.val) \n        \n        \n        return new_node",
        "solution_js": "var cloneGraph = function(node) {\n    if(!node)\n        return node;\n    \n    let queue = [node];\n    \n    let map = new Map();\n    \n\t//1. Create new Copy of each node and save in Map\n    while(queue.length) {\n        let nextQueue = [];\n        \n        for(let i = 0; i < queue.length; i++) {\n            let n = queue[i];\n            \n            let newN = new Node(n.val);\n            \n            if(!map.has(n)) {\n                map.set(n, newN);\n            }\n            \n            let nei = n.neighbors;\n            \n            for(let j = 0; j < nei.length; j++) {\n                if(map.has(nei[j]))\n                    continue;\n                nextQueue.push(nei[j]); \n            }\n        }\n        \n        queue = nextQueue;\n    }\n    \n    queue = [node];\n    \n    let seen = new Set();\n    seen.add(node);\n    \n\t//2. Run BFS again and populate neighbors in new node created in step 1.\n    while(queue.length) {\n        let nextQueue = [];\n        \n        for(let i = 0; i < queue.length; i++) {\n            let n = queue[i];\n            \n            let nei = n.neighbors;\n            let newn = map.get(n);\n            \n            for(let j = 0; j < nei.length; j++) {\n                newn.neighbors.push(map.get(nei[j]));\n                \n                if(!seen.has(nei[j])) {\n                    nextQueue.push(nei[j]); \n                    seen.add(nei[j]);\n                }\n            }\n        }\n        \n        queue = nextQueue;\n    }\n    \n    return map.get(node);\n};",
        "solution_java": "/*\n// Definition for a Node.\nclass Node {\n    public int val;\n    public List<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}",
        "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};"
    },
    {
        "title": "Find K Closest Elements",
        "algo_input": "Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.\n\nAn integer a is closer to x than an integer b if:\n\n\n\t|a - x| &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",
        "solution_py": "class Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        \n        def sorted_distance(value, static_input = x):\n            return abs(value - static_input)\n        \n        distances = []\n        result = []\n        heapq.heapify(distances)\n        \n        for l,v in enumerate(arr):\n            distances.append((l, sorted_distance(value = v)))\n        \n        for i in heapq.nsmallest(k, distances, key = lambda x: x[1]):\n            result.append(arr[i[0]])\n        \n        result.sort()\n        return result\n            \n            ",
        "solution_js": "var findClosestElements = function(arr, k, x) {\n\tconst result = [...arr];\n\n\twhile (result.length > k) {\n\t\tconst start = result[0];\n\t\tconst end = result.at(-1);\n\n\t\tx - start <= end - x \n\t\t\t? result.pop() \n\t\t\t: result.shift();\n\t}\n\treturn result;\n};",
        "solution_java": "class Solution {\npublic List<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}",
        "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};"
    },
    {
        "title": "Heaters",
        "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",
        "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)",
        "solution_js": "var findRadius = function(houses, heaters) {\n\thouses.sort((a, b) => a - b);\n\theaters.sort((a, b) => a - b);\n\tlet heaterPos = 0;\n\tconst getRadius = (house, pos) => Math.abs(heaters[pos] - house);\n\n\treturn houses.reduce((radius, house) => {\n\t\twhile (\n\t\t\theaterPos < heaters.length &&\n\t\t\tgetRadius(house, heaterPos) >= \n\t\t\tgetRadius(house, heaterPos + 1)\n\t\t) heaterPos += 1;\n\n\t\tconst currentRadius = getRadius(house, heaterPos);\n\t\treturn Math.max(radius, currentRadius);\n\t}, 0);\n};",
        "solution_java": "class Solution {\n  public boolean can(int r, int[] houses, int[] heaters) {\n    int prevHouseIdx = -1;\n    for(int i = 0; i < heaters.length; i++) {\n      int from = heaters[i]-r;\n      int to   = heaters[i]+r;\n      for(int j = prevHouseIdx+1; j < houses.length; j++){\n        if(houses[j]<=to && houses[j]>=from){\n          prevHouseIdx++;\n        }\n        else break;\n      }\n      if(prevHouseIdx >= houses.length-1)return true;\n    }\n    return prevHouseIdx>= houses.length-1;\n  }\n  public int findRadius(int[] houses, int[] heaters) {\n    Arrays.sort(houses);\n    Arrays.sort(heaters);\n    int lo = 0, hi = 1000000004;\n    int mid, ans = hi;\n    while(lo <= hi) {\n      mid = (lo+hi)/2;\n      if(can(mid, houses, heaters)){\n        ans = mid;\n        hi = mid - 1;\n      } else lo = mid + 1;\n    }\n    return ans;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    //we will assign each house to its closest heater in position(by taking the minimum\n    //of the distance between the two closest heaters to the house) and then store the maximum\n    //of these differences(since we want to have the same standard radius)\n    int findRadius(vector<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};"
    },
    {
        "title": "Minimum Length of String After Deleting Similar Ends",
        "algo_input": "Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:\n\n\n\tPick a non-empty prefix from the string s where all the characters in the prefix are equal.\n\tPick a non-empty suffix from the string s where all the characters in this suffix are equal.\n\tThe prefix and the suffix should not intersect at any index.\n\tThe characters from the prefix and suffix must be the same.\n\tDelete both the prefix and the suffix.\n\n\nReturn the minimum length of s after performing the above operation any number of times (possibly zero times).\n\n&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",
        "solution_py": "class Solution:\n    def minimumLength(self, s: str) -> int:\n        while(len(s)>1 and s[0]==s[-1]):\n            s=s.strip(s[0])\n        else:\n            return len(s)",
        "solution_js": "var minimumLength = function(s) {\n    const n = s.length;\n\n    let left = 0;\n    let right = n - 1;\n\n    while (left < right) {\n        if (s.charAt(left) != s.charAt(right)) break;\n\n        left++;\n        right--;\n\n        while (left <= right && s.charAt(left - 1) == s.charAt(left)) left++;\n        while (left <= right && s.charAt(right) == s.charAt(right + 1)) right--;\n    }\n\n    return right - left + 1;\n};",
        "solution_java": "class Solution {\n    public int minimumLength(String s) {\n        int length = s.length();\n        char[] chars = s.toCharArray();\n        for(int left = 0,right = chars.length-1;left < right;){\n            if(chars[left] == chars[right]){\n                char c = chars[left];\n             while(left < right && chars[left] == c ){\n                    left++;\n                    length--;\n\n                }\n\n                while (right >= left && chars[right] == c){\n                    right--;\n                    length--;\n\n                }\n            }else {\n                break;\n            }\n        }\n        return length;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumLength(string s) {\n        int i=0,j=s.length()-1;\n        while(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};"
    },
    {
        "title": "Find N Unique Integers Sum up to Zero",
        "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",
        "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))",
        "solution_js": "var sumZero = function(n) {\n  var num = Math.floor(n/2); \n  var res = [];\n\n  for(var i=1;i<=num;i++){\n      res.push(i,-i)\n     } \n\n  if(n%2!==0){\n    res.push(0)\n  }\n  \n  return res \n}",
        "solution_java": "class Solution {\n    public int[] sumZero(int n) {\n        int[] ans = new int[n];\n        int j=0;\n        \n        for(int i=1;i<=n/2;i++)\n        {\n            ans[j] = i;\n            j++;\n        }\n        for(int i=1;i<=n/2;i++)\n        {\n            ans[j] = -i;\n            j++;\n        }\n        if(n%2!=0) ans[j] = 0;\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<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};"
    },
    {
        "title": "Minimize Hamming Distance After Swap Operations",
        "algo_input": "You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.\n\nThe Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 &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",
        "solution_py": "class UnionFind:\n    def __init__(self, n):\n        self.roots = [i for i in range(n)]\n\n    def find(self, v):\n        if self.roots[v] != v:\n            self.roots[v] = self.find(self.roots[v])\n\n        return self.roots[v]\n\n    def union(self, u, v):\n        self.roots[self.find(u)] = self.find(v)\n\nclass Solution:\n    def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n        uf = UnionFind(len(source))\n        for idx1, idx2 in allowedSwaps:\n            uf.union(idx1, idx2)\n\n        m = collections.defaultdict(set)\n        for i in range(len(source)):\n            m[uf.find(i)].add(i)\n\n        res = 0\n        for indices in m.values():\n            freq = {}\n            for i in indices:\n                freq[source[i]] = freq.get(source[i], 0)+1\n                freq[target[i]] = freq.get(target[i], 0)-1\n            res += sum(val for val in freq.values() if val > 0)\n\n        return res",
        "solution_js": "var minimumHammingDistance = function(source, target, allowedSwaps) {\n    const n = source.length;\n    \n    const uf = {};\n    const sizes = {};\n    const members = {};\n    \n    // initial setup\n    for (let i = 0; i < n; i++) {\n        const srcNum = source[i];\n        \n        uf[i] = i;\n        sizes[i] = 1;\n        members[i] = new Map();\n        members[i].set(srcNum, 1);\n    }\n    \n    function find(x) {\n        if (uf[x] != x) uf[x] = find(uf[x]);\n        return uf[x];\n    }\n    \n    function union(x, y) {\n        const rootX = find(x);\n        const rootY = find(y);\n        \n        if (rootX === rootY) return;\n        \n        if (sizes[rootX] > sizes[rootY]) {\n            uf[rootY] = rootX;\n            sizes[rootX] += sizes[rootY];\n            \n            for (const [num, count] of members[rootY]) {\n                if (!members[rootX].has(num)) members[rootX].set(num, 0);\n                members[rootX].set(num, members[rootX].get(num) + count);\n            }\n        }\n        else {\n            uf[rootX] = rootY;\n            sizes[rootY] += sizes[rootX];\n\n            const num = source[x];\n\n            for (const [num, count] of members[rootX]) {\n                if (!members[rootY].has(num)) members[rootY].set(num, 0);\n                members[rootY].set(num, members[rootY].get(num) + count);\n            }\n        }\n    }\n    \n    for (const [idx1, idx2] of allowedSwaps) {\n        union(idx1, idx2);\n    }\n    \n    let mismatches = 0;\n    \n    for (let i = 0; i < n; i++) {\n        const srcNum = source[i];\n        const tarNum = target[i];\n        \n        const group = find(i);\n        \n        if (members[group].has(tarNum)) {\n            members[group].set(tarNum, members[group].get(tarNum) - 1);\n            if (members[group].get(tarNum) === 0) members[group].delete(tarNum);\n        }   \n        else {\n            mismatches++;\n        }\n    }\n    \n    return mismatches;\n};",
        "solution_java": "class Solution {\n    public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {\n        int minHamming = 0;\n        UnionFind uf = new UnionFind(source.length);\n        for (int [] swap : allowedSwaps) {\n            int firstIndex = swap[0];\n            int secondIndex = swap[1];\n           // int firstParent = uf.find(firstIndex);\n           // int secondParent = uf.find(secondIndex);\n           // if (firstParent != secondParent)\n           //     uf.parent[firstParent] = secondParent;\n\t\t   uf.union(firstIndex, secondIndex);\n        }\n        Map<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}",
        "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};"
    },
    {
        "title": "Valid Triangle Number",
        "algo_input": "Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.\n\n&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",
        "solution_py": "class Solution {\n    public int triangleNumber(int[] nums) {\n        int n = nums.length;\n        Arrays.sort(nums);\n        int count =0;\n        for(int k = n-1; k>=2; k--)\n        {\n            int i = 0;\n            int j = k-1;\n            while(i < j)\n            {\n                int sum = nums[i] +nums[j];\n                if(sum > nums[k])\n                {\n                    count += j-i;\n                    j--;\n                }\n                else\n                {\n                    i++;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_js": "class Solution {\n    public int triangleNumber(int[] nums) {\n        int n = nums.length;\n        Arrays.sort(nums);\n        int count =0;\n        for(int k = n-1; k>=2; k--)\n        {\n            int i = 0;\n            int j = k-1;\n            while(i < j)\n            {\n                int sum = nums[i] +nums[j];\n                if(sum > nums[k])\n                {\n                    count += j-i;\n                    j--;\n                }\n                else\n                {\n                    i++;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_java": "class Solution {\n    public int triangleNumber(int[] nums) {\n        int n = nums.length;\n        Arrays.sort(nums);\n        int count =0;\n        for(int k = n-1; k>=2; k--)\n        {\n            int i = 0;\n            int j = k-1;\n            while(i < j)\n            {\n                int sum = nums[i] +nums[j];\n                if(sum > nums[k])\n                {\n                    count += j-i;\n                    j--;\n                }\n                else\n                {\n                    i++;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\n    public int triangleNumber(int[] nums) {\n        int n = nums.length;\n        Arrays.sort(nums);\n        int count =0;\n        for(int k = n-1; k>=2; k--)\n        {\n            int i = 0;\n            int j = k-1;\n            while(i < j)\n            {\n                int sum = nums[i] +nums[j];\n                if(sum > nums[k])\n                {\n                    count += j-i;\n                    j--;\n                }\n                else\n                {\n                    i++;\n                }\n            }\n        }\n        return count;\n    }\n}"
    },
    {
        "title": "Design Authentication Manager",
        "algo_input": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.\n\nImplement the AuthenticationManager class:\n\n\n\tAuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.\n\tgenerate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.\n\trenew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.\n\tcountUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.\n\n\nNote that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.\n\n&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",
        "solution_py": "class AuthenticationManager(object):\n\n    def __init__(self, timeToLive):\n        self.token = dict()\n        self.time = timeToLive # store timeToLive and create dictionary\n\n    def generate(self, tokenId, currentTime):\n        self.token[tokenId] = currentTime # store tokenId with currentTime\n\n    def renew(self, tokenId, currentTime):\n        limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n        if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n            self.token[tokenId] = currentTime\n\n    def countUnexpiredTokens(self, currentTime):\n        limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n        c = 0\n        for i in self.token:\n            if self.token[i]>limit: # count unexpired tokens\n                c+=1\n        return c",
        "solution_js": "// O(n)\nvar AuthenticationManager = function(timeToLive) {\n    this.ttl = timeToLive;\n    this.map = {};\n};\nAuthenticationManager.prototype.generate = function(tokenId, currentTime) {\n    this.map[tokenId] = currentTime + this.ttl;\n};\nAuthenticationManager.prototype.renew = function(tokenId, currentTime) {\n    let curr = this.map[tokenId];\n    if (curr > currentTime) {\n        this.generate(tokenId, currentTime);\n    }\n};\nAuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {\n    return Object.keys(this.map).filter(key => this.map[key] > currentTime).length;\n};",
        "solution_java": "class AuthenticationManager {\n    private int ttl;\n    private Map<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}",
        "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};"
    },
    {
        "title": "Minimum Operations to Make the Array Alternating",
        "algo_input": "You are given a 0-indexed array nums consisting of n positive integers.\n\nThe array nums is called alternating if:\n\n\n\tnums[i - 2] == nums[i], where 2 &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",
        "solution_py": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        n = len(nums)\n        odd, even = defaultdict(int), defaultdict(int)\n        for i in range(n):\n            if i % 2 == 0:\n                even[nums[i]] += 1\n            else:\n                odd[nums[i]] += 1\n        topEven, secondEven = (None, 0), (None, 0)\n        for num in even:\n            if even[num] > topEven[1]:\n                topEven, secondEven = (num, even[num]), topEven\n            elif even[num] > secondEven[1]:\n                secondEven = (num, even[num])\n        topOdd, secondOdd = (None, 0), (None, 0)\n        for num in odd:\n            if odd[num] > topOdd[1]:\n                topOdd, secondOdd = (num, odd[num]), topOdd\n            elif odd[num] > secondOdd[1]:\n                secondOdd = (num, odd[num])\n        if topOdd[0] != topEven[0]:\n            return n - topOdd[1] - topEven[1]\n        else:\n            return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\n\nvar minimumOperations = function(nums) {\n    let countOddId = {}    \n    let countEvenId = {}\n    if(nums.length === 1) return 0\n    if(nums.length === 2 && nums[0] === nums[1]) {\n        return 1\n    }\n    nums.forEach((n, i) => {\n        if(i%2) {\n            if(!countOddId[n]) {\n                countOddId[n] = 1;\n            } else {\n                countOddId[n]++\n            }\n        } else {\n            if(!countEvenId[n]) {\n                countEvenId[n] = 1;\n            } else {\n                countEvenId[n]++\n            }\n        }\n    })\n    \n    const sortedEven = Object.entries(countEvenId).sort((a, b) => {\n        return  b[1] - a[1]\n    })\n\n    const sortedOdd = Object.entries(countOddId).sort((a, b) => {\n        return  b[1] - a[1]\n    })\n\n    if(sortedEven[0][0] === sortedOdd[0][0]) {\n        let maxFirst =0;\n        let maxSec =0;\n\n        if(sortedEven.length === 1) {\n            maxFirst = sortedEven[0][1];\n            maxSec = sortedOdd[1]? sortedOdd[1][1] : 0;\n            return  nums.length - (maxFirst + maxSec)  \n        } \n        \n        if(sortedOdd.length === 1) {\n            maxFirst = sortedOdd[0][1];\n            maxSec = sortedEven[1] ? sortedEven[1][1] : 0;\n            return  nums.length - (maxFirst + maxSec)  \n        }\n        if(sortedEven[0][1] >= sortedOdd[0][1] && sortedEven[1][1] <= sortedOdd[1][1]) {\n            maxFirst = sortedEven[0][1]\n            maxSec = sortedOdd[1][1]\n            return  nums.length - (maxFirst + maxSec)  \n        } else {\n            maxFirst = sortedOdd[0][1]\n            maxSec = sortedEven[1][1]\n            return  nums.length - (maxFirst + maxSec)  \n        }\n    } else {\n        return nums.length - (sortedEven[0][1] + sortedOdd[0][1])\n    }\n\n};",
        "solution_java": "class Solution {\n    public int minimumOperations(int[] nums) {\n        int freq[][] = new int[100005][2];\n        int i, j, k, ans=0;\n        for(i = 0; i < nums.length; i++) {\n    \t\t\tfreq[nums[i]][i&1]++;\n    \t\t}\n    \t\t\n    \t\tfor(i = 1, j=k=0; i <= 100000; i++) {\n\t\t\t// Add the maximum frequency of odd indexes to maximum frequency even indexes \n\t\t    //and vice versa, it will give us how many elements we don't need to change. \n    \t\tans = Math.max(ans, Math.max(freq[i][0] + k, freq[i][1] + j));\n            j = Math.max(j, freq[i][0]);\n            k = Math.max(k, freq[i][1]);\n        }\n        return nums.length - ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumOperations(vector<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};"
    },
    {
        "title": "Valid Mountain Array",
        "algo_input": "Given an array of integers arr, return true if and only if it is a valid mountain array.\n\nRecall that arr is a mountain array if and only if:\n\n\n\tarr.length &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",
        "solution_py": "class Solution:\n    def validMountainArray(self, arr: List[int]) -> bool:\n        if len(arr) < 3:\n            return False\n        for i in range(1,len(arr)):\n            if arr[i] <= arr[i-1]:\n                if i==1:\n                    return False\n                break\n\n        for j in range(i,len(arr)):\n            if arr[j] >= arr[j-1]:\n                return False\n        return True",
        "solution_js": "var validMountainArray = function(arr) {\n  let index = 0, length = arr.length;\n  //find the peak\n    while(index < length && arr[index] < arr[index + 1])index++\n  //edge cases\n    if(index === 0 || index === length - 1) return false;\n  //check if starting from peak to end of arr is descending order\n    \n    while(index < length && arr[index] > arr[index + 1])index++\n    \n    return index === length - 1;\n};",
        "solution_java": "class Solution {\n    public boolean validMountainArray(int[] arr) {\n        // edge case\n        if(arr.length < 3) return false;\n        // keep 2 pointers\n        int i=0;\n        int j=arr.length-1;\n        // use i pointer to iterate through steep increase from LHS\n        while(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}",
        "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};****"
    },
    {
        "title": "Binary Tree Cameras",
        "algo_input": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.\n\nReturn the minimum number of cameras needed to monitor all nodes of the tree.\n\n&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",
        "solution_py": "import itertools\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def minCameraHelper(self, root: Optional[TreeNode]) -> (int, int):\n        # Return 3 things:\n        # cam, uncam, uncov\n        # cam(era) is best score for valid tree with camera at root\n        # uncam(era) is best score for valid tree without camera at root\n        # uncov(ered) is best score for invalid tree, where the only invalidity (i.e. the only uncovered node) is the root node\n        \n        # Note: maxint (float(\"inf\")) is used to signify situations that don't make sense or can't happen.\n        # Anywhere there is a float(\"inf\"), you can safely replace that with a 1 as 1 is as bad or worse than worst practical,\n        # but I stick with maxint to highlight the nonsensical cases for the reader!\n        \n        if not root.left and not root.right:\n            # base case: leaf\n            # Note: \"Uncam\" setting doesn't make much sense (a leaf with no parents can either have a camera or be uncovered,\n            #       but not covered with no camera)\n            return 1, float(\"inf\"), 0\n        \n        if root.left:\n            left_cam, left_uncam, left_uncov = self.minCameraHelper(root.left)\n        else:\n            # base case: empty child\n            # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n            left_cam, left_uncam, left_uncov = float(\"inf\"), 0, 0\n            \n        if root.right:\n            right_cam, right_uncam, right_uncov = self.minCameraHelper(root.right)\n        else:\n            # base case: empty child\n            # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n            right_cam, right_uncam, right_uncov = float(\"inf\"), 0, 0\n            \n        # Get the possible combinations for each setting    \n        cam_poss = itertools.product([left_cam, left_uncam, left_uncov], [right_cam, right_uncam, right_uncov])\n        uncam_poss = [(left_cam, right_cam), (left_uncam, right_cam), (left_cam, right_uncam)]\n        uncov_poss = [(left_uncam, right_uncam)]\n        \n        # Compute costs for each setting\n        cam = min([x + y for x, y in cam_poss]) + 1\n        uncam = min([x + y for x, y in uncam_poss])\n        uncov = min([x + y for x, y in uncov_poss])\n        \n        return cam, uncam, uncov\n                    \n    def minCameraCover(self, root: Optional[TreeNode]) -> int:\n        cam, uncam, _ = self.minCameraHelper(root)\n        return min(cam, uncam)",
        "solution_js": "var minCameraCover = function(root) {\n    let cam = 0;\n    // 0 --> No covered\n    // 1 --> covered by camera\n    // 2 --> has camera\n    function dfs(root) {\n        if(root === null) return 1;\n\n        const left = dfs(root.left);\n        const right = dfs(root.right);\n\n        if(left === 0 || right === 0) { // child required a camera to covered\n            cam++;\n            return 2;\n        } else if(left === 2 || right === 2) { // child has camera so i am covered\n            return 1;\n        } else { // child is covered but don't have camera,So i want camera\n            return 0;\n        }\n    }\n\n    const ans = dfs(root);\n\n    if(ans === 0) ++cam;\n\n    return cam;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    private int count = 0;\n    public int minCameraCover(TreeNode root) {\n        if(helper(root) == -1)\n            count++;\n        return count;\n    }\n    \n    //post order\n    //0 - have camera\n    //1 - covered\n    //-1 - not covered\n    public int helper(TreeNode root) {\n        if(root == null)\n            return 1;\n        int left = helper(root.left);\n        int right = helper(root.right);\n        if(left == -1 || right == -1) {\n            count++;\n            return 0;\n        }\n        if(left == 0 || right == 0)\n            return 1;\n        \n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    map<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};"
    },
    {
        "title": "Check if Word Equals Summation of Two Words",
        "algo_input": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -&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",
        "solution_py": "class Solution:\n    def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n        x=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n        a=\"\"\n        for i in firstWord:\n            a=a+str(x.index(i))\n        \n        b=\"\"\n        for i in secondWord:\n            b=b+str(x.index(i))\n\n        c=\"\"\n        for i in targetWord:\n            c=c+str(x.index(i))\n        if int(a)+int(b)==int(c):\n            return True\n        return False",
        "solution_js": "var isSumEqual = function(firstWord, secondWord, targetWord) {\n    let obj = {\n        'a' : '0',\n        \"b\" : '1',\n        \"c\" : '2',\n        \"d\" : '3',\n        \"e\" : '4',\n        'f' : '5',\n        'g' : '6',\n        'h' : '7',\n        'i' : '8', \n        \"j\" : '9'\n    }\n    let first = \"\", second = \"\", target = \"\"\n    for(let char of firstWord){\n        first += obj[char]\n    }\n    for(let char of secondWord){\n        second += obj[char]\n    }\n    for(let char of targetWord){\n        target += obj[char]\n    }\n    return parseInt(first) + parseInt(second) === parseInt(target)\n};",
        "solution_java": "class Solution {\n    public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {\n        int sumfirst=0, sumsecond=0, sumtarget=0;\n        for(char c : firstWord.toCharArray()){\n            sumfirst += c-'a';\n            sumfirst *= 10;\n        }\n        for(char c : secondWord.toCharArray()){\n            sumsecond += c-'a';\n            sumsecond *= 10;\n        }\n        for(char c : targetWord.toCharArray()){\n            sumtarget += c-'a';\n            sumtarget *= 10;\n        }\n       \n        return (sumfirst + sumsecond) == sumtarget;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSumEqual(string firstWord, string secondWord, string targetWord) {\n        int first=0,second=0,target=0;\n        for(int i=0;i<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};"
    },
    {
        "title": "Satisfiability of Equality Equations",
        "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",
        "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",
        "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};",
        "solution_java": "class Solution {\n    static int par[];\n\n    public static int findPar(int u) {\n        return par[u] == u ? u : (par[u] = findPar(par[u]));\n    }\n\n    public boolean equationsPossible(String[] equations) {\n        par = new int[26];\n        for (int i = 0; i < 26; i++) {\n            par[i] = i;\n        }\n\n        /*First perform all the merging operation*/\n        for (String s : equations) {\n            int c1 = s.charAt(0) - 'a';\n            int c2 = s.charAt(3) - 'a';\n            char sign = s.charAt(1);\n\n            int p1 = findPar(c1);\n            int p2 = findPar(c2);\n\n            if (sign == '=') {\n                if (p1 != p2) {\n                    if (p1 < p2) {\n                        par[p2] = p1;\n                    } else {\n                        par[p1] = p2;\n                    }\n                }\n            } \n        }\n\n        /*Now traverse on the whole string and search for any != operation and check if there parents are same*/\n        for (String s : equations) {\n            int c1 = s.charAt(0) - 'a';\n            int c2 = s.charAt(3) - 'a';\n            char sign = s.charAt(1);\n\n            int p1 = findPar(c1);\n            int p2 = findPar(c2);\n\n            if (sign == '!') {\n                if (p1 == p2) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:    \n    bool equationsPossible(vector<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};"
    },
    {
        "title": "Fraction to Recurring Decimal",
        "algo_input": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\n\nIf the fractional part is repeating, enclose the repeating part in parentheses.\n\nIf multiple answers are possible, return any of them.\n\nIt is guaranteed that the length of the answer string is less than 104 for all the given inputs.\n\n&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",
        "solution_py": "from collections import defaultdict\nclass Solution:\n    def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n        sign = \"\" if numerator*denominator >= 0 else \"-\"\n        numerator, denominator = abs(numerator), abs(denominator)\n        a = numerator//denominator\n        numerator %= denominator\n        if not numerator: return sign+str(a)\n        fractions = []\n        index = defaultdict(int)\n        while 10*numerator not in index:\n            numerator *= 10\n            index[numerator] = len(fractions)\n            fractions.append(str(numerator//denominator))\n            numerator %= denominator\n        i = index[10*numerator]\n        return sign+str(a)+\".\"+\"\".join(fractions[:i])+\"(\"+\"\".join(fractions[i:])+\")\" if numerator else sign+str(a)+\".\"+\"\".join(fractions[:i])",
        "solution_js": "var fractionToDecimal = function(numerator, denominator) {\n    if(numerator == 0) return '0'\n    let result = ''\n    if(numerator*denominator <0){\n        result += '-'\n    }\n    \n    let dividend = Math.abs(numerator)\n    let divisor = Math.abs(denominator)\n    result += Math.floor(dividend/divisor).toString()\n    \n    let remainder = dividend % divisor\n    if(remainder == 0) return result\n    \n    result += '.'\n    \n    let map1 = new Map()\n    while(remainder != 0){\n        if(map1.has(remainder)){\n            let i = map1.get(remainder)\n            result = result.slice(0, i) + '(' + result.slice(i) + ')'\n            break;\n        }\n        map1.set(remainder, result.length)\n        remainder *= 10\n        result += Math.floor(remainder/divisor).toString()\n        remainder %= divisor\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public String fractionToDecimal(int numerator, int denominator) {\n        if(numerator == 0){\n            return  \"0\";\n        }\n        \n        StringBuilder sb = new StringBuilder(\"\");\n        if(numerator<0 && denominator>0 || numerator>0 && denominator<0){\n            sb.append(\"-\");\n        }\n        \n        long divisor = Math.abs((long)numerator);\n        long dividend = Math.abs((long)denominator);\n        long remainder = divisor % dividend;\n        sb.append(divisor / dividend);\n        \n        if(remainder == 0){\n            return sb.toString();\n        }\n        sb.append(\".\");\n        HashMap<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}",
        "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};"
    },
    {
        "title": "Factorial Trailing Zeroes",
        "algo_input": "Given an integer n, return the number of trailing zeroes in n!.\n\nNote that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.\n\n&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",
        "solution_py": "class Solution:\n    def trailingZeroes(self, n: int) -> int:\n        res = 0\n        for i in range(2, n+1):\n            while i > 0 and i%5 == 0:\n                i //= 5\n                res += 1\n        return res",
        "solution_js": "var trailingZeroes = function(n) {\n    let count=0\n   while(n>=5){\n       count += ~~(n/5)\n       n= ~~(n/5)\n   }\n    return count\n};",
        "solution_java": "class Solution {\n    public int trailingZeroes(int n) {\n        int count=0;\n        while(n>1) {count+=n/5; n=n/5;}\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int trailingZeroes(int n) {\n        int ni=0, mi=0;\n        for (int i=1; i<=n; i++){\n            int x=i;\n            while (x%2==0){\n                x= x>>1;\n                ni++;\n            }\n            while (x%5==0){\n                x= x/5;\n                mi++;\n            }\n        }\n        return min(mi,ni);\n    }\n};"
    },
    {
        "title": "Rotate Function",
        "algo_input": "You are given an integer array nums of length n.\n\nAssume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:\n\n\n\tF(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].\n\n\nReturn the maximum value of F(0), F(1), ..., F(n-1).\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n&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",
        "solution_py": "class Solution:\n    def maxRotateFunction(self, nums: List[int]) -> int:\n        preSum, cur = 0, 0\n        for i in range(len(nums)):\n            cur += i * nums[i]\n            preSum += nums[i]\n        ans = cur\n        for i in range(1, len(nums)):\n            cur -= len(nums) * nums[len(nums) - i]\n            cur += preSum\n            ans = max(ans, cur)\n        return ans",
        "solution_js": "var maxRotateFunction = function(nums) { \n    let n = nums.length;\n    let dp = 0;\n    \n    let sum = 0; \n    for (let i=0; i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Valid Parenthesis String",
        "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",
        "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",
        "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar checkValidString = function(s) {\n    let map = {}\n    return check(s,0,0,map);\n};\n\nfunction check(s,index,open,map){\n    if(index == s.length){\n        return open == 0;\n    }\n\n    if(open < 0){\n        return false;\n    }\n    let string = index.toString() + \"##\" + open.toString();\n    if(string in map){\n        return map[string]\n    }\n\n    if(s[index] == '('){\n        let l = check(s,index+1,open+1,map)\n        map[string] = l\n        return l\n    }else if (s[index] == ')'){\n        let r = check(s,index+1,open-1,map)\n        map[string] = r;\n        return r\n    }else {\n        let lr = check(s,index+1,open+1,map) || check(s,index+1,open-1,map)\n              || check(s,index+1,open,map)\n        map[string] = lr;\n        return lr\n    }\n}",
        "solution_java": "class Solution{\n\tpublic boolean checkValidString(String s){\n\t\tStack<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}",
        "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};"
    },
    {
        "title": "Water Bottles",
        "algo_input": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.\n\nThe operation of drinking a full water bottle turns it into an empty bottle.\n\nGiven the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.\n\n&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",
        "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)",
        "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};",
        "solution_java": "class Solution {\n    public int numWaterBottles(int numBottles, int numExchange) {\n        int drinkedBottles = numBottles;\n        int emptyBottles = numBottles;\n\n        while(emptyBottles >= numExchange){\n            int gainedBottles = emptyBottles / numExchange;\n\n            drinkedBottles += gainedBottles;\n\n            int unusedEmptyBottles = emptyBottles % numExchange;\n\n            emptyBottles = gainedBottles + unusedEmptyBottles;\n        }\n        return drinkedBottles;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numWaterBottles(int numBottles, int numExchange) {\n        int ex=0,remain=0,res=numBottles;\n        while(numBottles>=numExchange){\n             remain=numBottles%numExchange;\n          numBottles=numBottles/numExchange;\n           res+=numBottles;\n            numBottles+=remain;\n          cout<<numBottles<<\" \";\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Smallest Subsequence of Distinct Characters",
        "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/",
        "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)",
        "solution_js": "var smallestSubsequence = function(s) {\n    let stack = [];\n  for(let i = 0; i < s.length; i++){\n      if(stack.includes(s[i])) continue;\n   while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) stack.pop();\n      stack.push(s[i]);\n  }\n  return stack.join(\"\");\n};",
        "solution_java": "class Solution {\n    public String smallestSubsequence(String s) {\n        boolean[] inStack = new boolean [26];\n        int[] lastIdx = new int [26];\n        Arrays.fill(lastIdx,-1);\n        for(int i = 0; i < s.length(); i++){\n            lastIdx[s.charAt(i)-'a'] = i;\n        }\n        Deque<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}",
        "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};"
    },
    {
        "title": "Nth Magical Number",
        "algo_input": "A positive integer is magical if it is divisible by either a or b.\n\nGiven the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.\n\n&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",
        "solution_py": "class Solution:\n    def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n        import math\n        lcm= A*B // math.gcd(A,B)\n        l,r=2,10**14\n        while l<=r:\n            mid=(l+r)//2\n            n = mid//A+mid//B-mid//lcm\n            if n>=N:\n                r=mid-1\n           \n            else:\n                l=mid+1\n        return l%(10**9+7)",
        "solution_js": "/**\n * @param {number} n\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nvar nthMagicalNumber = function(n, a, b) {\n    const gcd = (a1,b1)=>{\n        if(b1===0) return a1;\n        return gcd(b1,a1%b1)\n    }\n    const modulo = 1000000007;\n    let low = 0;\n    let high = 10e17;\n    let lcmAB = Math.floor((a*b)/gcd(a,b));\n    \n    while(low<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};",
        "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}",
        "solution_c": "class Solution \n{\npublic:\n    \n    int lcm(int a, int b)                   // Finding the LCM of a and b\n    {\n        if(a==b)\n            return a;\n        if(a > b)\n        {\n            int count = 1;\n            while(true)\n            {\n                if((a*count)%b==0)\n                    return a*count;\n                count++;\n            }\n        }\n        int count = 1;\n        while(true)\n        {\n            if((b*count)%a==0)\n                return b*count;\n            count++;\n        }\n        return -1;      // garbage value--ignore.\n    }\n    \n    int nthMagicalNumber(int n, int a, int b) \n    {\n        long long int comm = lcm(a,b);                       //common element\n        long long int first = (((comm*2) - comm) / a) - 1;   //no. of elements appearing before the comm multiples (a).\n        long long int second = (((comm*2) - comm) / b) - 1;  //no. of elements appearing before the comm multiples(b).\n    \n        long long int landmark = (n / (first + second + 1)) * comm; // last common element before nth number.\n        long long int offset = n % (first + second + 1);            // how many numbers to consider after last common\n        \n        long long int p = landmark, q = landmark;   // initialisations to find the offset from the landmarked element\n        long long int ans = landmark;\n        for(int i=1;i<=offset;i++)  // forwarding offset number of times.\n        {\n            if(p+a < q+b)           //this logic easily takes care of which elements to be considered for the current iteration. \n            {\n                ans = p+a;\n                p = p+a;\n            }\n            else\n            {\n                ans = q+b;\n                q = q+b;\n            }\n        }\n        \n        return (ans%1000000007);    //returning the answer.\n    }\n};\n\n/*\n    a and b\n    1st step would be to find the LCM of the two numbers --> Multiples of LCM would be the common numbers in the sequential pattern.\n    The next step would be to find the numbers of a and numbers of b appearing between the common number.\n    \n\tDRY : \n\t\n    4 and 6\n    4 -> 4 8 12 16 20 24 28 32 36 40   -->  \n    6 -> 6 12 18 24 30 36 42 48 54 60  -->\n    \n    4 6 8    12     16 18 20        24 --> n/(f + s) --->  23/4 = 5 and 3\n    5th -----> (comm * 5 = 60) ------>\n*/"
    },
    {
        "title": "Search in Rotated Sorted Array II",
        "algo_input": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).\n\nBefore being passed to your function, nums is rotated at an unknown pivot index k (0 &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",
        "solution_py": "class Solution:\n    def search(self, nums: List[int], target: int) -> bool:\n        nums.sort()\n        low=0\n        high=len(nums)-1\n        while low<=high:\n            mid=(low+high)//2\n            if nums[mid]==target:\n                return True\n            elif nums[mid]>target:\n                high=mid-1\n            else:\n                low=mid+1\n        return False",
        "solution_js": "var search = function(nums, target) {\n    let found = nums.findIndex(c=> c==target);\n    if(found === -1) return false\n    else\n        return true\n};",
        "solution_java": "class Solution {\n    public boolean search(int[] nums, int target) {\n   if (nums == null || nums.length == 0) return false;\n    \n   int left = 0, right = nums.length-1;\n    int start = 0;\n\n//1. find index of the smallest element\n    while(left < right) {\n         while (left < right && nums[left] == nums[left + 1])\n                ++left;\n         while (left < right && nums[right] == nums[right - 1])\n                --right;\n        int mid = left + (right-left)/2;\n        if (nums[mid] > nums[right]) {\n            left = mid +1;\n        } else right = mid;\n    }\n    \n//2. figure out in which side our target lies\n    start = left;\n    left = 0;\n    right = nums.length-1;\n    if (target >= nums[start] && target <= nums[right])\n        left = start;\n    else right = start;\n    \n//3. Run normal binary search in sorted half.\n    while(left <= right) {\n        int mid = left + (right - left)/2;\n        if (nums[mid] == target) return true;\n        \n        if (nums[mid] > target) right = mid-1;\n        else left = mid + 1;\n    }\n    \n    return false;\n}\n}",
        "solution_c": "class Solution {\npublic:\n    bool search(vector<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};"
    },
    {
        "title": "Video Stitching",
        "algo_input": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.\n\nEach video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi.\n\nWe can cut these clips into segments freely.\n\n\n\tFor example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].\n\n\nReturn the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.\n\n&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",
        "solution_py": "class Solution:\n    def videoStitching(self, clips: List[List[int]], T: int) -> int:\n        dp = [float('inf')] * (T + 1)\n        dp[0] = 0\n        for i in range(1, T + 1):\n            for start, end in clips:\n                if start <= i <= end:\n                    dp[i] = min(dp[start] + 1, dp[i])\n        if dp[T] == float('inf'):\n            return -1\n        return dp[T]",
        "solution_js": "/** https://leetcode.com/problems/video-stitching/\n * @param {number[][]} clips\n * @param {number} time\n * @return {number}\n */\nvar videoStitching = function(clips, time) {\n  // Memo\n  this.memo = new Map();\n  \n  // Sort the clips for easier iteration\n  clips.sort((a, b) => a[0] - b[0]);\n  \n  // If the output is `Infinity` it means the task is impossible\n  let out = dp(clips, time, 0, -1);\n  return out === Infinity ? -1 : out;\n};\n\nvar dp = function(clips, time, index, endTime) {\n  let key = `${index}_${endTime}`;\n  \n  // Base, we got all the clip we need\n  if (endTime >= time) {\n    return 0;\n  }\n  \n  // Reach end of the clip array\n  if (index === clips.length) {\n    return Infinity;\n  }\n  \n  // Return form memo\n  if (this.memo.has(key) === true) {\n    return this.memo.get(key);\n  }\n  \n  // There are 2 choices, include clip in current `index` or exclude\n  // Include clip in current `index`\n  let include = Infinity;\n  \n  // We can only include clip in current `index` if either:\n  // - the `endTime` is -1 and current clip's starting is 0, in which this clip is the first segment\n  // - the `endTime` is greater than current clip's starting time, in which this clip has end time greater than our `endTime`\n  if ((endTime < 0 && clips[index][0] === 0) ||\n      endTime >= clips[index][0]) {\n    // Update the next `endTime` with the current clip's end time, `clips[index][1]`\n    let nextEndTime = clips[index][1];\n    include = 1 + dp(clips, time, index + 1, nextEndTime);\n  }\n  \n  // Exclude clip in current `index`\n  let exclude = dp(clips, time, index + 1, endTime);\n  \n  // Find which one has less clips\n  let count = Math.min(include, exclude);\n  \n  // Set memo\n  this.memo.set(key, count);\n  \n  return count;\n};",
        "solution_java": "class Solution {\n    public int videoStitching(int[][] clips, int time) {\n        Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);\n        int n = clips.length;\n        int interval[] = new int[2];\n        int cuts = 0;\n        while(true){\n            cuts++;\n            int can_reach = 0;\n            for(int i = interval[0]; i <= interval[1]; i++){\n                int j = 0;\n                while(j < n){\n                    if(clips[j][0] < i){\n                        j++;\n                    }\n                    else if(clips[j][0] == i){\n                        can_reach = Math.max(can_reach , clips[j][1]);\n                        j++;\n                    }\n                    else{\n                        break;\n                    }\n                }\n                if(can_reach >= time) return cuts;\n            }\n            interval[0] = interval[1] + 1;\n            interval[1] = can_reach;\n            if(interval[0] > interval[1]) return -1;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    static bool comp(vector<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};"
    },
    {
        "title": "Can Place Flowers",
        "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",
        "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",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Add Minimum Number of Rungs",
        "algo_input": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.\n\nYou are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.\n\nReturn the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.\n\n&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",
        "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            ",
        "solution_js": "var addRungs = function(rungs, dist) {\n    let res = 0;\n    let prev = 0;\n    for ( let i = 0; i < rungs.length; i++ ){\n        res += Math.floor(( rungs[i] - prev - 1 ) / dist );\n        prev = rungs[i];\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public int addRungs(int[] rungs, int dist) {\n        int ans = 0;\n        for (int i=0 ; i<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}",
        "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};"
    },
    {
        "title": "Car Pooling",
        "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",
        "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        ",
        "solution_js": "/**\n * @param {number[][]} trips\n * @param {number} capacity\n * @return {boolean}\n */\nvar carPooling = function(trips, capacity) {\n    \n    // sort trips by destination distance\n    trips.sort((a, b) => a[2] - b[2]);\n    \n    // build result array, using max distance\n    const lastTrip = trips[trips.length - 1];\n    const maxDistance = lastTrip[lastTrip.length - 1];\n    const arr = new Array(maxDistance + 1).fill(0);\n    \n    // build partial sum array\n    for (const [val, start, end] of trips) {\n        arr[start] += val;\n        arr[end] -= val;\n    }\n\n    // build combined sum array\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n        sum += arr[i];\n        if (sum > capacity) return false;\n    }\n    \n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean carPooling(int[][] trips, int capacity) {\n        Map<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}",
        "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};"
    },
    {
        "title": "Rotate Array",
        "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",
        "solution_py": "class Solution:\n    def reverse(self,arr,left,right):\n        while left < right:\n            arr[left],arr[right] = arr[right], arr[left]\n            left, right = left + 1, right - 1\n        return arr\n    def rotate(self, nums: List[int], k: int) -> None:\n        length = len(nums)\n        k = k % length\n        l, r = 0, length - 1\n        nums = self.reverse(nums,l,r)\n        l, r = 0, k - 1\n        nums = self.reverse(nums,l,r)\n        l, r = k, length - 1\n        nums = self.reverse(nums,l,r)\n        return nums",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nvar rotate = function(nums, k) {\n    const len = nums.length;\n    k %= len;\n    const t = nums.splice(len - k, k);\n    nums.unshift(...t);\n};",
        "solution_java": "class Solution {\n    public void rotate(int[] nums, int k) {\n        reverse(nums , 0 , nums.length-1);\n        reverse(nums , 0 , k-1);\n        reverse(nums , k , nums.length -1);\n    }\n    \n    public static void reverse(int[] arr , int start , int end){\n        while(start<end){\n            int temp = arr[start];\n            arr[start] = arr[end];\n            arr[end] = temp;\n            start++;\n            end--;\n        }\n    }\n}",
        "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};"
    },
    {
        "title": "License Key Formatting",
        "algo_input": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.\n\nWe want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.\n\nReturn the reformatted license key.\n\n&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",
        "solution_py": "class Solution:\n    def licenseKeyFormatting(self, s: str, k: int) -> str:\n        new_str = s.replace(\"-\", \"\")\n        res = \"\"\n        j = len(new_str)-1\n        i = 0\n        while j >= 0:\n            res += new_str[j].upper()\n            i += 1\n            if i == k and j != 0:\n                res += \"-\"\n                i = 0\n            j -= 1\n        return res[::-1]",
        "solution_js": "// Please upvote if you like the solution. Thanks\n\nvar licenseKeyFormatting = function(s, k) {\n let str=s.replace(/[^A-Za-z0-9]/g,\"\").toUpperCase()\n    let ans=\"\"\n    let i=str.length;\n    while(i>0){\n        ans=\"-\"+str.substring(i-k,i)+ans // we are taking k characters from the end of string and adding it to answer\n        i=i-k\n    }\n    return (ans.substring(1)) // removing the \"-\" which is present in the start of ans\n};",
        "solution_java": "class Solution {\n    public String licenseKeyFormatting(String s, int k) {\n        StringBuilder answer = new StringBuilder();\n        int length = 0;\n        // Iterate Backwards to fullfill first group condition\n        for(int i=s.length()-1;i>=0;i--) {\n            if(s.charAt(i) == '-') {\n                continue;\n            }\n            if(length > 0 && length % k == 0) {\n                answer.append('-');\n            }\n            answer.append(Character.toUpperCase(s.charAt(i)));\n            length++;\n        }\n        return answer.reverse().toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string licenseKeyFormatting(string s, int k) {\n        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};"
    },
    {
        "title": "Count the Hidden Sequences",
        "algo_input": "You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].\n\nYou are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.\n\n\n\tFor example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive).\n\n\t\n\t\t[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.\n\t\t[5, 6, 3, 7] is not possible since it contains an element greater than 6.\n\t\t[1, 2, 3, 4] is not possible since the differences are not correct.\n\t\n\t\n\n\nReturn the number of possible hidden sequences there are. If there are no possible sequences, return 0.\n\n&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",
        "solution_py": "class Solution:\n    def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n        l = [0]\n        for i in differences:\n            l.append(l[-1]+i)\n        return max(0,(upper-lower+1)-(max(l)-min(l)))",
        "solution_js": "var numberOfArrays = function(differences, lower, upper) {\n    let temp = 0;\n    let res = 0;\n    let n = lower;\n\n    for (let i = 0; i < differences.length; i++) {\n        temp += differences[i];\n        differences[i] = temp;\n    }\n\n    const min = Math.min(...differences);\n    const max = Math.max(...differences);\n\n    while (n <= upper) {\n        if (n + min >= lower && n + max <= upper) res++;\n        n++;\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public int numberOfArrays(int[] differences, int lower, int upper) {\n        ArrayList<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}",
        "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}; "
    },
    {
        "title": "All Divisions With the Highest Score of a Binary Array",
        "algo_input": "You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 &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",
        "solution_py": "class Solution:\n    def maxScoreIndices(self, nums: List[int]) -> List[int]:\n        zeroFromLeft = [0] * (len(nums) + 1)\n        oneFromRight = [0] * (len(nums) + 1)\n        for i in range(len(nums)):\n            if nums[i] == 0:\n                zeroFromLeft[i + 1] = zeroFromLeft[i] + 1\n            else:\n                zeroFromLeft[i + 1] = zeroFromLeft[i]\n\n        for i in range(len(nums))[::-1]:\n            if nums[i] == 1:\n                oneFromRight[i] = oneFromRight[i + 1] + 1\n            else:\n                oneFromRight[i] = oneFromRight[i + 1]\n\n        allSum = [0] * (len(nums) + 1)\n        currentMax = 0\n        res = []\n        for i in range(len(nums) + 1):\n            allSum[i] = oneFromRight[i] + zeroFromLeft[i]\n            if allSum[i] > currentMax:\n                res = []\n                currentMax = allSum[i]\n            if allSum[i] == currentMax:\n                res.append(i)\n        return res",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar maxScoreIndices = function(nums) {\n        let n=nums.length;\n        // initialize 3 arrays for counting with n+1 size\n        let zeros = new Array(n+1).fill(0);\n        let ones = new Array(n+1).fill(0);\n        let total = new Array(n+1).fill(0);\n\n       // count no of zeros from left to right\n        for(let i=0;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Merge k Sorted Lists",
        "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",
        "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",
        "solution_js": "var mergeKLists = function(lists) {    \n    // Use min heap to keep track of the smallest node in constant time.\n    // Enqueue and dequeue will be log(k) where k is the # of lists\n    // b/c we only need to keep track of the next node for each list\n    // at any given time.\n    const minHeap = new MinPriorityQueue({ priority: item => item.val });\n    \n    for (let head of lists) {\n        if (head) minHeap.enqueue(head);\n    }\n    \n    // Create tempHead that we initiate the new list with\n    // Final list will start at tempHead.next\n    const tempHead = new ListNode();\n    let curr = tempHead;\n    \n    while (!minHeap.isEmpty()) {\n        const { val, next } = minHeap.dequeue().element;\n        curr.next = new ListNode(val);\n        curr = curr.next;\n        \n        if (next) minHeap.enqueue(next);\n    }\n    \n    return tempHead.next;\n};",
        "solution_java": "class Solution {\npublic ListNode mergeKLists(ListNode[] lists) {\n    if(lists == null || lists.length < 1) return null;\n\n     //add the first chunk of linkedlist to res,\n     //so later we started from index 1\n    ListNode res = lists[0];\n\n    //traverse the lists and start merge by calling mergeTwo\n    for(int i = 1; i < lists.length; i++){\n        res = mergeTwo(res, lists[i]);\n    }\n\n    return res;\n}\n    //leetcode 21 technics\n    private ListNode mergeTwo(ListNode l1, ListNode l2){\n        if(l1 == null) return l2;\n        if(l2 == null) return l1;\n\n        if(l1.val < l2.val){\n            l1.next = mergeTwo(l1.next, l2);\n            return l1;\n        } else{\n            l2.next = mergeTwo(l2.next, l1);\n            return l2;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    struct compare\n    {\n        bool operator()(ListNode* &a,ListNode* &b)\n        {\n            return a->val>b->val;\n        }\n    };\n    ListNode* mergeKLists(vector<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};"
    },
    {
        "title": "Minimum Replacements to Sort the Array",
        "algo_input": "You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.\n\n\n\tFor example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].\n\n\nReturn the minimum number of operations to make an array that is sorted in non-decreasing order.\n\n&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",
        "solution_py": "class Solution:\n    def minimumReplacement(self, nums) -> int:\n        ans = 0\n        n = len(nums)\n        curr = nums[-1]\n        for i in range(n - 2, -1, -1):\n            if nums[i] > curr:\n                q = nums[i] // curr\n                if nums[i] == curr * q:\n                    nums[i] = curr\n                    ans += q - 1\n                else:\n                    nums[i] = nums[i] // (q + 1)\n                    ans += q\n            curr = nums[i]\n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumReplacement = function(nums) {\n    const n = nums.length;\n    let ans = 0;\n    for(let i = n - 2 ; i >= 0 ; i--){\n        if(nums[i]>nums[i+1]){\n            const temp = Math.ceil(nums[i]/nums[i+1]);\n            ans += temp - 1;\n            nums[i] = Math.floor(nums[i]/temp);\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public long minimumReplacement(int[] nums) {\n        long ret = 0L;\n        int n = nums.length;\n        int last = nums[n - 1];\n        for(int i = n - 2;i >= 0; i--){\n            if(nums[i] <= last){\n                last = nums[i];\n                continue;\n            }\n            if(nums[i] % last == 0){\n                // split into nums[i] / last elements, operations cnt = nums[i] / last - 1;\n                ret += nums[i] / last - 1;\n            }else{\n                // split into k elements operations cnt = k - 1;\n                int k = nums[i] / last + 1; // ceil\n                ret += k - 1;\n                last = nums[i] / k; // left most element max is nums[i] / k\n            }\n\n        }\n\n        return ret;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    long long minimumReplacement(vector<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};"
    },
    {
        "title": "Sum of Numbers With Units Digit K",
        "algo_input": "Given two integers num and k, consider a set of positive integers with the following properties:\n\n\n\tThe units digit of each integer is k.\n\tThe sum of the integers is num.\n\n\nReturn the minimum possible size of such a set, or -1 if no such set exists.\n\nNote:\n\n\n\tThe set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.\n\tThe units digit of a number is the rightmost digit of the number.\n\n\n&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",
        "solution_py": "class Solution:\n    def minimumNumbers(self, num: int, k: int) -> int:\n        if num == 0:\n            return 0\n        \n        if k == 0:\n            return 1 if num % 10 == 0 else -1\n        \n        for n in range(1, min(num // k, 10) + 1):\n            if (num - n * k) % 10 == 0:\n                return n\n        \n        return -1",
        "solution_js": "var minimumNumbers = function(num, k) {\n    if (num === 0) return 0;\n    for (let i = 1; i <= 10; i++) {\n        if (k*i % 10 === num % 10 && k*i <= num) return i;\n        if (k*i > num) return -1\n    } return -1;\n};",
        "solution_java": "class Solution\n{\n    public int minimumNumbers(int num, int k)\n    {\n        if(num == 0)\n            return 0;\n        if(k == 0)\n            if(num % 10 == 0) //E.g. 20,1590,3000\n                return 1;\n            else\n                return -1;\n        for(int i = 1; i <= num/k; i++) // Start with set size 1 and look for set having unit's digit equal to that of num\n            if(num % 10 == ((i*k)%10)) // Look for equal unit's digit\n                return i;\n\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n   \n    //same code as that of coin change\n    int coinChange(vector<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};"
    },
    {
        "title": "Minimum Operations to Make Array Equal",
        "algo_input": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e.,&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",
        "solution_py": "class Solution:\n    def minOperations(self, n: int) -> int:\n\n        return sum([n-x for x in range(n) if x % 2 != 0])",
        "solution_js": "var minOperations = function(n) {\n    let reqNum;\n    if(n%2!=0){\n        reqNum = Math.floor(n/2)*2+1\n    }else{\n        reqNum = ((Math.floor(n/2))*2+1 + (Math.floor(n/2) -1)*2+1)/2\n    }\n    let count = 0;\n    for(let i=1; i<reqNum; i +=2){\n        count += (reqNum-i)\n    }\n    return count\n};",
        "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}",
        "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};"
    },
    {
        "title": "Keep Multiplying Found Values by Two",
        "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",
        "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",
        "solution_js": "var findFinalValue = function(nums, original) {\n    while (nums.includes(original)) {\n        original = original * 2\n    }\n\n    return original\n};",
        "solution_java": "class Solution\n{\n    public int findFinalValue(int[] nums, int original)\n    {\n        HashSet<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}",
        "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};"
    },
    {
        "title": "Next Permutation",
        "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",
        "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",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nvar nextPermutation = function(nums) {\n    const dsc = nums.slice();\n    dsc.sort((a, b) => b - a);\n    if (dsc.every((n, i) => n === nums[i])) {\n        nums.sort((a, b) => a - b);\n    } else {\n        const len = nums.length;\n        let lo = len - 1, hi;\n        while (nums[lo] === dsc[dsc.length - 1]) {\n            lo--;\n            dsc.pop();\n        }\n        while (lo >= 0) {\n            // console.log(lo, nums[lo], nums.slice(lo + 1))\n            hi = nums.slice(lo + 1).reverse().findIndex((n) => n > nums[lo]);\n            if (hi !== -1) {\n                hi = len - 1 - hi;\n                break;\n            }\n            lo--;\n        }\n\n        const lval = nums[lo];\n        // console.log(lo, lval, hi, nums[hi]);\n        nums[lo] = nums[hi];\n        nums[hi] = lval;\n        const sorted = nums.slice(lo + 1);\n        // console.log(nums, sorted)\n        sorted.sort((a, b) => a - b);\n        for (let i = 0; i < sorted.length; i++)\n            nums[lo + 1 + i] = sorted[i];\n    }\n};",
        "solution_java": "class Solution {\n    public void nextPermutation(int[] nums) {\n        // FIND peek+1\n        int nextOfPeak = -1;\n        for (int i = nums.length - 1; i > 0; i--) {\n            if (nums[i] > nums[i - 1]) {\n                nextOfPeak = i - 1;\n                break;\n            }\n        }\n\n        // Return reverse Array\n        if (nextOfPeak == -1) {\n            int start = 0;\n            int end = nums.length - 1;\n            while (start <= end) {\n                int temp = nums[start];\n                nums[start] = nums[end];\n                nums[end] = temp;\n                start++;\n                end--;\n            }\n            return;\n        }\n        // Find element greater than peek\n        int reversalPoint = nums.length - 1;\n        for (int i = nums.length - 1; i > nextOfPeak; i--) {\n            if (nums[i] > nums[nextOfPeak]) {\n                reversalPoint = i;\n                break;\n            }\n        }\n\n        // swap nextOfPeak && reversalPoint\n        int temp = nums[nextOfPeak];\n        nums[nextOfPeak] = nums[reversalPoint];\n        nums[reversalPoint] = temp;\n\n        // Reverse array from nextOfPeak+1\n        int start = nextOfPeak + 1;\n        int end = nums.length - 1;\n        while (start <= end) {\n            int temp1 = nums[start];\n            nums[start] = nums[end];\n            nums[end] = temp1;\n            start++;\n            end--;\n        }\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void nextPermutation(vector<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};"
    },
    {
        "title": "Out of Boundary Paths",
        "algo_input": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.\n\nGiven the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.\n\n&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",
        "solution_py": "class Solution:\n    def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int:\n        if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n:\n            return 1\n        \n        if dp[maxMove][startRow][startColumn]!=-1:\n            return dp[maxMove][startRow][startColumn]\n        \n        if mat[startRow][startColumn]==1:\n            return 0\n        \n        if maxMove <= 0:\n            return 0\n        \n        # mat[startRow][startColumn] = 1\n        a = self.helper(m, n, maxMove-1, startRow+1, startColumn,mat,dp)\n        b = self.helper(m, n, maxMove-1, startRow-1, startColumn,mat,dp)\n        c = self.helper(m, n, maxMove-1, startRow, startColumn+1,mat,dp)\n        d = self.helper(m, n, maxMove-1, startRow, startColumn-1,mat,dp)\n        dp[maxMove][startRow][startColumn] = a+b+c+d\n        return dp[maxMove][startRow][startColumn]\n        \n        \n    def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n        mat = [[0 for i in range(n)] for j in range(m)]\n        dp = [[[-1 for i in range(n+1)] for j in range(m+1)] for k in range(maxMove+1)]\n        return self.helper(m, n, maxMove, startRow, startColumn, mat,dp)%(10**9  + 7) \n    \n\n            ",
        "solution_js": "vector<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}",
        "solution_java": "class Solution {\n    int[][][] dp;\n    int mod = 1000000007;\n    public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n        dp = new int[m][n][maxMove + 1];\n        for (int i = 0; i < m; i++)\n            for (int j = 0; j < n; j++)\n                for (int k = 0; k <= maxMove; k++)\n                    dp[i][j][k] = -1;\n        return count(m, n, maxMove, startRow, startColumn) % mod;\n    }\n    public int count(int m, int n, int move, int r, int c) {\n        if (r < 0 || c < 0 || r >= m || c >= n)\n            return 1;\n        if (move <= 0)\n            return 0;\n        if (dp[r][c][move] != -1)\n            return dp[r][c][move] % mod;\n        dp[r][c][move] = ((count(m, n, move - 1, r + 1, c) % mod + count (m, n, move - 1, r - 1, c) % mod) % mod + (count (m, n, move - 1, r, c + 1) % mod + count(m, n, move - 1, r, c - 1) % mod) % mod ) % mod;\n        return dp[r][c][move] % mod;\n    }\n}",
        "solution_c": "vector<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}"
    },
    {
        "title": "Count of Range Sum",
        "algo_input": "Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.\n\nRange sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i &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",
        "solution_py": "class Solution:\n    def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n        acc = list(accumulate(nums))\n        ans = a = 0\n        for n in nums:\n            a += n\n            ans += sum(1 for x in acc if lower <= x <= upper)\n            acc.pop(0)\n            lower += n\n            upper += n\n        return ans",
        "solution_js": "var countRangeSum = function(nums, lower, upper) {\n  let preSum = Array(nums.length + 1).fill(0);\n  let count = 0;\n\n  // create preSum array, use preSum to check the sum range\n  for (let i = 0; i < nums.length; i++) {\n      preSum[i + 1] = preSum[i] + nums[i];\n  }\n\n  const sort = function(preSum) {\n      if (preSum.length === 1) return preSum;\n\n      let mid = Math.floor(preSum.length / 2);\n      let left = sort(preSum.slice(0, mid));\n      let right = sort(preSum.slice(mid))\n\n      return merge(left, right);\n  }\n\n  const merge = function(left, right) {\n      let start = 0;\n      let end = 0;\n\n      for (let i = 0; i < left.length; i++) {\n          // all elements before start index, after subtracting left[i] are less than lower, which means all elements after start index are bigger or equal than lower\n          while (start < right.length && right[start] - left[i] < lower) {\n              start++;\n          }\n          // similarly, all elements before end index are less or euqal then upper\n          while (end < right.length && right[end] - left[i] <= upper) {\n              end++;\n          }\n\n          // since the initial values of start and end are the same, and upper >= lower, so end will >= start too, which means the rest of the end minus start element difference will fall between [lower, upper].\n          count += end - start;\n      }\n\n      let sort = [];\n      while (left.length && right.length) {\n          if (left[0] <= right[0]) {\n              sort.push(left.shift());\n          } else {\n              sort.push(right.shift());\n          }\n      }\n\n      return [...sort, ...left, ...right];\n  }\n\n  sort(preSum);\n  return count;\n};",
        "solution_java": "class Solution {\n    public int countRangeSum(int[] nums, int lower, int upper) {\n        int n = nums.length, ans = 0;\n        long[] pre = new long[n+1];\n        for (int i = 0; i < n; i++){\n            pre[i+1] = nums[i] + pre[i];\n        }\n        Arrays.sort(pre);\n        int[] bit = new int[pre.length+2];\n        long sum = 0;\n        for (int i = 0; i < n; i++){\n            update(bit, bs(sum, pre), 1);\n            sum += nums[i];\n            ans += sum(bit, bs(sum-lower, pre)) - sum(bit, bs(sum-upper-1, pre));\n        }\n        return ans;\n    }\n\n    private int bs(long sum, long[] pre){ // return the index of first number bigger than sum\n        int lo = 0, hi = pre.length;\n        while(lo < hi){\n            int mid = (lo+hi) >> 1;\n            if (pre[mid]>sum){\n                hi=mid;\n            }else{\n                lo=mid+1;\n            }\n        }\n        return lo;\n    }\n\n    private void update(int[] bit, int idx, int inc){\n        for (++idx; idx < bit.length; idx += idx & -idx){\n            bit[idx] += inc;\n        }\n    }\n\n    private int sum(int[] bit, int idx){\n        int ans = 0;\n        for (++idx; idx > 0; idx -= idx & -idx){\n            ans += bit[idx];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    using ll = long long;\n\n    int countRangeSum(vector<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};"
    },
    {
        "title": "Vertical Order Traversal of a Binary Tree",
        "algo_input": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree.\n\nFor each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).\n\nThe vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.\n\nReturn the vertical order traversal of the binary tree.\n\n&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",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n    def verticalTraversal(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: List[List[int]]\n        \"\"\"\n        q = [(0, 0, root)]\n        l = []\n        while q:\n            col, row, node = q.pop()\n            l.append((col, row, node.val))\n            if node.left:\n                q.append((col-1, row+1, node.left))\n            if node.right:\n                q.append((col+1, row+1, node.right))\n        l.sort()\n        print(l)\n        ans = []\n        ans.append([l[0][-1]])\n        for i in range(1, len(l)):\n            if l[i][0] > l[i-1][0]:\n                ans.append([l[i][-1]])\n            else:\n                ans[-1].append(l[i][-1])\n        return ans",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nvar verticalTraversal = function(root) {\n    let ans = [];\n    let l = 0, ri = 0, mi = 0;\n    const preOrder = (r = root, mid = 0, d = 0) => {\n        if(!r) return ;\n\n        if(mid == 0) {\n            if(ans.length < mi + 1) ans.push([]);\n            ans[mi].push({v: r.val, d});\n        } else if(mid < 0) {\n           if(mid < l) {\n               l = mid;\n               mi++;\n               ans.unshift([{v: r.val, d}]);\n           } else {\n               let idx = mi + mid;\n               ans[idx].push({v: r.val, d});\n           }\n        } else {\n            if(mid > ri) {\n                ri = mid;\n                ans.push([{v: r.val, d}]);\n            } else {\n                let idx = mi + mid;\n                ans[idx].push({v: r.val, d});\n            }\n        }\n\n        preOrder(r.left, mid - 1, d + 1);\n        preOrder(r.right, mid + 1, d + 1);\n    }\n    preOrder();\n    const sortByDepthOrVal = (a, b) => {\n        if(a.d == b.d) return a.v - b.v;\n        return a.d - b.d;\n    }\n    ans = ans.map(col => col.sort(sortByDepthOrVal).map(a => a.v));\n    return ans;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n    private static class MNode {\n        TreeNode Node;\n        int hDist;\n        int level;\n        MNode(TreeNode node, int hd, int l) {\n            Node = node;\n            hDist = hd;\n            level = l;\n        }\n    }\n\n    public List<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}",
        "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};"
    },
    {
        "title": "XOR Queries of a Subarray",
        "algo_input": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].\n\nFor each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).\n\nReturn an array answer where answer[i] is the answer to the ith query.\n\n&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",
        "solution_py": "class Solution:\n    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n\n\n       \"\"\"\n\n       arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\n\n       find pref xor of arr\n\n       pref = [x,x,x,x]\n\n       for each query find the left and right indices\n       the xor for range (l, r) would be pref[r] xor pref[l-1]\n       \n       \"\"\"     \n       n, m = len(queries), len(arr)\n\n       answer = [1]*n\n\n       pref = [1]*m\n       pref[0] = arr[0]\n       if m > 1:\n           for i in range(1,m):\n               pref[i] = pref[i-1] ^ arr[i]\n\n       for (i, (l,r)) in enumerate(queries):\n           if l == 0: answer[i] = pref[r]          \n           else: answer[i] = pref[r] ^ pref[l-1]\n\n       return answer",
        "solution_js": "var xorQueries = function(arr, queries) {\n    let n = arr.length;\n    \n    while ((n & (n - 1)) != 0) {\n        n++;\n    }\n    \n    const len = n;\n    const tree = new Array(len * 2).fill(0);\n  \n    build(tree, 1, 0, len - 1);\n    \n    const res = [];\n    \n    for (let i = 0; i < queries.length; i++) {\n        const [start, end] = queries[i];\n        \n        const xor = query(tree, 1, 0, len - 1, start, end);\n        \n        res.push(xor);\n    }\n    \n    \n    return res;\n    \n   \n    function build(tree, segmentIdx, segmentStart, segmentEnd) {\n        if (segmentStart === segmentEnd) {\n            tree[segmentIdx] = arr[segmentStart];\n            return;\n        }\n        \n        const mid = (segmentStart + segmentEnd) >> 1;\n        build(tree, segmentIdx * 2, segmentStart, mid);\n        build(tree, segmentIdx * 2 + 1, mid + 1, segmentEnd);\n        \n        tree[segmentIdx] = tree[segmentIdx * 2] ^ tree[segmentIdx * 2 + 1];\n\t\treturn;\n    } \n    \n    \n    function query(tree, node, nodeStart, nodeEnd, queryStart, queryEnd) {\n        if (queryStart <= nodeStart && nodeEnd <= queryEnd) {\n            return tree[node];\n        }    \n        if (nodeEnd < queryStart || queryEnd < nodeStart) {\n            return 0;\n        }\n        \n        const mid = (nodeStart + nodeEnd) >> 1;\n        \n        const leftXor = query(tree, node * 2, nodeStart, mid, queryStart, queryEnd);\n        const rightXor = query(tree, node * 2 + 1, mid + 1, nodeEnd, queryStart, queryEnd);\n        \n        return leftXor ^ rightXor;\n    }\n};\n``",
        "solution_java": "class Solution\n{\n    public int[] xorQueries(int[] arr, int[][] queries)\n    {\n        int[] ans = new int[queries.length];\n        int[] xor = new int[arr.length];\n        xor[0] = arr[0];\n        // computing prefix XOR of arr\n        for(int i = 1; i < arr.length; i++)\n        {\n            xor[i] = arr[i] ^ xor[i-1];\n        }\n        for(int i = 0; i < queries.length; i++)\n        {\n            // if query starts from something other than 0 (say i), then we XOR all values from arr[0] to arr[i-1]\n            if(queries[i][0] != 0)\n            {\n                ans[i] = xor[queries[i][1]];\n                for(int j = 0; j < queries[i][0]; j++)\n                {\n                    ans[i] = arr[j] ^ ans[i];\n                }\n            }\n            // if start of query is 0, then we striaght up use the prefix XOR till ith element\n            else\n                ans[i] = xor[queries[i][1]];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    // we know that (x ^ x)  = 0,\n    \n    // arr = [1,4,8,3,7,8],  let we have to calculate xor of subarray[2,4]\n    \n    // (1 ^ 4 ^ 8 ^ 3 ^ 7) ^ (1 ^ 4) = (8 ^ 3 ^ 7), this is nothing but prefix[right] ^ prefix[left - 1]\n    \n    // (1 ^ 1 = 0) and (4 ^ 4) = 0\n    \n    \n    vector<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};"
    },
    {
        "title": "Count Unguarded Cells in the Grid",
        "algo_input": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.\n\nA guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.\n\nReturn the number of unoccupied cells that are not guarded.\n\n&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",
        "solution_py": "class Solution:\n    def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n        dp = [[0] * n for _ in range(m)]\n        for x, y in guards+walls:\n            dp[x][y] = 1\n               \n        directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n        \n        for x, y in guards:\n            for dx, dy in directions:\n                curr_x = x\n                curr_y = y\n                \n                while 0 <= curr_x+dx < m and 0 <= curr_y+dy < n and dp[curr_x+dx][curr_y+dy] != 1:\n                    curr_x += dx\n                    curr_y += dy\n                    dp[curr_x][curr_y] = 2\n                    \n        return sum(1 for i in range(m) for j in range(n) if dp[i][j] == 0)                    ",
        "solution_js": "var countUnguarded = function(m, n, guards, walls) {\n    let board = new Array(m).fill(0).map(_=>new Array(n).fill(0))\n    \n    // 0 - Empty\n    // 1 - Guard\n    // 2 - Wall\n    // 3 - Guard view\n    \n    const DIRECTIONS = [\n        [-1, 0],\n        [0, 1],\n        [1, 0],\n        [0, -1]\n    ]\n    \n    for(let [guardRow, guardCol] of guards) board[guardRow][guardCol] = 1\n    \n    for(let [wallRow, wallCol] of walls) board[wallRow][wallCol] = 2\n    \n    for(let [guardRow, guardCol] of guards){\n        //Loop through row with the same col\n        //Go down from current row\n        let row = guardRow + 1\n        while(row < m){\n            //Stop if you encounter a wall or guard\n            if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break\n            board[row][guardCol] = 3\n            row++\n        }\n        //Go up from current row\n        row = guardRow - 1\n        while(row >= 0){\n            if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break\n            board[row][guardCol] = 3\n            row--\n        }\n        \n        \n        //Loop through col with the same row\n        //Go right from current col\n        let col = guardCol + 1\n        while(col < n){\n            if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break\n            board[guardRow][col] = 3\n            col++\n        }\n        \n        //Go left from current col\n        col = guardCol - 1\n        while(col >= 0){\n            if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break\n            board[guardRow][col] = 3\n            col--\n        }\n    }\n    \n\t//Count the free cells\n    let freeCount = 0\n    for(let i = 0; i < m; i++){\n        for(let j = 0; j < n; j++){\n            if(board[i][j] == 0) freeCount++\n        }\n    }\n    \n    return freeCount\n};",
        "solution_java": "class Solution\n{\n    public int countUnguarded(int m, int n, int[][] guards, int[][] walls)\n    {\n        int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};\n        char[][] grid= new char[m][n];\n        int count = m*n - guards.length - walls.length;\n        for(int[] wall : walls)\n        {\n            int x = wall[0], y = wall[1];\n            grid[x][y] = 'W';\n        }\n        for(int[] guard : guards)\n        {\n            int x = guard[0], y = guard[1];\n            grid[x][y] = 'G';\n        }\n        for(int[] point : guards)\n        {\n            for(int dir[] : dirs)\n            {\n                int x = point[0] + dir[0];\n                int y = point[1] + dir[1];\n                while(!(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 'G' || grid[x][y] == 'W'))\n                {\n                    if(grid[x][y] != 'P')\n                        count--;\n                    grid[x][y] = 'P';\n                    x += dir[0];\n                    y += dir[1];\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void dfs( vector<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};"
    },
    {
        "title": "Student Attendance Record I",
        "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",
        "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)",
        "solution_js": "var checkRecord = function(s) {\n    let absent = 0;\n    let lates = 0;\n    for (let i = 0; i < s.length; i++) {\n        if(s[i] === 'L') {\n            lates++;\n            if(lates > 2) return false;\n        } else {\n            lates = 0;\n            if(s[i] === 'A') {\n                absent++;\n                if(absent > 1) return false; \n            }\n        }\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean checkRecord(String s) {\n\n    int size=s.length();\n    if(s.replace(\"A\",\"\").length()<=size-2||s.indexOf(\"LLL\")!=-1)return false;\n\n    return true;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkRecord(string s);\n};\n/*********************************************************/\nbool Solution::checkRecord(string s) {\n    int i, size = s.size(), maxL=0, countA=0, countL=0;\n    for (i = 0; i < size; ++i) {\n        if (s[i] == 'L') {\n            ++countL;\n        } else {\n            countL = 0;\n        }\n        if (s[i] == 'A') {\n            ++countA;\n        }\n        if (maxL < countL) {\n            maxL = countL;\n        }\n        if( countA >= 2 || maxL >= 3) {\n            return false;\n        }\n    }\n    return true;\n}\n/*********************************************************/"
    },
    {
        "title": "Get Equal Substrings Within Budget",
        "algo_input": "You are given two strings s and t of the same length and an integer maxCost.\n\nYou want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).\n\nReturn the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.\n\n&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",
        "solution_py": "class Solution(object):\n    def equalSubstring(self, s, t, maxCost):\n        \"\"\"\n        :type s: str\n        :type t: str\n        :type maxCost: int\n        :rtype: int\n        \"\"\"\n        \n        \n        \n        \n        best = 0\n        \n        windowCost = 0\n        l = 0\n        for r in range(len(s)):\n            \n            windowCost += abs(ord(s[r]) - ord(t[r]))\n            \n            while windowCost > maxCost:\n                \n                windowCost -= abs(ord(s[l]) - ord(t[l]))\n                l+=1\n                \n            best = max(best,r-l+1)\n            \n        return best\n                \n            \n            ",
        "solution_js": "var equalSubstring = function(s, t, maxCost) {\n    let dp = [], ans = 0;\n\n    for (let i = 0, j = 0, k = 0; i < s.length; i++) {\n        // overlay\n        k += dp[i] = abs(s[i], t[i]);\n        \n        // non first\n        if (k > maxCost) {\n            k -= dp[j], j++;\n            continue;\n        }\n        \n        // eligible\n        ans++;\n    }\n\n    return ans;\n\n    // get abs value\n    function abs(a, b) {\n        return Math.abs(a.charCodeAt(0) - b.charCodeAt(0));\n    }\n};",
        "solution_java": "class Solution {\n    public int equalSubstring(String s, String t, int maxCost) {\n        int ans =0;\n        int tempcost =0;\n        int l =0 ;\n        int r= 0 ;\n        for(;r!=s.length();r++){\n            tempcost += Math.abs(s.charAt(r)-t.charAt(r));\n            while(tempcost>maxCost){\n                tempcost -= Math.abs(s.charAt(l)-t.charAt(l));\n                l++;\n            }\n            ans =Math.max(ans,r+1-l);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int equalSubstring(string s, string t, int maxCost) {\n        int l = 0, r = 0, currCost = 0, n = s.length(), maxLen = 0;\n\n        while(r < n) {\n            currCost += abs(s[r] - t[r]);\n            r++;\n\n            while(currCost > maxCost) {\n                currCost -= abs(s[l] - t[l]);\n                l++;\n            }\n\n            maxLen = max(r - l, maxLen);\n        }\n\n        return maxLen;\n    }\n};"
    },
    {
        "title": "Maximum Repeating Substring",
        "algo_input": "For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.\n\nGiven strings sequence and word, return the maximum k-repeating value of word in sequence.\n\n&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",
        "solution_py": "class Solution:\n    def maxRepeating(self, sequence: str, word: str) -> int:\n        if word not in sequence:\n            return 0\n\n        left = 1\n        right = len(sequence) // len(word)\n        while left <= right:\n            mid = (left + right) // 2\n            if word * mid in sequence:\n                left = mid + 1\n            else:\n                right = mid - 1\n\n        return left - 1",
        "solution_js": "var maxRepeating = function(sequence, word) {\n\tlet result = 0;\n\n\twhile (sequence.includes(word.repeat(result + 1))) {\n\t\tresult += 1;\n\t};\n\treturn result;\n};",
        "solution_java": "class Solution {\n    public int maxRepeating(String s, String w) {\n        if(w.length()>s.length()) return 0;\n        int ans=0;\n        StringBuilder sb=new StringBuilder(\"\");\n        while(sb.length()<=s.length()){\n            sb.append(w);\n            if(s.contains(sb)) ans++;\n            else break;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint maxRepeating(string sequence, string word) {\n\t\tint k = 0;\n\t\tstring temp = word;\n\n\t\twhile(sequence.find(temp) != string::npos){\n\t\t\ttemp += word;\n\t\t\tk++;\n\t\t}\n\n\t\treturn k;\n\t}\n};"
    },
    {
        "title": "Count Square Sum Triples",
        "algo_input": "A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.\n\nGiven an integer n, return the number of square triples such that 1 &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",
        "solution_py": "class Solution:\n    def countTriples(self, n: int) -> int:\n        c = 0\n        for i in range(1, n+1):\n            for j in range(i+1, n+1):\n                sq = i*i + j*j\n                r = int(sq ** 0.5)\n                if ( r*r == sq and r <= n ):\n                    c +=2\n        return c",
        "solution_js": "var countTriples = function(n) {\n    let count = 0;\n    for (let i=1; i < n; i++) {\n        for (let j=1; j < n; j++) {\n            let root = Math.sqrt(j*j + i*i)\n            if (Number.isInteger(root) && root <= n) {\n                count++\n            }\n        }\n    }\n\n    return count\n};",
        "solution_java": "class Solution {\n    public int countTriples(int n) {\n        int c = 0;\n        for(int i=1 ; i<=n ; i++){\n            for(int j=i+1 ; j<=n ; j++){\n                int sq = ( i * i) + ( j * j);\n                int r = (int) Math.sqrt(sq);\n                if( r*r == sq && r <= n )\n                    c += 2;\n            }\n        }\n        return c;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countTriples(int n) {\n        int res = 0;\n        for (int a = 3, sqa; a < n; a++) {\n            sqa = a * a;\n            for (int b = 3, sqc, c; b < n; b++) {\n                sqc = sqa + b * b;\n                c = sqrt(sqc);\n                if (c > n) break;\n                res += c * c == sqc;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts",
        "algo_input": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:\n\n\n\thorizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and\n\tverticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.\n\n\nReturn the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.\n\n&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",
        "solution_py": "class Solution:\n    def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n        horizontalCuts.sort()\n        verticalCuts.sort()\n        \n        mxHr = 0\n        prev = 0\n        for i in horizontalCuts:\n            mxHr = max(mxHr, i-prev)\n            prev = i\n        mxHr = max(mxHr, h-horizontalCuts[-1])\n        \n        mxVr = 0\n        prev = 0\n        for i in verticalCuts:\n            mxVr = max(mxVr, i-prev)\n            prev = i\n        mxVr = max(mxVr, w-verticalCuts[-1])\n        \n        return (mxHr * mxVr) % ((10 ** 9) + 7)",
        "solution_js": "var maxArea = function(h, w, horizontalCuts, verticalCuts) {\n    horizontalCuts.sort((a,b) => a-b)\n    verticalCuts.sort((a,b) => a-b)\n    let max_hor_dis = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length-1])\n    let max_ver_dis = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length-1])\n    for(let i=1; i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Expressive Words",
        "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",
        "solution_py": "class Solution:\n    def expressiveWords(self, s: str, words: List[str]) -> int:\n        # edge cases\n        if len(s) == 0 and len(words) != 0:\n            return False\n        if len(words) == 0 and len(s) != 0:\n            return False\n        if len(s) == 0 and len(words) == 0:\n            return True\n     \n        # helper function, compressing string and extract counts\n        def compressor(s_word):\n            init_string =[s_word[0]]\n            array = []\n            start = 0\n            for i,c in enumerate(s_word):\n                if c == init_string[-1]:\n                    continue\n                array.append(i-start)\n                start = i\n                init_string += c  \n            array.append(i-start+1)    \n            return init_string,array\n\n        res = len(words)\n        s_split, s_array = compressor(s)\n        for word in words:\n            word_split = ['']\n            word_array = []\n            word_split,word_array = compressor(word)\n            if s_split == word_split:\n                for num_s,num_word in zip(s_array,word_array):\n                    if num_s != num_word and num_s < 3 or num_word > num_s:\n                        res -= 1\n                        break\n            else:\n                res -= 1\n        return res",
        "solution_js": "/**\n * @param {string} s\n * @param {string[]} words\n * @return {number}\n */\nvar expressiveWords = function(s, words) {\n    let arr = [];\n    let curr = 0\n    while(curr < s.length){\n        let count = 1\n        while(s[curr] === s[curr+1]){\n            count++;\n            curr++\n        }\n        arr.push([s[curr] , count]);\n        curr++\n    }\n    let ans = 0\n    for(let charArr of words){\n        let idx = 0;\n        let i = 0;\n        let flag = true;\n        if(charArr.length > s.length)continue\n\n        while( i < charArr.length ){\n            let count = 1\n            while(charArr[i] === charArr[i+1]){\n                i++;\n                count++\n            }\n            if(arr[idx][0] !== charArr[i] || arr[idx][1] < count || (arr[idx][1] <3 && arr[idx][1] !== count) ){\n                flag = false;\n                break\n            }\n            idx++;\n            i++\n\n        }\n        if(idx !== arr.length)flag = false\n        if(flag)ans++\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    private String getFreqString(String s) {\n        int len = s.length();\n        StringBuilder freqString = new StringBuilder();\n        int currFreq = 1;\n        char prevChar = s.charAt(0);\n        freqString.append(s.charAt(0));\n        for(int i = 1; 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}",
        "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};"
    },
    {
        "title": "Maximum Subarray",
        "algo_input": "Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nA subarray is a contiguous part of an array.\n\n&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",
        "solution_py": "class Solution:\n    def maxSubArray(self, nums: List[int]) -> int:\n        def kadane(i):\n            if F[i] != None:\n                return F[i]\n            F[i] = max(nums[i],kadane(i-1) + nums[i])\n            return F[i]\n        n = len(nums)\n        F = [None for _ in range(n)]\n        F[0] = nums[0]\n        kadane(n-1)\n        return max(F)",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\n var maxSubArray = function(nums) {\n   let max = Number.MIN_SAFE_INTEGER;\n   let curr = 0;\n   for (let i = 0; i < nums.length; i++) {\n      if (curr < 0 && nums[i] > curr) {\n          curr = 0;\n      }\n    curr += nums[i];\n    max = Math.max(max, curr);\n   }\n  return max;\n}; ",
        "solution_java": "class Solution {\n    public int maxSubArray(int[] nums) {\n        int n = nums.length;\n        int currmax = 0;\n        int gmax = nums[0];\n        for(int i=0;i<n;i++) {\n            currmax+=nums[i];\n            gmax=Math.max(gmax, currmax);\n            currmax=Math.max(currmax, 0);\n        }\n        return gmax;\n    }\n}",
        "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};"
    },
    {
        "title": "Minimum Cost to Make at Least One Valid Path in a Grid",
        "algo_input": "Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:\n\n\n\t1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])\n\t2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])\n\t3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])\n\t4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])\n\n\nNotice that there could be some signs on the cells of the grid that point outside the grid.\n\nYou will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.\n\nYou can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.\n\nReturn the minimum cost to make the grid have at least one valid path.\n\n&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",
        "solution_py": "class Solution:\n    def minCost(self, grid: List[List[int]]) -> int:\n        changes = [[float(\"inf\") for _ in range(len(grid[0]))] for _ in range(len(grid))]\n        heap = [(0,0,0)]\n        dirn = [(0,1),(0,-1),(1,0),(-1,0)]\n        while heap:\n            dist,r,c = heapq.heappop(heap)\n            if r >= len(grid) or r < 0 or c >= len(grid[0]) or c < 0 or changes[r][c] <= dist:\n                continue\n            if r == len(grid) - 1 and c == len(grid[0]) - 1:\n                return dist\n            changes[r][c] = dist\n            for i in range(1,5):\n                if i == grid[r][c]:\n                    heapq.heappush(heap,(dist,r+dirn[i-1][0],c+dirn[i-1][1]))\n                else:\n                    heapq.heappush(heap,(dist+1,r+dirn[i-1][0],c+dirn[i-1][1]))\n        return dist\n                    ",
        "solution_js": "const minCost = function (grid) {\n\tconst m = grid.length,\n\t\tn = grid[0].length,\n\t\tcheckPos = (i, j) =>\n\t\t\ti > -1 && j > -1 && i < m && j < n && !visited[i + \",\" + j],\n\t\tdir = { 1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0] },\n\t\tdfs = (i, j) => {\n\t\t\tif (!checkPos(i, j)) return false;\n\t\t\tif (i === m - 1 && j === n - 1) return true;\n\t\t\tvisited[i + \",\" + j] = true;\n\t\t\tnext.push([i, j]);\n\t\t\treturn dfs(i + dir[grid[i][j]][0], j + dir[grid[i][j]][1]);\n\t\t},\n\t\tvisited = {};\n\tlet changes = 0, cur = [[0, 0]], next;\n\twhile (cur.length) {\n\t\tnext = [];\n\t\tfor (const [i, j] of cur) if (dfs(i, j)) return changes;\n\t\tchanges++;\n\t\tcur = [];\n\t\tnext.forEach(pos => {\n\t\t\tfor (let d = 1; d < 5; d++) {\n\t\t\t\tconst x = pos[0] + dir[d][0],\n\t\t\t\t\ty = pos[1] + dir[d][1];\n\t\t\t\tif (checkPos(x, y)) cur.push([x, y]);\n\t\t\t}\n\t\t});\n\t}\n};",
        "solution_java": "class Solution {\n\n    int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n\n    private boolean isValid(int i,int j,int n,int m) {\n        return i<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}",
        "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};"
    },
    {
        "title": "Sum Game",
        "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",
        "solution_py": "class Solution:\n    def sumGame(self, num: str) -> bool:\n        n = len(num)\n        q_cnt_1 = s1 = 0\n        for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n            if num[i] == '?':\n                q_cnt_1 += 1\n            else:\n                s1 += int(num[i])\n        q_cnt_2 = s2 = 0\n        for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n            if num[i] == '?':\n                q_cnt_2 += 1\n            else:\n                s2 += int(num[i])\n        s_diff = s1 - s2 # calculate sum difference and question mark difference\n        q_diff = q_cnt_2 - q_cnt_1\n        return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins",
        "solution_js": "/**\n * @param {string} num\n * @return {boolean}\n */\nvar sumGame = function(num) {\n    \n    function getInfo(s) {\n        var sum = 0;\n        var ques = 0;\n        for(let c of s.split(''))\n            if (c !== '?') sum += c - 0;\n            else ques++;\n        return [sum, ques];\n    }\n    \n    function check(sum1, sum2, q1, q2, q) {\n        return sum1 + 9* Math.min(q/2, q1) > sum2 + 9 * Math.min(q/2, q2);\n    }\n    \n    \n    var q = getInfo(num)[1];\n    var [sum1, q1] = getInfo(num.substring(0, Math.floor(num.length/2)));\n    var [sum2, q2] = getInfo(num.substring(Math.floor(num.length/2), num.length));\n    if (sum1 < sum2) { \n        [sum1, sum2] = [sum2, sum1];\n        [q1, q2] = [q2, q1];\n    }\n    \n    return check(sum1, sum2, q1, q2, q) || check(sum2, sum1, q2, q1, q);\n};",
        "solution_java": "class Solution {\n    public boolean sumGame(String num) {\n        int q = 0, d = 0, n = num.length();\n        for (int i = 0; i < n; i++){\n            if (num.charAt(i) == '?'){\n                q += 2* i < n? 1 : -1;\n            }else{\n                d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0');\n            }\n        }\n        return (q & 1) > 0 || q * 9 + 2 * d != 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool sumGame(string num) {\n        const int N = num.length();\n        \n        int lDigitSum = 0;\n        int lQCount = 0;\n        int rDigitSum = 0;\n        int rQCount = 0;\n        \n        for(int i = 0; i < N; ++i){\n            if(isdigit(num[i])){\n                if(i < N / 2){\n                    lDigitSum += (num[i] - '0');\n                }else{\n                    rDigitSum += (num[i] - '0');\n                }\n            }else{\n                if(i < N / 2){\n                    ++lQCount;\n                }else{\n                    ++rQCount;\n                }\n            }\n        }\n        \n        // Case 0: Only digits (without '?')\n        if((lQCount + rQCount) == 0){\n            return (lDigitSum != rDigitSum);\n        }\n        \n        // Case 1: Odd number of '?'\n        if((lQCount + rQCount) % 2 == 1){\n            return true;\n        }\n        \n        // Case 2: Even number of '?'\n        int minQCount = min(lQCount, rQCount);\n        lQCount -= minQCount;\n        rQCount -= minQCount;\n        return (lDigitSum + 9 * lQCount / 2 != rDigitSum + 9 * rQCount / 2);\n    }\n};"
    },
    {
        "title": "Number of Arithmetic Triplets",
        "algo_input": "You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:\n\n\n\ti &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",
        "solution_py": "class Solution:\n    def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n        \n        ans = 0\n        n = len(nums)\n        for i in range(n):\n            if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n                ans += 1\n        \n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} diff\n * @return {number}\n */\nvar arithmeticTriplets = function(nums, diff) {\n    count = 0\n    for(let i = 0; i < nums.length - 2; i++){\n       for(let j = i + 1; j < nums.length - 1; j++){\n           for(let k = j + 1; k < nums.length; k++){\n            if(i < j && j < k && nums[j] - nums[i] === diff && nums[k] - nums[j] === diff){\n                count++\n            }\n         }\n      }\n    }\n    return count\n};",
        "solution_java": "class Solution {\n    public int arithmeticTriplets(int[] nums, int diff) {\n        int result = 0;\n        int[] map = new int[201];\n\n        for(int num: nums) {\n            map[num] = 1;\n\n            if(num - diff >= 0) {\n                map[num] += map[num - diff];\n            }\n\n            if(map[num] >= 3) result += 1;\n        }\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int arithmeticTriplets(vector<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};"
    },
    {
        "title": "Letter Combinations of a Phone Number",
        "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",
        "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",
        "solution_js": "var letterCombinations = function(digits) {\n  if(!digits) return []\n  let res = []\n  const alpha = {\n    2: \"abc\",\n    3: \"def\",\n    4: \"ghi\",\n    5: \"jkl\",\n    6: \"mno\",\n    7: \"pqrs\",\n    8: \"tuv\",\n    9: \"wxyz\"\n  }\n  \n  const dfs = (i, digits, temp)=>{\n    if(i === digits.length){\n      res.push(temp.join(''))\n      return\n    }\n    \n    let chars = alpha[digits[i]]\n    for(let ele of chars){\n      temp.push(ele)\n      dfs(i+1, digits, temp)\n      temp.pop()\n    }\n  }\n  dfs(0, digits, [])\n  return res\n};",
        "solution_java": "class Solution {\n    String[] num = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n    public List<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}",
        "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};"
    },
    {
        "title": "Number of Sets of K Non-Overlapping Line Segments",
        "algo_input": "Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.\n\nReturn the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.\n\n&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",
        "solution_py": "class Solution:\n    def numberOfSets(self, n: int, k: int) -> int:\n        MOD = 10**9 + 7\n        @lru_cache(None)\n        def dp(i, k, isStart):\n            if k == 0: return 1 # Found a way to draw k valid segments\n            if i == n: return 0 # Reach end of points\n            ans = dp(i+1, k, isStart) # Skip ith point\n            if isStart:\n                ans += dp(i+1, k, False) # Take ith point as start\n            else:\n                ans += dp(i, k-1, True) # Take ith point as end\n            return ans % MOD\n        return dp(0, k, True)",
        "solution_js": "var numberOfSets = function(n, k) {\n    return combinations(n+k-1,2*k)%(1e9+7)\n};\nvar combinations=(n,k)=>{\n    var dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>1))\n    for (let i = 1; i <=n; i++) \n        for (let k = 1; k <i; k++)\n            dp[i][k]=(dp[i-1][k-1]+dp[i-1][k]) %(1e9+7)     \n    return dp[n][k]\n}",
        "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}",
        "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};"
    },
    {
        "title": "Display Table of Food Orders in a Restaurant",
        "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",
        "solution_py": "class Solution:\n    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n        column = ['Table']\n        dish = []\n        table_dict = {}\n        for order_row in orders : \n            if order_row[-1] not in dish :\n                dish.append(order_row[-1])\n        \n        for order_row in orders :\n            if order_row[1] not in table_dict.keys() :\n                table_dict[order_row[1]] = {}\n                for food in dish : \n                    table_dict[order_row[1]][food] = 0 \n                table_dict[order_row[1]][order_row[-1]] += 1\n            else : \n               table_dict[order_row[1]][order_row[-1]] += 1 \n        \n        dish.sort()\n        column = column + dish \n        ans = [column]\n        table = []\n        childDict = {}\n        for key in sorted(table_dict.keys()) : \n            table.append(int(key))\n            childDict[key] = []\n            for value in column : \n                if value != 'Table' :\n                    childDict[key].append(str(table_dict[key][value]))\n        table.sort()\n        output = [ans[0]]\n        for table_num in table : \n            childList = [str(table_num)]\n            output.append(childList + childDict[str(table_num)])\n        return output ",
        "solution_js": "var displayTable = function(orders) {\n    var mapOrders = {};\n    var tables = [];\n    var dishes = [];\n    for(var i=0;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Brace Expansion II",
        "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",
        "solution_py": "class Solution:\n    def braceExpansionII(self, expression: str) -> List[str]:\n        s = list(reversed(\"{\" + expression + \"}\"))\n        \n        def full_word(): \n            cur = [] \n            while s and s[-1].isalpha():    \n                cur.append(s.pop())            \n            return \"\".join(cur)\n        \n        def _expr(): \n            res = set()    \n            if s[-1].isalpha(): \n                res.add(full_word())    \n            elif s[-1] == \"{\":   \n                s.pop() # remove open brace\n                res.update(_expr()) \n                while s and s[-1] == \",\": \n                    s.pop() # remove comma \n                    res.update(_expr())    \n                s.pop() # remove close brace \n            while s and s[-1] not in \"},\": \n                res = {e + o for o in _expr() for e in res}\n            return res    \n        \n        return sorted(_expr()) ",
        "solution_js": "var braceExpansionII = function(expression) { // , mutiplier = ['']\n    const char = ('{' + expression + '}').split('').values()\n    const result = [...rc(char)];\n    result.sort((a,b) => a.localeCompare(b));\n    return result;\n};\n\nfunction rc (char) {\n    const result = new Set();  \n    \n    let resolved = ['']\n    let chars = '';\n    let currentChar = char.next().value; \n   \n    while (currentChar !== '}' && currentChar) {\n        if (currentChar === '{') {\n            resolved = mix(mix(resolved, [chars]), rc(char));\n            chars = '';\n        } else if (currentChar === ',') {\n            for (const v of mix(resolved, [chars])) {\n                result.add(v);\n            }\n            chars = '';\n            resolved = [''];\n        } else {\n            chars += currentChar;\n        }\n        currentChar = char.next().value;\n    }\n    \n    for (const v of mix(resolved, [chars])) {\n        result.add(v);\n    }\n    \n    return result; // everything\n}\n\nfunction mix (a, b) {\n    const result = [];\n    for (const ca of a) {\n        for (const cb of b) {\n            result.push(ca + cb);\n        }\n    }\n    return result;\n}",
        "solution_java": "class Solution {\n    // To Get the value of index traversed in a recursive call.\n    int index = 0;\n\n    public List<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}",
        "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};```"
    },
    {
        "title": "Rotate String",
        "algo_input": "Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\n\nA shift on s consists of moving the leftmost character of s to the rightmost position.\n\n\n\tFor example, if s = \"abcde\", then it will be \"bcdea\" after one shift.\n\n\n&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",
        "solution_py": "class Solution:\n    def rotateString(self, s: str, goal: str) -> bool:\n        for x in range(len(s)):\n            s = s[-1] + s[:-1]\n            if (goal == s):\n                return True\n        return False",
        "solution_js": "var rotateString = function(s, goal) {\n   const n = s.length;\n   for(let i = 0; i < n; i++) {\n      s = s.substring(1) + s[0];\n      if(s === goal) return true;\n   }\n   return false;\n};",
        "solution_java": "class Solution {\n    public boolean rotateString(String s, String goal) {\n        int n = s.length(), m = goal.length();\n        if (m != n) return false;\n\n        for (int offset = 0; offset < n; offset++) {\n            if (isMatch(s, goal, offset)) return true;\n        }\n        return false;\n    }\n\n    private boolean isMatch(String s, String g, int offset) {\n        int n = s.length();\n        for (int si = 0; si < n; si++) {\n            int gi = (si + offset) % n;\n            if (s.charAt(si) != g.charAt(gi)) return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool rotateString(string s, string goal) {\n        if(s.size()!=goal.size()){\n            return false;\n        }\n        string temp=s+s;\n        if(temp.find(goal)!=-1){\n            return true;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Maximum Path Quality of a Graph",
        "algo_input": "There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime.\n\nA valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).\n\nReturn the maximum quality of a valid path.\n\nNote: There are at most four edges connected to each node.\n\n&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",
        "solution_py": "class Solution:\n    def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n        graph = defaultdict(list)\n\t\t# build graph\n        for edge in edges:\n            graph[edge[0]].append((edge[1], edge[2]))\n            graph[edge[1]].append((edge[0], edge[2]))\n        \n        q = deque()\n        q.append((0, 0, values[0], set([0])))\n        cache = {}\n        maxPoint = 0\n\t\t\n        while q:\n            currV, currTime, currPoints, currSet = q.popleft()\n            if currV in cache:\n\t\t\t\t# if vertex has been visited, and if the previousTime is \n\t\t\t\t# less or equal to current time but current points is lower?\n\t\t\t\t# then this path can't give us better quality so stop proceeding.\n                prevTime, prevPoints = cache[currV]\n                if prevTime <= currTime and prevPoints > currPoints:\n                    continue\n            cache[currV] = (currTime, currPoints)\n\t\t\t# can't go over the maxTime limit\n            if currTime > maxTime:\n                continue\n\t\t\t# collect maxPoint only if current vertex is 0\n            if currV == 0:\n                maxPoint = max(maxPoint, currPoints)\n            for neigh, neighTime in graph[currV]:\n                newSet = currSet.copy()\n\t\t\t\t# collects quality only if not collected before\n                if neigh not in currSet:\n                    newSet.add(neigh)\n                    newPoint = currPoints + values[neigh]\n                else:\n                    newPoint = currPoints\n                q.append((neigh, currTime + neighTime, newPoint, newSet))\n        return maxPoint",
        "solution_js": "var maximalPathQuality = function(values, edges, maxTime) {\n    const adjacencyList = values.map(() => []);\n    for (const [node1, node2, time] of edges) {\n        adjacencyList[node1].push([node2, time]);\n        adjacencyList[node2].push([node1, time]);\n    }\n\n    const dfs = (node, quality, time, seen) => {\n        // if we returned back to the 0 node, then we log it as a valid value\n        let best = node === 0 ? quality : 0;\n\n        // try to visit all the neighboring nodes within the maxTime\n        // given while recording the max\n        for (const [neighbor, routeTime] of adjacencyList[node]) {\n            const totalTime = time + routeTime;\n            if (totalTime > maxTime) continue;\n            if (seen.has(neighbor)) {\n                best = Math.max(best,\n                                dfs(neighbor, quality, totalTime, seen));\n            } else {\n                seen.add(neighbor);\n                best = Math.max(best,\n                                dfs(neighbor, quality + values[neighbor], totalTime, seen));\n                seen.delete(neighbor);\n            }\n        }\n        return best;\n    }\n    return dfs(0, values[0], 0, new Set([0]));\n};",
        "solution_java": "class Solution {\n    public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {\n        int n = values.length;\n        List<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}",
        "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};"
    },
    {
        "title": "My Calendar III",
        "algo_input": "A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)\n\nYou are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.\n\nImplement the MyCalendarThree class:\n\n\n\tMyCalendarThree() Initializes the object.\n\tint book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.\n\n\n&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",
        "solution_py": "import bisect\nclass MyCalendarThree:\n\n    def __init__(self):\n        self.events = []        \n\n    def book(self, start: int, end: int) -> int:\n        L, R = 1, 0\n        bisect.insort(self.events, (start, L))\n        bisect.insort(self.events, (end, R))\n        res = 0\n        cnt = 0\n        for _, state in self.events:\n            #if an interval starts, increase the counter\n            #othewise, decreas the counter\n            cnt += 1 if state == L else -1\n            res = max(res, cnt)\n        return res",
        "solution_js": "var MyCalendarThree = function() {\n    this.intersections = [];\n    this.kEvents = 0;\n    \n};\n\n/** \n * @param {number} start \n * @param {number} end\n * @return {number}\n */\nMyCalendarThree.prototype.book = function(start, end) {\n    let added = false;\n    for(let i = 0; i < this.intersections.length; i++) {\n        const a = this.intersections[i];\n        if(end <= a.start) {\n            this.intersections.splice(i, 0, {start, end, count: 1});\n            this.kEvents = Math.max(this.kEvents, 1);\n            this.added = true;\n            break;\n        }\n        if(start < a. start) {\n            this.intersections.splice(i, 0, {start, end: a.start, count: 1});\n            i++;\n            start = a.start;\n        }\n        if(a.start < start && start < a.end ) {\n            this.intersections.splice(i, 0, {start: a.start, end: start, count: a.count});\n            i++;\n            a.start = start;\n        }\n        if(end < a.end) {\n            this.intersections.splice(i + 1, 0, {start: end, end: a.end, count: a.count});\n            a.count++;\n            a.end = end;\n            this.kEvents = Math.max(this.kEvents, a.count);\n            this.added = true;\n            break;\n        }\n        if(end === a.end) {\n            a.count++;\n            a.end = end;\n            this.kEvents = Math.max(this.kEvents, a.count); \n            this.added = true;\n            break;\n        } \n        if(a.start === start && a.end < end ) {\n            a.count++;\n            this.kEvents = Math.max(this.kEvents, a.count);\n            start = a.end;\n        }\n    }\n    if(!added) {\n        this.intersections.push({start, end, count: 1});\n        this.kEvents = Math.max(this.kEvents, 1);\n    }\n    return this.kEvents;\n};",
        "solution_java": "class MyCalendarThree {\n\n    TreeMap<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}",
        "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};"
    },
    {
        "title": "Minimum Operations to Make a Uni-Value Grid",
        "algo_input": "You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.\n\nA uni-value grid is a grid where all the elements of it are equal.\n\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n\n&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",
        "solution_py": "class Solution:\n    def minOperations(self, grid: List[List[int]], x: int) -> int:\n        \n        m = len(grid)\n        n = len(grid[0])\n\t\t\n\t\t# handle the edge case\n        if m==1 and n==1: return 0\n\t\t\n\t\t# transform grid to array, easier to operate\n        arr = [] \n        for i in range(m):\n            arr+=grid[i]\n        \n        arr.sort()\n        \n\t\t# the median is arr[len(arr)//2] when len(arr) is odd\n\t\t# or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even.\n        cand1 = arr[len(arr)//2]\n        cand2 = arr[len(arr)//2-1]\n        \n        return min(\n            self.get_num_operations_to_target(grid, cand1, x),\n            self.get_num_operations_to_target(grid, cand2, x)\n        )\n        \n        \n    def get_num_operations_to_target(self, grid, target,x):\n\t\t\"\"\"Get the total number of operations to transform all grid elements to the target value.\"\"\"\n        ans = 0\n        for i in range(len(grid)):\n            for j in range(len(grid[0])):\n                if abs(grid[i][j]-target)%x!=0:\n                    return -1\n                else:\n                    ans+=abs(grid[i][j]-target)//x\n\n        return ans\n                ",
        "solution_js": "var minOperations = function(grid, x) {\n    \n    let remainder = -Infinity, flatten = [], res = 0;\n    \n    for(let i = 0;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Maximum Difference Between Node and Ancestor",
        "algo_input": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.\n\nA node a is an ancestor of b if either: any child of a is equal to b&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",
        "solution_py": "class Solution:\n    def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n        self.max_diff = float('-inf')\n        \n        def dfs(node,prev_min,prev_max):\n            if not node:\n                return\n            dfs(node.left,min(prev_min,node.val),max(prev_max,node.val))\n            dfs(node.right,min(prev_min,node.val),max(prev_max,node.val))\n            self.max_diff = max(abs(node.val-prev_min),abs(node.val-prev_max),self.max_diff)\n        dfs(root,root.val,root.val)\n        return self.max_diff",
        "solution_js": "var maxAncestorDiff = function(root) {\n    let ans = 0;\n    const traverse = (r = root, mx = root.val, mn = root.val) => {\n        if(!r) return;\n        ans = Math.max(ans, Math.abs(mx - r.val), Math.abs(mn - r.val));\n        mx = Math.max(mx, r.val);\n        mn = Math.min(mn, r.val);\n        traverse(r.left, mx, mn);\n        traverse(r.right, mx, mn);\n    }\n    traverse();\n    return ans;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n    public int maxAncestorDiff(TreeNode root) {\n\n        if (root == null) return 0;\n\n        return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE);\n    }\n\n    public int find(TreeNode root, int min, int max) {\n        if (root == null) return Math.abs(max-min);\n\n        min = Math.min(min, root.val);\n        max = Math.max(max, root.val);\n\n        return Math.max(find(root.left, min, max), find(root.right, min, max));\n    }\n\n}",
        "solution_c": "class Solution {\nprivate:\n    int maxDiff;\n    pair <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};"
    },
    {
        "title": "Minesweeper",
        "algo_input": "Let's play the minesweeper game (Wikipedia, online game)!\n\nYou are given an m x n char matrix board representing the game board where:\n\n\n\t'M' represents an unrevealed mine,\n\t'E' represents an unrevealed empty square,\n\t'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),\n\tdigit ('1' to '8') represents how many mines are adjacent to this revealed square, and\n\t'X' represents a revealed mine.\n\n\nYou are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').\n\nReturn the board after revealing this position according to the following rules:\n\n\n\tIf a mine 'M' is revealed, then the game is over. You should change it to 'X'.\n\tIf an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.\n\tIf an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.\n\tReturn the board when no more squares will be revealed.\n\n\n&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",
        "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        ",
        "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};",
        "solution_java": "class Solution {\n    public char[][] updateBoard(char[][] board, int[] click) {\n        int r = click[0];\n        int c = click[1];\n        if(board[r][c] == 'M')\n        {\n            board[r][c] = 'X';\n            return board;\n        }\n        dfs(board, r, c);\n        return board;\n    }\n\n    private void dfs(char[][]board, int r, int c)\n    {\n        if(r < 0 || r >= board.length || c >= board[0].length || c < 0 || board[r][c] == 'B')//Stop case\n            return;\n        int num = countMine(board, r, c);//count how many adjacent mines\n        if(num != 0)\n        {\n            board[r][c] = (char)('0' + num);\n            return;\n        }\n        else\n        {\n            board[r][c] = 'B';\n            dfs(board, r + 1, c);//recursively search all neighbors\n            dfs(board, r - 1, c);\n            dfs(board, r, c + 1);\n            dfs(board, r, c - 1);\n            dfs(board, r - 1, c - 1);\n            dfs(board, r + 1, c - 1);\n            dfs(board, r - 1, c + 1);\n            dfs(board, r + 1, c + 1);\n        }\n    }\n\n    private int countMine(char[][]board, int r, int c)\n    {\n        int count = 0;\n        for(int i = r - 1; i <= r + 1; ++i)\n        {\n            for(int j = c - 1; j <= c + 1; ++j)\n            {\n                if(i >= 0 && i < board.length && j >= 0 && j < board[0].length)\n                {\n                    if(board[i][j] == 'M')\n                        count++;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int m, n ;\n    vector<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};"
    },
    {
        "title": "Merge BSTs to Create Single BST",
        "algo_input": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:\n\n\n\tSelect two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].\n\tReplace the leaf node in trees[i] with trees[j].\n\tRemove trees[j] from trees.\n\n\nReturn the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.\n\nA BST (binary search tree) is a binary tree where each node satisfies the following property:\n\n\n\tEvery node in the node's left subtree has a value&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",
        "solution_py": "class Solution:\n    def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n        n = len(trees)\n        if n == 1: return trees[0]\n\n        value_to_root = {} # Map each integer root value to its node\n        appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf\n        self.saw_conflict = False # If this is ever true, break out of function and return None\n        leaf_value_to_parent_node = {}\n\n        def is_leaf_node(curr: TreeNode) -> bool:\n            return curr.left is None and curr.right is None\n\n        def get_size(curr: TreeNode) -> int: # DFS to count Binary Tree Size\n            if curr is None: return 0\n            return 1 + get_size(curr.left) + get_size(curr.right)\n\n        def is_valid_bst(curr: TreeNode, lo=-math.inf, hi=math.inf) -> bool: # Standard BST validation code\n            if curr is None: return True\n            return all((lo < curr.val < hi,\n                        is_valid_bst(curr.left, lo, curr.val),\n                        is_valid_bst(curr.right, curr.val, hi)))\n\n        def process_child(child_node: TreeNode, parent: TreeNode) -> None:\n            if child_node is None:\n                return None\n            elif child_node.val in leaf_value_to_parent_node or child_node.val in appeared_as_middle_child:\n                self.saw_conflict = True # Already saw this child node's value in a non-root node\n            elif is_leaf_node(child_node):\n                leaf_value_to_parent_node[child_node.val] = parent\n            elif child_node.val in value_to_root:\n                self.saw_conflict = True\n            else:\n                appeared_as_middle_child.add(child_node.val)\n                process_child(child_node.left, child_node)\n                process_child(child_node.right, child_node)\n\n        def process_root(curr_root: TreeNode) -> None:\n            value_to_root[curr_root.val] = curr_root\n\n            if curr_root.val in appeared_as_middle_child:\n                self.saw_conflict = True\n            else:\n                process_child(curr_root.left, curr_root)\n                process_child(curr_root.right, curr_root)\n\n        for root_here in trees:\n            process_root(root_here)\n            if self.saw_conflict: return None\n\n        final_expected_size = len(leaf_value_to_parent_node) + len(appeared_as_middle_child) + 1\n\n        final_root = None # The root of our final BST will be stored here\n        while value_to_root:\n            root_val, root_node_to_move = value_to_root.popitem()\n\n            if root_val not in leaf_value_to_parent_node: # Possibly found main root\n                if final_root is None:\n                    final_root = root_node_to_move\n                else:\n                    return None # Found two main roots\n            else:\n                new_parent = leaf_value_to_parent_node.pop(root_val)\n                if new_parent.left is not None and new_parent.left.val == root_val:\n                    new_parent.left = root_node_to_move\n                    continue\n                elif new_parent.right is not None and new_parent.right.val == root_val:\n                    new_parent.right = root_node_to_move\n                else:\n                    return None # Didn't find a place to put this node\n\n        # Didn't find any candidates for main root, or have a cycle, or didn't use all trees\n        if final_root is None or not is_valid_bst(final_root) or get_size(final_root) != final_expected_size:\n            return None\n\n        return final_root",
        "solution_js": "var canMerge = function(trees) {\n    let Node={},indeg={}\n    // traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node\n    let dfs=(node,leftparent=null,rightparent=null)=>{\n        if(!node)return\n        indeg[node.val]=indeg[node.val]||Number(leftparent!==null||rightparent!==null)\n        node.lp=leftparent,node.rp=rightparent\n        dfs(node.left,node,null),dfs(node.right,null,node)\n    }\n    for(let root of trees)\n        Node[root.val]=root,\n        dfs(root)\n    //there are a lot of potential roots=> no bueno\n    if(Object.values(indeg).reduce((a,b)=>a+b)!=Object.keys(indeg).length-1)\n        return null\n    //find THE root\n    let bigRoot,timesMerged=0\n    for(let root of trees)\n        if(indeg[root.val]===0)\n            bigRoot=root\n    // traverse the tree while replacing each leaf that can be replaced\n    let rec=(node=bigRoot)=>{\n        if(!node)\n            return\n        if(!node.left&&!node.right){\n            let toadd=Node[node.val]\n            Node[node.val]=undefined //invalidating the trees you already used\n            if(toadd===undefined)\n                return\n            //make the change\n            if(node.lp===null&&node.rp===null)\n                return\n            else if(node.lp!==null)\n                node.lp.left=toadd\n            else\n                node.rp.right=toadd\n            timesMerged++\n            rec(toadd)\n        }\n        else\n            rec(node.left),rec(node.right)\n    }\n    rec()\n    var isValidBST = function(node,l=-Infinity,r=Infinity) { //l and r are the limits node.val should be within\n        if(!node)\n            return true\n        if(node.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};",
        "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}",
        "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};"
    },
    {
        "title": "Watering Plants",
        "algo_input": "You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.\n\nEach plant needs a specific amount of water. You will water the plants in the following way:\n\n\n\tWater the plants in order from left to right.\n\tAfter watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.\n\tYou cannot refill the watering can early.\n\n\nYou are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.\n\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.\n\n&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",
        "solution_py": "class Solution:\n    def wateringPlants(self, plants: List[int], capacity: int) -> int:\n        result = 0\n        curCap = capacity\n\n        for i in range(len(plants)):\n            if curCap >= plants[i]:\n                curCap -= plants[i]\n                result += 1\n\n            else:\n                result += i * 2 + 1\n                curCap = capacity - plants[i]\n\n        return result",
        "solution_js": "var wateringPlants = function(plants, capacity) {\n    var cap = capacity;\n    var steps = 0;\n    for(let i = 0; i < plants.length;i++){\n        if(cap >= plants[i]){\n            steps = steps + 1;\n        }else{\n            cap = capacity;\n            steps = steps + (2 *i + 1);\n        }\n        cap = cap - plants[i];\n    }\n    return steps;\n};",
        "solution_java": "class Solution {\n    public int wateringPlants(int[] plants, int capacity) {\n        int count=0,c=capacity;\n        for(int i=0;i<plants.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}",
        "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};"
    },
    {
        "title": "Partition Array According to Given Pivot",
        "algo_input": "You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:\n\n\n\tEvery element less than pivot appears before every element greater than pivot.\n\tEvery element equal to pivot appears in between the elements less than and greater than pivot.\n\tThe relative order of the elements less than pivot and the elements greater than pivot is maintained.\n\t\n\t\tMore formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i &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",
        "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",
        "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};",
        "solution_java": "// Time complexity = 2n = O(n)\n// Space complexity = O(1), or O(n) if the result array is including in the complexity analysis.\n\nclass Solution {\n    public int[] pivotArray(int[] nums, int pivot) {\n        int[] result = new int[nums.length];\n        int left = 0, right = nums.length - 1;\n\n        for(int i = 0; i < nums.length; i++) {\n            if(nums[i] < pivot) {\n                result[left++] = nums[i];\n            }\n            if(nums[nums.length - 1 - i] > pivot) {\n                result[right--] = nums[nums.length - 1 - i];\n            }\n        }\n\n        while(left <= right) {\n            result[left++] = pivot;\n            result[right--] = pivot;\n        }\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<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};"
    },
    {
        "title": "Check if Numbers Are Ascending in a Sentence",
        "algo_input": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.\n\n\n\tFor example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words.\n\n\nGiven a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).\n\nReturn true if so, or false otherwise.\n\n&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",
        "solution_py": "class Solution:\n    def areNumbersAscending(self, s):\n        nums = re.findall(r'\\d+', s)\n        return nums == sorted(set(nums), key=int)",
        "solution_js": "var areNumbersAscending = function(s) {\n    const numbers = [];\n    const arr = s.split(\" \");\n    for(let i of arr) {\n        if(isFinite(i)) {\n            if(numbers.length > 0 && numbers[numbers.length - 1] >= i) {\n                return false;\n            }\n            numbers.push(+i);\n        }\n    }\n    return true\n};",
        "solution_java": "// Space Complexity: O(1)\n// Time Complexity: O(n)\nclass Solution {\n    public boolean areNumbersAscending(String s) {\n        int prev = 0;\n\n        for(String token: s.split(\" \")) {\n            try {\n                int number = Integer.parseInt(token);\n                if(number <= prev)\n                    return false;\n                prev = number;\n            }\n            catch(Exception e) {}\n        }\n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool areNumbersAscending(string s) {\n        s.push_back(' '); // for last number calculation\n        int prev = -1;\n        string num;\n        \n        for(int i = 0 ; i < s.size() ; ++i)\n        {\n            char ch = s[i];\n            if(isdigit(ch))\n                num += ch;\n            else if(ch == ' ' and isdigit(s[i - 1]))\n            {\n                if(stoi(num) <= prev) // number is not strictly increasing\n                    return false;\n                prev = stoi(num);\n                num = \"\";\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Decode XORed Array",
        "algo_input": "There is a hidden integer array arr that consists of n non-negative integers.\n\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].\n\nYou are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].\n\nReturn the original array arr. It can be proved that the answer exists and is unique.\n\n&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",
        "solution_py": "class Solution:\n    def decode(self, encoded: List[int], first: int) -> List[int]:\n        return [first] + [first:= first ^ x for x in encoded]",
        "solution_js": "var decode = function(encoded, first) {\n    return [first].concat(encoded).map((x,i,a)=>{return i===0? x : a[i] ^= a[i-1]});\n};",
        "solution_java": "class Solution {\n    public int[] decode(int[] encoded, int first) {\n        int[] ans = new int[encoded.length + 1];\n        ans[0] = first;\n        for (int i = 0; i < encoded.length; i++) {\n            ans[i + 1] = ans[i] ^ encoded[i];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<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};"
    },
    {
        "title": "Minimum Changes To Make Alternating Binary String",
        "algo_input": "You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.\n\nThe string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not.\n\nReturn the minimum number of operations needed to make s alternating.\n\n&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",
        "solution_py": "class Solution:\n    def minOperations(self, s: str) -> int:\n        count = 0\n        count1 = 0\n        for i in range(len(s)):\n            if i % 2 == 0:\n                if s[i] == '1':\n                    count += 1\n                if s[i] == '0':\n                    count1 += 1\n            else:\n                if s[i] == '0':\n                    count += 1\n                if s[i] == '1':\n                    count1 += 1\n        return min(count, count1)",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minOperations = function(s) {\n    let counter1=0;\n    let counter2=0;\n    for(let i=0;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Positions of Large Groups",
        "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",
        "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",
        "solution_js": "// 77 ms, faster than 97.56%\n// 45 MB, less than 87.81%\nvar largeGroupPositions = function(s) {\n\tlet re = /(.)\\1{2,}/g;\n\tlet ans = [];\n\twhile ((rslt = re.exec(s)) !== null) {\n\t\tans.push([rslt.index, rslt.index + rslt[0].length-1]);\n\t}\n\treturn ans;\n};",
        "solution_java": "class Solution {\n    public List<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}",
        "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};"
    },
    {
        "title": "Three Divisors",
        "algo_input": "Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\n\nAn integer m is a divisor of n if there exists an integer k such that n = k * m.\n\n&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",
        "solution_py": "import math\nclass Solution:\n    def isThree(self, n: int) -> bool:\n        primes = {3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1, 67:1, 71:1, 73:1, 79:1, 83:1, 89:1, 97:1}\n        if n == 4:\n            return True\n        else:\n            a = math.sqrt(n)\n\n            if primes.get(a,0):\n                return True\n            else:\n                return False",
        "solution_js": "var isThree = function(n) {\n    var set = new Set();\n    for(var i = 1; i<=Math.sqrt(n) && set.size <= 3; i++)\n    {\n        if(n % i === 0)\n        {\n            set.add(i);\n            set.add(n / i);\n        }\n    }\n    return set.size===3;  \n};",
        "solution_java": "class Solution {\n    public boolean isThree(int n) {\n        if(n<4 ) return false;\n        int res = (int)Math.sqrt(n);\n        for(int i=2;i*i<n;i++){\n            if(res%i ==0) return false;\n        }\n        return true;\n}}",
        "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};"
    },
    {
        "title": "Best Position for a Service Centre",
        "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",
        "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)",
        "solution_js": "/**\n * @param {number[][]} positions\n * @return {number}\n */\nvar getMinDistSum = function(positions) {\n    /**\n      identify the vertical range and horizontal range\n      \n      start from the center of positions\n      calc the distance\n        test the 4 direction with a certain step\n            if any distance is closer, choose it as the new candidate\n        if all 4 are further, reduce the step\n    **/\n    \n    \n    let xSum = 0;\n    let ySum = 0;\n    for (const [x, y] of positions) {\n        xSum += x;\n        ySum += y;\n    }\n    \n    let n = positions.length;\n    let x = xSum / n;\n    let y = ySum / n;\n    \n    let step = 0.5;\n    const dirs = [[0, 1], [0, -1], [-1, 0], [1, 0]];\n    while (step >= 10 ** -5) {\n        \n        const dist = calcDist(x, y);\n        let found = false;\n        for (const [xDiff, yDiff] of dirs) {\n            const newX = x + xDiff * step;\n            const newY = y + yDiff * step;\n            const newDist = calcDist(newX, newY);\n            \n            // console.log(x, y, newDist, dist);\n            if (newDist < dist) {\n                x = newX;\n                y = newY;\n                found = true;\n                break;\n            }\n        }\n        \n        if (!found) {\n            step /= 2;\n        }\n    }\n    \n    return calcDist(x, y);\n    \n    \n    function calcDist(x, y) {\n        let dist = 0;\n        for (const [posX, posY] of positions) {\n            dist += Math.sqrt((x - posX) ** 2 + (y - posY) ** 2);\n        }\n        return dist;\n    }\n};",
        "solution_java": "class Solution {\n    private static final double MIN_STEP = 0.0000001;\n    private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n    public double getMinDistSum(int[][] positions) {\n        double cx = 0, cy = 0;\n        int n = positions.length;\n        for (int[] pos: positions) {\n            cx += pos[0];\n            cy += pos[1];\n        }\n        cx /= n; cy /= n;\n        Node center = new Node(cx, cy, totalDistance(positions, cx, cy));\n\n        double step = 50.0;\n        while (step > MIN_STEP) {\n            Node min = center;\n            for (int[] direction: DIRECTIONS) {\n                double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step;\n                double totalDist = totalDistance(positions, dx, dy);\n                if (totalDist < center.dist) min = new Node(dx, dy, totalDist);\n            }\n            if (center == min) step /= 2;\n            center = min;\n        }\n\n        return center.dist;\n    }\n\n    private double sq(double p) {\n        return p * p;\n    }\n\n    private double dist(int[] pos, double x, double y) {\n        return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1]));\n    }\n\n    private double totalDistance(int[][] positions, double x, double y) {\n        double dist = 0;\n        for (int[] pos: positions) dist += dist(pos, x, y);\n        return dist;\n    }\n\n    private static class Node {\n        double x, y, dist;\n        Node (double x, double y, double dist) {\n            this.x = x;\n            this.y = y;\n            this.dist = dist;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    const double MIN_STEP = 0.000001; // With 0.00001 not AC\n\n    const int dx[4] = {0, 0, 1,-1};\n    const int dy[4] = {1, -1, 0, 0};\n\n    double totalDist(vector<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};"
    },
    {
        "title": "Combination Sum IV",
        "algo_input": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to&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",
        "solution_py": "class Solution:\n    def combinationSum4(self, nums: List[int], target: int) -> int:\n        dp = [0] * (target+1)\n        dp[0] = 1\n        for i in range(1, target+1):\n            for num in nums: \n                num_before = i - num\n                if num_before >= 0:\n                    dp[i] += dp[num_before]\n        return dp[target]",
        "solution_js": "var combinationSum4 = function(nums, target) {\n    const dp = Array(target + 1).fill(0);\n    \n    nums.sort((a,b) => a - b);\n    \n    for(let k=1; k <= target; k++) {\n        for(let n of nums) {\n            if(k < n) break;\n            dp[k] += (k == n) ? 1 : dp[k-n];\n        }\n    }\n     \n    return dp[target];\n};",
        "solution_java": "class Solution {\n    public int combinationSum4(int[] nums, int target) {\n        Integer[] memo = new Integer[target + 1];\n        return recurse(nums, target, memo);\n    }\n    \n    public int recurse(int[] nums, int remain, Integer[] memo){\n        \n        if(remain < 0) return 0;\n        if(memo[remain] != null) return memo[remain];\n        if(remain == 0) return 1;\n        \n        int ans = 0;\n        for(int i = 0; i < nums.length; i++){\n            ans += recurse(nums, remain - nums[i], memo);\n        }\n        \n        memo[remain] = ans;\n        return memo[remain];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int combinationSum4(vector<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};"
    },
    {
        "title": "Self Crossing",
        "algo_input": "You are given an array of integers distance.\n\nYou start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.\n\nReturn true if your path crosses itself, and false if it does not.\n\n&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",
        "solution_py": "class Solution:\n    def isSelfCrossing(self, x):\n        n = len(x)\n        if n < 4: return False\n        for i in range(3, n):\n            if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True\n            if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True\n            if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] and 0<=x[i-3]-x[i-1]<=x[i-5]: return True\n        return False\n        ",
        "solution_js": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b)          return true;  // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true;  // cross [i - 4]\n\nif (x[i] < a)       arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}",
        "solution_java": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b)          return true;  // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true;  // cross [i - 4]\n\nif (x[i] < a)       arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSelfCrossing(vector<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};"
    },
    {
        "title": "Kth Ancestor of a Tree Node",
        "algo_input": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.\n\nThe kth ancestor of a tree node is the kth node in the path from that node to the root node.\n\nImplement the TreeAncestor class:\n\n\n\tTreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.\n\tint getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.\n\n\n&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",
        "solution_py": "from math import ceil, log2\nfrom typing import List\n\nNO_PARENT = -1\n\nclass TreeAncestor:\n    def __init__(self, n: int, parent: List[int]):\n        self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]\n        self.__initialize(parent)\n\n    def __initialize(self, parent: List[int]):\n        self.parent[0], prev = parent, parent\n\n        for jump_pow in range(1, len(self.parent)):\n            cur = self.parent[jump_pow]\n\n            for i, p in enumerate(prev):\n                if p != NO_PARENT:\n                    cur[i] = prev[p]\n\n            prev = cur\n\n    def getKthAncestor(self, node: int, k: int) -> int:\n        jump_pow = self.jump_pow\n\n        while k > 0 and node != NO_PARENT:\n            jumps = 1 << jump_pow\n\n            if k >= jumps:\n                node = self.parent[jump_pow][node]\n                k -= jumps\n            else:\n                jump_pow -= 1\n\n        return node\n\n    @property\n    def jump_pow(self) -> int:\n        return len(self.parent) - 1",
        "solution_js": "/**\n * @param {number} n\n * @param {number[]} parent\n */\nvar TreeAncestor = function(n, parent) {\n    this.n = n;\n    this.parent = parent;\n};\n\n/** \n * @param {number} node \n * @param {number} k\n * @return {number}\n */\n\n/*\nQs:\n1. Is the given tree a binary tree or n-ary tree?\n2. Can k be greater than possible (the total number of ancestors of given node)?\n\nEvery node has a parent except the root.\n1. Check if given node has a parent. If not, return -1.\n2. Set given node as the current ancestor and start a while loop which continues while k is greater than 0.\nAt each iteration, we set `ancestor` to the parent of current `ancestor` and decrement k. If k is still greater\nthan 0 but ancestor is -1, that means k is greater than possible. Hence, we return -1. Else, while loop will\nend when we are at the correct k-th ancestor. We return ancestor.\n*/\nTreeAncestor.prototype.getKthAncestor = function(node, k) {\n    // check if given node has a parent\n    if (this.parent[node] === -1) return -1;\n    let ancestor = node;\n    while (k > 0) {\n        if (ancestor === -1) return -1; // k is greater than total number of ancestors of given node\n        ancestor = this.parent[ancestor];\n        k--;\n    }\n    return ancestor;\n    // T.C: O(k)\n};",
        "solution_java": "class TreeAncestor {\n    int n;\n    int[] parent;\n    List<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}",
        "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};"
    },
    {
        "title": "Magic Squares In Grid",
        "algo_input": "A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.\n\nGiven a row x col&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",
        "solution_py": "class Solution:\n\n    digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n    @classmethod\n    def magic_3_3(cls, square: List[List[int]]) -> bool:\n        if set(sum(square, [])) != Solution.digits:\n            return False\n        sum_row0 = sum(square[0])\n        for r in range(1, 3):\n            if sum(square[r]) != sum_row0:\n                return False\n        if any(sum(col) != sum_row0 for col in zip(*square)):\n            return False\n        sum_main_diagonal = sum_second_diagonal = 0\n        for i in range(3):\n            sum_main_diagonal += square[i][i]\n            sum_second_diagonal += square[i][2 - i]\n        return sum_main_diagonal == sum_second_diagonal == sum_row0\n\n    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n        count = 0\n        rows, cols = len(grid), len(grid[0])\n        for r in range(rows - 2):\n            for c in range(cols - 2):\n                if Solution.magic_3_3([grid[row_idx][c: c + 3]\n                                       for row_idx in range(r, r + 3)]):\n                    count += 1\n        return count",
        "solution_js": "var numMagicSquaresInside = function(grid) {\n    let res = 0;\n    for(let i = 0; i < grid.length - 2; i++){\n       for(let j = 0; j < grid[0].length - 2; j++){\n           //only check 4\n           if(grid[i][j]+grid[i][j+1]+grid[i][j+2]==15\n           && grid[i][j]+grid[i+1][j]+grid[i+2][j]==15\n           && grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]==15\n           && grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]==15){\n               let set = new Set();\n           for(let a = i; a<=i+2; a++){\n              for(let b = j; b<=j+2; b++){\n                  if(grid[a][b]>=1&&grid[a][b]<=9) set.add(grid[a][b]);\n           }}\n           if(set.size===9) res++;\n       }}}\n    return res;\n};",
        "solution_java": "class Solution {\n\tpublic int numMagicSquaresInside(int[][] grid) {\n\t\tint n=grid.length,m=grid[0].length,count=0;\n\t\tfor(int i=0;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}",
        "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};"
    },
    {
        "title": "Maximum Nesting Depth of the Parentheses",
        "algo_input": "A string is a valid parentheses string (denoted VPS) if it meets one of the following:\n\n\n\tIt is an empty string \"\", or a single character not equal to \"(\" or \")\",\n\tIt can be written as AB (A concatenated with B), where A and B are VPS's, or\n\tIt can be written as (A), where A is a VPS.\n\n\nWe can similarly define the nesting depth depth(S) of any VPS S as follows:\n\n\n\tdepth(\"\") = 0\n\tdepth(C) = 0, where C is a string with a single character not equal to \"(\" or \")\".\n\tdepth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.\n\tdepth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\n\n\nFor example, \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n\nGiven a VPS represented as string s, return the nesting depth of s.\n\n&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",
        "solution_py": "class Solution:\n    def maxDepth(self, s: str) -> int:\n        ans = cur = 0\n        for c in s:\n            if c == '(':\n                cur += 1\n                ans = max(ans, cur)\n            elif c == ')':\n                cur -= 1\n        return ans ",
        "solution_js": "var maxDepth = function(s) {\n    let maxCount = 0, count = 0;\n    for (let i = 0; i < s.length; i++) {\n        if (s[i] === '(') {\n            maxCount = Math.max(maxCount, ++count);\n        } else if (s[i] === ')') {\n            count--;\n        }\n    }\n    return maxCount;\n};",
        "solution_java": "class Solution {\n    public int maxDepth(String s) {\n        int count = 0;   //count current dept of \"()\"\n        int max = 0;     //count max dept of \"()\"\n\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == '(') {\n                count++;\n            } else if (s.charAt(i) == ')') {\n                count--;\n            }\n            max = Math.max(count, max);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDepth(string s) {\n        int maxi=0,curr=0;\n        for(int i=0;i<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};"
    },
    {
        "title": "Find All People With Secret",
        "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",
        "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)",
        "solution_js": "var findAllPeople = function(n, meetings, firstPerson) {\n    const timeToMeeting = mapSortedTimeToMeetings(meetings);\n\n    const peopleThatCurrentlyHaveSecret = new Set([0, firstPerson]);\n    for (const peopleInMeetings of timeToMeeting.values()) {\n        const personToMeetingsWithPeople =\n            mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings);\n        let peopleInMeetingsWithSecret =\n            findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret);\n\n        // BFS algorithm\n        while (peopleInMeetingsWithSecret.size > 0) {\n            const nextPeopleInMeetingsWithSecret = new Set();\n            for (const attendee of peopleInMeetingsWithSecret) {\n                for (const personInMeetingWithAttendee of personToMeetingsWithPeople[attendee]) {\n\n                    // only add new people that have the secret otherwise there will be an\n                    // infinite loop\n                    if (!peopleThatCurrentlyHaveSecret.has(personInMeetingWithAttendee)) {\n                        nextPeopleInMeetingsWithSecret.add(personInMeetingWithAttendee);\n                        peopleThatCurrentlyHaveSecret.add(personInMeetingWithAttendee);\n                    }\n                }\n            }\n            peopleInMeetingsWithSecret = nextPeopleInMeetingsWithSecret;\n        }\n    }\n    return [...peopleThatCurrentlyHaveSecret];\n};\n\n// groups all the meetings by time\n// keys (time) is sorted in ascending order\nfunction mapSortedTimeToMeetings(meetings) {\n    meetings.sort((a, b) => a[2] - b[2]);\n\n    const timeToMeeting = new Map();\n    for (const [person1, person2, time] of meetings) {\n        if (!timeToMeeting.has(time)) {\n            timeToMeeting.set(time, []);\n        }\n        timeToMeeting.get(time).push([person1, person2]);\n    }\n    return timeToMeeting;\n}\n\n// creates an adjacency list of people and people they are having meetings with\nfunction mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings) {\n    const personToMeetingsWithPeople = {};\n    for (const [person1, person2] of peopleInMeetings) {\n        if (!personToMeetingsWithPeople[person1]) {\n            personToMeetingsWithPeople[person1] = [];\n        }\n        if (!personToMeetingsWithPeople[person2]) {\n            personToMeetingsWithPeople[person2] = [];\n        }\n        personToMeetingsWithPeople[person1].push(person2);\n        personToMeetingsWithPeople[person2].push(person1);\n    }\n    return personToMeetingsWithPeople;\n}\n\n// finds all the people that are in meetings that have the secret\n// set data structue is used so that people are not duplicated\nfunction findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret) {\n    const peopleInMeetingsWithSecret = new Set();\n    for (const peopleInMeeting of peopleInMeetings) {\n        for (const person of peopleInMeeting) {\n            if (peopleThatCurrentlyHaveSecret.has(person)) {\n                peopleInMeetingsWithSecret.add(person);\n            }\n        }\n    }\n    return peopleInMeetingsWithSecret;\n}",
        "solution_java": "class Solution {\n    public List<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}",
        "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};"
    },
    {
        "title": "Longest Common Subsequence",
        "algo_input": "Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.\n\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\n\n\tFor example, \"ace\" is a subsequence of \"abcde\".\n\n\nA common subsequence of two strings is a subsequence that is common to both strings.\n\n&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",
        "solution_py": "class Solution:\n    def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n        def lcs(ind1,ind2):\n            prev=[0 for i in range(ind2+1)]\n            curr=[0 for i in range(ind2+1)]\n            \n            for i in range(1,ind1+1):\n                for j in range(1,ind2+1):\n                    if text1[i-1]==text2[j-1]:\n                        curr[j]=1+prev[j-1]\n                         \n                    else:\n                        curr[j]=max(prev[j],curr[j-1])\n                prev=list(curr) # remember to use a new list for prev\n\n            return prev[-1]\n                    \n        \n        ans=lcs(len(text1),len(text2))\n        return ans",
        "solution_js": "/**\n * @param {string} text1\n * @param {string} text2\n * @return {number}\n */\nlet memo\nconst dp=(a,b,i,j)=>{\n    if(i===0||j===0)return 0;\n    if(memo[i][j]!=-1)return memo[i][j];\n    if(a[i-1]===b[j-1]){\n        return memo[i][j]= 1+ dp(a,b,i-1,j-1);\n    }else{\n        return memo[i][j]=Math.max(dp(a,b,i-1,j),dp(a,b,i,j-1));\n    }\n\n}\nconst bottomUp=(a,b)=>{\n\n    for(let i=1;i<=a.length;i++){\n        for(let j=1;j<=b.length;j++){\n            if(a[i-1]===b[j-1]){\n              memo[i][j]=1+memo[i-1][j-1]\n            }else{\n                memo[i][j]=Math.max(memo[i-1][j],memo[i][j-1]);\n            }\n\n        }\n    }\n\nreturn memo[a.length][b.length]\n\n}\n\nvar longestCommonSubsequence = function(text1, text2) {\n    memo=[];\n    for(let i=0;i<=text1.length;i++){\n        memo[i]=[];\n        for(let j=0;j<=text2.length;j++){\n          if(i===0||j===0)memo[i][j]=0;\n            else memo[i][j]=-1;\n        }\n    }\n    return bottomUp(text1,text2,text1.length,text2.length);\n    // return dp(text1,text2,text1.length,text2.length);\n};",
        "solution_java": "class Solution {\n    public int longestCommonSubsequence(String text1, String text2) {\n        int m = text1.length();\n        int n = text2.length();\n        int[][] dp = new int[m + 1][n + 1];\n\n        for (int i = 1; i <= m; i++) {\n            for (int j = 1; j <= n; j++) {\n                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n                    dp[i][j] = 1 + dp[i - 1][j - 1];\n                } else {\n                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n                }\n            }\n        }\n\n        return dp[m][n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestCommonSubsequence(string text1, string text2) {\n        int dp[1001][1001] = {0};\n        for(int i = 1; i <= text1.size(); i++)\n            for(int j = 1; j <= text2.size(); j++)\n                if(text1[i-1] == text2[j-1]) dp[i][j] = 1 + dp[i-1][j-1];\n                else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n        return dp[text1.size()][text2.size()];\n    }\n};"
    },
    {
        "title": "Decode the Slanted Ciphertext",
        "algo_input": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.\n\noriginalText is placed first in a top-left to bottom-right manner.\n\nThe blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText.\n\nencodedText is then formed by appending all characters of the matrix in a row-wise fashion.\n\nThe characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.\n\nFor example, if originalText = \"cipher\" and rows = 3, then we encode it in the following manner:\n\nThe blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\".\n\nGiven the encoded string encodedText and number of rows rows, return the original string originalText.\n\nNote: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.\n\n&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",
        "solution_py": "class Solution:\n    def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n        n = len(encodedText)\n        cols = n // rows\n        step = cols + 1\n        res = \"\"\n        \n        for i in range(cols):\n            for j in range(i, n, step):\n                res += encodedText[j]\n            \n        return res.rstrip()",
        "solution_js": "var decodeCiphertext = function(encodedText, rows) {\n    const numColumns = encodedText.length / rows;\n    const stringBuilder = [];\n    let nextCol = 1;\n    let row = 0;\n    let col = 0;\n    let index = 0\n    while (index < encodedText.length) {\n        stringBuilder.push(encodedText[index]);\n        if (row === rows - 1 || col === numColumns - 1) {\n            row = 0;\n            col = nextCol;\n            nextCol++;\n        } else {\n            row++;\n            col++;\n        }\n        index = calcIndex(row, col, numColumns);\n    }\n    while (stringBuilder[stringBuilder.length - 1] === ' ') {\n        stringBuilder.pop();\n    }\n    return stringBuilder.join('');\n};\n\nfunction calcIndex(row, col, numColumns) {\n    return row * numColumns + col;\n}",
        "solution_java": "class Solution {\n    public String decodeCiphertext(String str, int rows) {\n\n        //first find column size!!\n    \tint cols=str.length()/rows;\n    \tStringBuilder res=new StringBuilder(),new_res=new StringBuilder();;\n    \tfor(int i=0;i<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}",
        "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};"
    },
    {
        "title": "Reorganize String",
        "algo_input": "Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.\n\nReturn any possible rearrangement of s or return \"\" if not possible.\n\n&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",
        "solution_py": "class Solution:\n\tdef reorganizeString(self, s: str) -> str:\n\t\tc = Counter(s)  # for counting the distinct element \n\t\tpq = []\n\t\tfor k,v in c.items(): heapq.heappush(pq,(-v,k))  #multipy by -1 to make max heap \n\t\tans = ''\n\t\twhile pq :\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif ans and ans[-1] == ch: \n\t\t\t\tif not pq: return '' // if heap is empty we cant make the ans return empty string\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\t\treturn ans",
        "solution_js": "var reorganizeString = function(s) {\n    const charMap = {};\n    const res = [];\n\n    // Store the count of each char\n    for (let char of s) {\n        charMap[char] = (charMap[char] || 0) + 1;\n    }\n\n    // Sort in descending order by count\n    const sortedMap = Object.entries(charMap).sort((a, b) => b[1] - a[1]);\n\n    // Check if we can distribute the first char by every other position.\n    // We only need to check the first char b/c the chars are ordered by count\n    // so if the first char succeeds, all following chars will succeed\n    if (sortedMap[0][1] > Math.floor((s.length + 1) / 2)) return '';\n\n    let position = 0;\n    for (let entry of sortedMap) {\n        const char = entry[0]\n        const count = entry[1];\n        for (let j = 0; j < count; j++) {\n            // Distribute the current char every other position. The same char\n            // will never be placed next to each other even on the 2nd loop\n            // for placing chars in odd positions\n            res[position] = char;\n            position +=2;\n\n            // This will only happen once since total number of chars\n            // will be exactly equal to the length of s\n            if (position >= s.length) position = 1;\n        }\n    }\n\n    return res.join('');\n};",
        "solution_java": "class Solution {\n    public String reorganizeString(String s) {\n        StringBuilder ans=new StringBuilder(\"\");\n        char[] charArray=new char[s.length()];\n        Map<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}",
        "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};"
    },
    {
        "title": "Remove Colored Pieces if Both Neighbors are the Same Color",
        "algo_input": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.\n\nAlice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.\n\n\n\tAlice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.\n\tBob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.\n\tAlice and Bob cannot remove pieces from the edge of the line.\n\tIf a player cannot make a move on their turn, that player loses and the other player wins.\n\n\nAssuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.\n\n&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",
        "solution_py": "class Solution:\n    def winnerOfGame(self, s: str) -> bool:\n        \n        a = b = 0\n        \n        for i in range(1,len(s)-1):\n            if s[i-1] == s[i] == s[i+1]:\n                if s[i] == 'A':\n                    a += 1\n                else:\n                    b += 1\n                    \n        return a>b",
        "solution_js": "var winnerOfGame = function(colors) {\n    const n = colors.length;\n    const stack = [];\n    \n    let alice = 0;\n    let bob = 0;\n    \n    for (let i = 0; i < n; ++i) {\n        const char = colors[i];\n        \n        if (stack.length > 1 && stack[stack.length - 1] === char && stack[stack.length - 2] === char) {\n            stack.pop();\n            \n            if (char === \"A\") ++alice;\n            else ++bob;\n        }\n        stack.push(char);\n    }\n    \n    return alice > bob ? true : false; \n};",
        "solution_java": "class Solution {\n    public boolean winnerOfGame(String colors) {\n        int cntA=0,cntB=0;\n        for(int i=1;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}",
        "solution_c": "class Solution {\npublic:\n    bool winnerOfGame(string colors) {\n        if (colors.size() < 3) return false;\n        int a = 0, b = 0;\n        for (int i = 0; i < colors.size()-2; i++) {\n            if (colors.substr(i, 3) == \"AAA\") a++;\n            else if (colors.substr(i, 3) == \"BBB\") b++;\n        }\n        return a > b;\n    }\n};"
    },
    {
        "title": "Remove Linked List Elements",
        "algo_input": "Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.\n\n&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",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:\n        prev=head\n        cur=head\n        while cur is not None:\n            if cur.val==val:\n                if cur==head:\n                    head=head.next\n                    prev=head\n                else:\n                    prev.next=cur.next\n            else:\n                prev=cur\n            cur=cur.next\n        return head",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} val\n * @return {ListNode}\n */\nvar removeElements = function(head, val) {\n    \n    if(!head)return null\n    \n    //if the val is on the beginning  delete it \n    while( head && head.val===val)head=head.next\n\n    \n    let current=head;\n    let next=head.next;\n    //travers the liste and delete any node has this val    \n   while(next){        \n        if(next.val===val){\n        current.next=next.next\n        }\n        else current=next\n            \n        next=next.next\n        \n    }\n    \n    return head\n};",
        "solution_java": "class Solution {\n    public ListNode removeElements(ListNode head, int val) {\n        if (head == null) {\n            return head;\n        }\n        ListNode result = head;\n        while (head.next != null) {\n            if (head.next.val == val) {\n                head.next = head.next.next;\n            } else {\n                head = head.next;\n            }\n        }\n        if (result.val == val) {\n            result = result.next;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* removeElements(ListNode* head, int val) {\n        ListNode *prv,*cur,*temp;\n        while(head && head->val==val){\n            cur=head;\n            head=head->next;\n            delete(cur);\n        }\n       if(head==NULL) return head;\n        prv=head;\n        cur=head->next;\n        while(cur){\n            if(cur->val==val){\n                temp=cur;\n                prv->next=cur->next;\n                cur=cur->next;\n                delete(temp);\n            }\n            else{\n                prv=cur;\n                cur=cur->next;\n            }\n        }\n        return head;\n\n    }\n};"
    },
    {
        "title": "Prison Cells After N Days",
        "algo_input": "There are 8 prison cells in a row and each cell is either occupied or vacant.\n\nEach day, whether the cell is occupied or vacant changes according to the following rules:\n\n\n\tIf a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.\n\tOtherwise, it becomes vacant.\n\n\nNote that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.\n\nYou are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.\n\nReturn the state of the prison after n days (i.e., n such changes described above).\n\n&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",
        "solution_py": "class Solution:\n    def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n        patternMatch=defaultdict(int) # pattern match\n        totalPrisons=8 # totalPrisons\n        cells= [ str(c) for c in (cells)] # into char type\n        for d in range(1,n+1):\n            tempCell=[]\n            tempCell.append('0') # left corner case\n            for c in range(1,totalPrisons-1):\n                if (cells[c-1]=='1' and cells[c+1]=='1') or (cells[c-1]=='0' and cells[c+1]=='0'):\n                    tempCell.append('1') # insert 1 if first condition met\n                else:\n                    tempCell.append('0') # otherwise 0\n            tempCell.append('0') # right corner case\n            cells=tempCell # update cells\n            pattern= ''.join(tempCell) # insert pattern in hashtable\n            if pattern in patternMatch: # if there is a match\n                day=patternMatch[pattern]\n                remainder= (n%(d-1))-1 # take modulo\n                match= list(patternMatch.keys())[remainder] # find key\n                return [ int(m) for m in match] # return\n            patternMatch[pattern]=d # assign day\n        return [ int(c) for c in (cells)] # return",
        "solution_js": "/**\n * @param {number[]} cells\n * @param {number} n\n * @return {number[]}\n */\n\nvar prisonAfterNDays = function(cells, n) {\n    const set = new Set()\n    let cycleDuration = 0\n    \n    while(n--) {\n        const nextCells = getNextCells(cells)\n\n        // 1. Get cycle length\n        if(!set.has(String(nextCells))){\n            set.add(String(nextCells))\n            cycleDuration++\n            cells = nextCells\n            \n        } else {\n            // 2. Use cycle length to iterate once more to get to correct order\n            let remainderToMove = n%cycleDuration\n            while(remainderToMove >= 0) {\n                remainderToMove--\n                cells = getNextCells(cells)\n            }\n            break\n        }        \n        \n    }\n    \n    return cells\n};\n\nfunction getNextCells(cells) {\n    let temp = [...cells]\n    for(let i = 0; i < 8; i++) {\n        if(i>0 && i < 7 && cells[i-1] === cells[i+1]) {\n            temp[i] = 1\n        } else {\n            temp[i] = 0\n        }\n    }\n\n    return temp\n}\n\n// 0\n// 1\n// 2\n// n\n\n// 1 000 000 % n ",
        "solution_java": "class Solution {\n    public int[] prisonAfterNDays(int[] cells, int n) {\n        // # Since we have 6 cells moving cells (two wil remain unchaged at anytime) \n        // # the cycle will restart after 14 iteration\n        // # 1- The number of days if smaller than 14 -> you brute force O(13)\n        // # 2- The number is bigger than 14\n        // #                       - You do a first round of 14 iteration\n        // #                       - Than you do a second round of n%14 iteration\n        // #                       ===> O(27)\n        \n        n = n % 14 == 0 ? 14 : n%14;\n        int temp[] = new int[cells.length];\n        \n        while(n-- > 0)\n        {\n            for(int i=1; i <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}",
        "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};"
    },
    {
        "title": "Pizza With 3n Slices",
        "algo_input": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\n\n\n\tYou will pick any pizza slice.\n\tYour friend Alice will pick the next slice in the anti-clockwise direction of your pick.\n\tYour friend Bob will pick the next slice in the clockwise direction of your pick.\n\tRepeat until there are no more slices of pizzas.\n\n\nGiven an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.\n\n&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",
        "solution_py": " class Solution:\n    def maxSizeSlices(self, slices: List[int]) -> int:\n       ** #This solve function mainly on work on the idea of A Previous dp problem House Robber II \n\t\t#If we take the first slice then we cant take the second slice and vice versa**\n\t\tdef solve(slices,start,end,n,dp):\n            if start>end or n==0:\n                return 0\n            if dp[start][n] !=-1:\n                return dp[start][n]\n            include = slices[start] + solve(slices,start+2,end,n-1,dp)\n            \n            exclude = 0 + solve(slices,start+1,end,n,dp)\n            \n            dp[start][n]= max(include,exclude)\n            return dp[start][n]\n        dp1=[[-1 for i in range(k+1)]for _ in range(k+1)]\n        dp2=[[-1 for i in range(k+1)]for _ in range(k+1)]\n        \n        option1=solve(slices,0,k-2,k//3,dp1)#Taking the the first slice , now we cant take the last slice and next slice\n        option2=solve(slices,1,k-1,k//3,dp2)#Taking the the second slice , now we cant take the second last slice and next slice\n        \n        return max(option1,option2)",
        "solution_js": "var maxSizeSlices = function(slices) {\n    const numSlices = slices.length / 3;\n    const len = slices.length - 1;\n    \n    const dp = new Array(len).fill(null).map(() => new Array(numSlices + 1).fill(0));\n    const getMaxTotalSlices = (pieces) => {\n\t    // the max for 1 piece using only the first slice is itself\n        dp[0][1] = pieces[0];\n\t\t// the max for 1 piece using the first 2 slices is the max of the first and second slice\n        dp[1][1] = Math.max(pieces[0], pieces[1]);\n\t\t// start the max as the max of taking 1 slice from the first 2 slices\n        let max = dp[1][1];\n\t\t\n\t\t// calculate the max value for taking x number of pieces using up to that piece\n        for (let i = 2; i < pieces.length; i++) {\n            for (let numPieces = 1; numPieces <= numSlices; numPieces++) {\n                dp[i][numPieces] = Math.max(dp[i - 1][numPieces],                    // the max for not taking this piece\n\t\t\t\t                            dp[i - 2][numPieces - 1] + pieces[i]);   // the max for taking this piece\n                if (max < dp[i][numPieces]) max = dp[i][numPieces];                  // update the max if it is greater\n            }\n        }\n        return max;\n    }\n    \n    return Math.max(getMaxTotalSlices(slices.slice(0, slices.length - 1)),    // get max without the last slice\n                    getMaxTotalSlices(slices.slice(1)));                      // get max without the first slice\n};",
        "solution_java": "class Solution {\n    public int maxSizeSlices(int[] slices) {\n        int n = slices.length;\n        return Math.max(helper(slices, n/3, 0, n - 2), helper(slices, n/3, 1, n - 1));\n    }\n    \n    private int helper(int[] slices, int rounds, int start, int end) {\n        int n = end - start + 1, max = 0;\n        int[][][] dp = new int[n][rounds+1][2];\n        dp[0][1][1] = slices[start];\n        for (int i = start + 1; i <= end; i++) {\n            int x = i - start;\n            for (int j = 1; j <= rounds; j++) {\n                dp[x][j][0] = Math.max(dp[x-1][j][0], dp[x-1][j][1]);\n                dp[x][j][1] = dp[x-1][j-1][0] + slices[i];\n                if (j == rounds) {\n                    max = Math.max(max, Math.max(dp[x][j][0], dp[x][j][1]));\n                }\n            }\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int dp[501][501];\n    \n    int solve(vector<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};"
    },
    {
        "title": "Max Area of Island",
        "algo_input": "You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.\n\nThe area of an island is the number of cells with a value 1 in the island.\n\nReturn the maximum area of an island in grid. If there is no island, return 0.\n\n&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",
        "solution_py": "from queue import Queue\nfrom typing import List\n\n\nclass Solution:\n    def __init__(self):\n        self.directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]\n\n    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n        [rows, cols] = [len(grid), len(grid[0])]\n\n        ans = 0\n        visited: List[List[bool]] = [[False for _ in range(cols)] for _ in range(rows)]\n        \n        for i in range(rows):\n            for j in range(cols):\n                if not visited[i][j] and grid[i][j]:\n                    res = self.dfs(grid, visited, i, j)\n                    ans = res if res > ans else ans \n\n        return ans\n\n    def dfs(self, grid: List[List[int]], visited: List[List[bool]], startRow: int, startCol: int) -> int:\n        [rows, cols] = [len(grid), len(grid[0])]\n        \n        fields = 1\n        q = Queue()\n\n        q.put([startRow, startCol])\n        visited[startRow][startCol] = True\n\n        while not q.empty():\n            [row, col] = q.get()\n            for d in self.directions:\n                newRow = row + d[0]\n                newCol = col + d[1]\n                if newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols and not visited[newRow][newCol] and grid[newRow][newCol]:\n                    visited[newRow][newCol] = True\n                    fields += 1\n                    q.put([newRow, newCol])\n        \n        return fields",
        "solution_js": "var maxAreaOfIsland = function(grid) {\n    let result = 0;\n    const M = grid.length;\n    const N = grid[0].length;\n    const isOutGrid = (m, n) => m < 0 || m >= M || n < 0 || n >= N;\n    const island = (m, n) => grid[m][n] === 1;\n    const dfs = (m, n) => {\n        if (isOutGrid(m, n) || !island(m, n)) return 0;\n\n        grid[m][n] = 'X';\n        const top = dfs(m - 1, n);\n        const bottom = dfs(m + 1, n);\n        const left = dfs(m, n - 1);\n        const right = dfs(m, n + 1);\n        return 1 + top + bottom + left + right;\n    };\n\n    for (let m = 0; m < M; m++) {\n        for (let n = 0; n < N; n++) {\n            if (!island(m, n)) continue;\n            const area = dfs(m, n);\n\n            result = Math.max(area, result);\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int maxAreaOfIsland(int[][] grid) {\n\n      final int rows=grid.length;\n      final int cols=grid[0].length;\n      final int[][] dirrections=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};\n      Map<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}",
        "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};"
    },
    {
        "title": "Find First Palindromic String in the Array",
        "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",
        "solution_py": "class Solution:\n    def firstPalindrome(self, words):\n        for word in words:\n            if word == word[::-1]: return word\n        return \"\"",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Array Nesting",
        "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",
        "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",
        "solution_js": "var arrayNesting = function(nums) {\n\treturn nums.reduce((result, num, index) => {\n\t\tlet count = 1;\n\n\t\twhile (nums[index] !== index) {\n\t\t\tconst next = nums[index];\n\t\t\t[nums[index], nums[next]] = [nums[next], nums[index]];\n\t\t\tcount += 1;\n\t\t}\n\t\treturn Math.max(result, count);\n\t}, 0);\n};",
        "solution_java": "class Solution {\n    public int arrayNesting(int[] nums) {\n        int res=0;\n        boolean[] visited = new boolean[nums.length];\n        for(int i=0;i<nums.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}",
        "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};"
    },
    {
        "title": "Consecutive Numbers Sum",
        "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",
        "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",
        "solution_js": "var consecutiveNumbersSum = function(n) {\n    let count = 1;\n    for (let numberOfTerms = 2; numberOfTerms < Math.sqrt(2*n) + 1; numberOfTerms++) {\n        let startNumber = (n - numberOfTerms * (numberOfTerms - 1) / 2) / numberOfTerms;\n        if (Number.isInteger(startNumber) && startNumber !== 0) {\n            count++;\n        }\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n\n    public int consecutiveNumbersSum(int n) {\n        final double eightN = (8d * ((double) n)); // convert to double because 8n can overflow int\n        final int maxTriangular = (int) Math.floor((-1d + Math.sqrt(1d + eightN)) / 2d);\n        int ways = 1;\n        int triangular = 1;\n        for (int m = 2; m <= maxTriangular; ++m) {\n            triangular += m;\n            final int difference = n - triangular;\n            if ((difference % m) == 0) {\n                ways++;\n            }\n        }\n        return ways;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int consecutiveNumbersSum(int n) {\n        int count = 0;\n        for(int i = 2 ; i < n ; i++){\n            int sum_1 = i*(i+1)/2;\n            if(sum_1 > n)\n                break;\n            if((n-sum_1)%i == 0)\n                count++;\n        }\n        return count+1;\n    }\n};"
    },
    {
        "title": "Maximum Erasure Value",
        "algo_input": "You are given an array of positive integers nums and want to erase a subarray containing&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",
        "solution_py": "class Solution:\n    def maximumUniqueSubarray(self, nums: List[int]) -> int:\n        max_sum = 0\n        seen = set()\n        for l in range(len(nums)):\n            seen.clear()\n            curr_sum = 0\n            r = l\n            while r < len(nums):\n                if nums[r] in seen:\n                    break\n                curr_sum += nums[r]\n                seen.add(nums[r])\n                r += 1\n            max_sum = max(max_sum, curr_sum)\n        return max_sum",
        "solution_js": "var maximumUniqueSubarray = function(nums) {\n    let nmap = new Int8Array(10001), total = 0, best = 0\n    for (let left = 0, right = 0; right < nums.length; right++) {\n        nmap[nums[right]]++, total += nums[right]\n        while (nmap[nums[right]] > 1)\n            nmap[nums[left]]--, total -= nums[left++]\n        best = Math.max(best, total)\n    }\n    return best\n};",
        "solution_java": "class Solution {\n    public int maximumUniqueSubarray(int[] nums) {\n        short[] nmap = new short[10001];\n        int total = 0, best = 0;\n        for (int left = 0, right = 0; right < nums.length; right++) {\n            nmap[nums[right]]++;\n            total += nums[right];\n            while (nmap[nums[right]] > 1) {\n                nmap[nums[left]]--;\n                total -= nums[left++];\n            }\n            best = Math.max(best, total);\n        }\n        return best;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumUniqueSubarray(vector<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};"
    },
    {
        "title": "HTML Entity Parser",
        "algo_input": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.\n\nThe special characters and their entities for HTML are:\n\n\n\tQuotation Mark: the entity is &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",
        "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        ",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Check If a Word Occurs As a Prefix of Any Word in a Sentence",
        "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",
        "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",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Moving Stones Until Consecutive",
        "algo_input": "There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.\n\nIn one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x &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",
        "solution_py": "class Solution:\n    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n        a,b,c = sorted([a,b,c])\n        d1 = abs(b-a)-1 \n        d2 = abs(c-b)-1\n        mi = 2\n        if d1 == 0 and d2 == 0: mi = 0\n        elif d1 <= 1 or d2 <= 1: mi =1    \n        ma = c - a - 2\n        return [mi,ma]",
        "solution_js": "var numMovesStones = function(a, b, c) {\n    const nums = [a, b, c];\n\n    nums.sort((a, b) => a - b);\n\n    const leftGap = nums[1] - nums[0] - 1;\n    const rightGap = nums[2] - nums[1] - 1;\n\n    const maxMoves = leftGap + rightGap;\n\n    if (leftGap == 0 && rightGap == 0) return [0, 0];\n    if (leftGap > 1 && rightGap > 1) return [2, maxMoves];\n    return [1, maxMoves];\n};",
        "solution_java": "class Solution {\n    public int[] numMovesStones(int a, int b, int c) {\n        int[] arr ={a,b,c};\n        int[] arr2 = {a,b,c};\n        int maximum = findMaximum(arr);\n        int minimum = findMinimum(maximum,arr2);\n        return new int[]{minimum,maximum};\n    }\n    public int findMaximum(int[] arr){\n        Arrays.sort(arr);\n        int count = 0;\n        if(arr[0] == (arr[1]-1) && arr[1] == (arr[2] -1) ) return count;\n        if(arr[0] == arr[1]-1){\n            arr[2]--;\n            count++;\n        }\n        else{\n            arr[0]++;\n            count++;\n        }\n        return count + findMaximum(arr);\n\n    }\n\n    public int findMinimum(int max,int[] arr){\n        Arrays.sort(arr);\n        if(max == 0) return 0;\n        else if(Math.abs(arr[0]-arr[1]) >2 && Math.abs(arr[1]-arr[2]) >2 ) return 2;\n        else return 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    vector<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};"
    },
    {
        "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target",
        "algo_input": "Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.\n\n&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",
        "solution_py": "'''\ngreedy, prefix sum with hashtable\nO(n), O(n)\n'''\nclass Solution:\n    def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n        # hash set to record previously encountered prefix sums\n        prefix_sums = {0}\n        \n        res = prefix_sum = 0\n        for num in nums:\n            prefix_sum += num\n            if prefix_sum - target in prefix_sums:\n                res += 1\n                # greedily discard prefix sums before num\n                # thus not considering subarrays that start at before num \n                prefix_sums = {prefix_sum} \n            else:\n                prefix_sums.add(prefix_sum)\n        return res",
        "solution_js": "var maxNonOverlapping = function(nums, target) {\n    const seen = new Set();\n    let total = 0, result = 0;\n    \n    for(let n of nums) {\n        total += n;\n        \n        if(total === target || seen.has(total - target)) {\n            total = 0;\n            result++;\n            seen.clear()\n        } else seen.add(total)\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int maxNonOverlapping(int[] nums, int target) {\n        Map<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}",
        "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};"
    },
    {
        "title": "Maximum Building Height",
        "algo_input": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.\n\nHowever, there are city restrictions on the heights of the new buildings:\n\n\n\tThe height of each building must be a non-negative integer.\n\tThe height of the first building must be 0.\n\tThe height difference between any two adjacent buildings cannot exceed 1.\n\n\nAdditionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.\n\nIt is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.\n\nReturn the maximum possible height of the tallest building.\n\n&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",
        "solution_py": "class Solution:\n    def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n        arr = restrictions\n        arr.extend([[1,0],[n,n-1]])\n        arr.sort()\n        n = len(arr)\n        for i in range(1,n):\n            arr[i][1] = min(arr[i][1], arr[i-1][1]+arr[i][0]-arr[i-1][0])\n        for i in range(n-2,-1,-1):\n            arr[i][1] = min(arr[i][1], arr[i+1][1]+arr[i+1][0]-arr[i][0])\n        res = 0\n        for i in range(1,n):\n            #position where height can be the highest between arr[i-1][0] and arr[i][0]\n            k = (arr[i][1]-arr[i-1][1]+arr[i][0]+arr[i-1][0])//2\n            res = max(res, arr[i-1][1]+k-arr[i-1][0])\n        return res",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n    let maxHeight=0;\n    restrictions.push([1,0]);//Push extra restriction as 0 for 1\n    restrictions.push([n,n-1]);//Push extra restrition as n-1 for n\n    restrictions.sort(function(a,b){return a[0]-b[0]});\n    //Propogate from left to right to tighten the restriction: Check building restriction can be furhter tightened due to the left side building restriction.\n    for(let i=1;i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Find Winner on a Tic Tac Toe Game",
        "algo_input": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:\n\n\n\tPlayers take turns placing characters into empty squares ' '.\n\tThe first player A always places 'X' characters, while the second player B always places 'O' characters.\n\t'X' and 'O' characters are always placed into empty squares, never on filled ones.\n\tThe game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\n\tThe game also ends if all squares are non-empty.\n\tNo more moves can be played if the game is over.\n\n\nGiven a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return \"Draw\". If there are still movements to play return \"Pending\".\n\nYou can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.\n\n&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",
        "solution_py": "class Solution:\n    def tictactoe(self, moves: List[List[int]]) -> str:\n        wins = [\n            [(0, 0), (0, 1), (0, 2)],\n            [(1, 0), (1, 1), (1, 2)],\n            [(2, 0), (2, 1), (2, 2)],\n            [(0, 0), (1, 0), (2, 0)],\n            [(0, 1), (1, 1), (2, 1)],\n            [(0, 2), (1, 2), (2, 2)],\n            [(0, 0), (1, 1), (2, 2)],\n            [(0, 2), (1, 1), (2, 0)],\n        ]\n    \n        def checkWin(S):\n            for win in wins:\n                flag = True\n                for pos in win:\n                    if pos not in S:\n                        flag = False\n                        break\n                if flag:\n                    return True\n            return False\n        \n        A, B = set(), set()\n        for i, (x, y) in enumerate(moves):\n            if i % 2 == 0:\n                A.add((x, y))\n            else:\n                B.add((x, y))\n        \n        if checkWin(A):\n            return 'A'\n        elif checkWin(B):\n            return 'B'\n        \n        return \"Draw\" if len(moves) == 9 else \"Pending\"",
        "solution_js": "/**\n * @param {number[][]} moves\n * @return {string}\n */\nlet validate = (arr) => {\n    let set = [...new Set(arr)];\n    return set.length == 1 && set[0] != 0;\n}\n\nvar tictactoe = function(moves) {\n    let grid = [[0,0,0],[0,0,0],[0,0,0]];\n    for(let i in moves){\n        let [x,y] = moves[i]\n        grid[x][y] = (i % 2 == 1) ? -1 : 1;\n        if(validate(grid[x]) \n           || validate(grid.reduce((prev, curr) => [...prev, curr[y]], []))\n           || validate([grid[0][0], grid[1][1], grid[2][2]])\n           || validate([grid[0][2], grid[1][1], grid[2][0]])\n          )\n            return (i % 2) ? \"B\" : \"A\";\n    }\n    return (moves.length == 9) ? \"Draw\" : \"Pending\"\n};",
        "solution_java": "/**\nHere is my solution : \n\nTime Complexity O(M) \nSpace Complaexity O(1)\n*/\n\nclass Solution {\n    public String tictactoe(int[][] moves) {\n        \n        int [][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals\n          \n        for(int turn =0 ; turn < moves.length ; turn++){\n            \n\t\t\tint AorB =-1;\n            if(turn%2==0){AorB=1;}\n            \n            rcd[0][moves[turn][0]]+= AorB; \n            rcd[1][moves[turn][1]]+= AorB; \n            \n            if(moves[turn][0]== moves[turn][1]){rcd[2][0]+=AorB;}     // first diagonal\n            if(moves[turn][0]+moves[turn][1]-2 == 0){rcd[2][1]+=AorB;} //2nd diagonal                \n            \n            if( Math.abs(rcd[0][moves[turn][0]]) == 3 || Math.abs(rcd[1][moves[turn][1]]) == 3 \n               ||Math.abs(rcd[2][0]) ==3 || Math.abs(rcd[2][1]) ==3  ){\n             \n\t\t\t return AorB == 1 ? \"A\" : \"B\"; }\n                                                         } \n        \n        return moves.length == 9 ? \"Draw\" : \"Pending\";\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string tictactoe(vector<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."
    },
    {
        "title": "Minimum Time to Finish the Race",
        "algo_input": "You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.\n\n\n\tFor example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc.\n\n\nYou are also given an integer changeTime and an integer numLaps.\n\nThe race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds.\n\nReturn the minimum time to finish the race.\n\n&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",
        "solution_py": "class Solution:\n    def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n        # by observation, we can try to find out the optimal usage within certain numLaps\n        # use DP\n        # the optimal usage of this lap = min(change tire , no change)\n        # dp(laps) = min( dp(laps-1)+dp(1) + dp(laps-2)+dp(2) + ...)\n        \n        # we don't want to use tires too many laps, which will create unrealistic single lap time\n\t\t# we can evaluate single lap time by using changeTime <= 100000 and r >= 2\n\t\t# x = minimal continously laps\n\t\t# single lap time = 1*2^x <= 100000 -> x can't go more than 19\n\t\tlimit = 19\n        tires = list(set([(t1, t2) for t1, t2 in tires]))\n        memo = [[(-1,-1) for _ in range(min(limit,numLaps)+1)] for _ in range(len(tires))]\n        \n        for i in range(len(tires)):\n            for j in range(1, min(limit,numLaps)+1):                   # lap 1 to numLaps\n                if j == 1:\n                    memo[i][j] = (tires[i][0], tires[i][0])            # total time, lap time\n                else:\n                    # print('i, j', i, j)\n                    tmp = memo[i][j-1][1]*tires[i][1]                  # cost of continuously use tire this lap\n                    memo[i][j] = (memo[i][j-1][0]+tmp, tmp)\n        \n        @cache\n        def dp(laps):\n            if laps == 1:\n                return min(memo[i][1][0] for i in range(len(tires)))\n            \n            # no change:\n            best_time = min(memo[i][laps][0] for i in range(len(tires))) if laps <= limit else float('inf')\n            \n            # change tire:\n\t\t\t# e.g. change tire at this lap and see if it'll be faster -> dp(laps-1) + changeTime + dp(1)\n            # check all previous laps: dp(a) + changeTime + dp(b) until a < b\n            for j in range(1, laps):\n                a, b = laps-j, j\n                if a >= b:\n                    ta = dp(a)\n                    tb = dp(b)\n                    if ta+tb+changeTime < best_time:\n                        best_time = ta+tb+changeTime\n            return best_time\n                \n        return dp(numLaps)",
        "solution_js": "var minimumFinishTime = function(tires, changeTime, numLaps) {  \n    const n = tires.length\n    const smallestTire = Math.min(...tires.map(t => t[1]))\n    const maxSameTire = Math.floor(Math.log(changeTime) / Math.log(smallestTire)) + 1\n    const sameTireLast = Array(n).fill(0)\n\t\n\t// DP array tracking what is the min cost to complete lap i using same tire\n    const sameTire = Array(maxSameTire + 1).fill(Infinity)\n    for (let lap = 1; lap <= maxSameTire; lap++) {\n        tires.forEach((tire, i) => {\n            sameTireLast[i] += tire[0] * tire[1] ** (lap - 1)\n            sameTire[lap] = Math.min(sameTire[lap], sameTireLast[i])\n        })\n    }\n    \n    const dp = Array(numLaps + 1).fill(Infinity)\n    for (let i = 1; i < numLaps + 1; i++) {\n        if (i <= maxSameTire) dp[i] = sameTire[i]\n\t\t// at each lap, we can either use the same tire up to this lap (sameTire[i])\n\t\t// or a combination of 2 different best times, \n\t\t// eg lap 6: use best time from lap 3 + lap 3\n\t\t// or from lap 4 + lap 2\n\t\t// or lap 5 + lap 1\n        for (let j = 1; j < i / 2 + 1; j++) {\n            dp[i] = Math.min(dp[i], dp[i-j] + changeTime + dp[j])\n        }\n    }\n    return dp[numLaps]\n};",
        "solution_java": "class Solution {\n    int changeTime;\n    public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n        this.changeTime = changeTime;\n        int[] minTime = new int[numLaps + 1];\n        Arrays.fill(minTime, Integer.MAX_VALUE);\n\n        for (int[] tire : tires){\n            populateMinTime(tire, minTime);\n        }\n\n        int[] dp = new int[numLaps + 1];\n        for (int i = 1; i <= numLaps; i++){\n            dp[i] = minTime[i]; // maxValue for dp[i] is Integer.MAX_VALUE, no need to worry about overflow\n            for (int j = 1; j < i; j++){\n                dp[i] = Math.min(dp[i], dp[j] + changeTime + dp[i - j]); // it will never overflow, since dp[j] are far less than Integer.MAX_VALUE\n            }\n        }\n        return dp[numLaps];\n    }\n\n    private void populateMinTime(int[] tire, int[] minTime){\n        int sum = 0;\n        int base = tire[0];\n        int ex = tire[1];\n        int spent = 1;\n        for (int i = 1; i < minTime.length; i++){\n            spent = (i == 1) ? base : spent * ex;\n            if (spent > changeTime + base){break;} // set boundary\n            sum += spent;\n            minTime[i] = Math.min(minTime[i], sum);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumFinishTime(vector<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};"
    },
    {
        "title": "Validate Binary Tree Nodes",
        "algo_input": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.\n\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\n\nNote that the nodes have no values and that we only use the node numbers in this problem.\n\n&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",
        "solution_py": " class Solution:\n    def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n        \n        left_set=set(leftChild)\n        right_set=set(rightChild) \n\n        que=[]\n\n        for i in range(n):\n            if i not in left_set and i not in right_set:\n                que.append(i)\n        \n        if len(que)>1 or len(que)==0:\n            return False\n        \n        \n        graph=defaultdict(list)\n\n        for i in range(n):\n            graph[i]=[]\n\n            if leftChild[i]!=-1:\n                graph[i].append(leftChild[i])\n\n            if rightChild[i]!=-1:\n                graph[i].append(rightChild[i])\n        \n        visited=set()\n        visited.add(que[0])\n        \n        \n        while len(que)>0:\n            item=que.pop(0)\n            \n\n            children=graph[item]\n\n            for child in children:\n                if child not in visited:\n                    que.append(child)\n                    visited.add(child)\n                else:\n                    return False\n\n\n        for i in range(n):\n            if i not in visited:\n                return False\n\n        return True",
        "solution_js": "var validateBinaryTreeNodes = function(n, leftChild, rightChild) {\n\t// find in-degree for each node\n    const inDeg = new Array(n).fill(0);\n    for(let i = 0; i < n; ++i) {\n        if(leftChild[i] !== -1) {\n            ++inDeg[leftChild[i]];    \n        }\n        if(rightChild[i] !== -1) {\n            ++inDeg[rightChild[i]];\n        }\n    }\n\t// find the root node and check each node has only one in-degree\n    let rootNodeId = -1;\n    for(let i = 0; i < n; ++i) {\n        if(inDeg[i] === 0) {\n            rootNodeId = i;\n        } else if(inDeg[i] > 1) {\n            return false;\n        }\n    }\n\t// if no root node found -> invalid BT\n    if(rootNodeId === -1) {\n        return false;\n    }\n\t// BFS to check that each node is visited at least and at most once\n    const visited = new Set();\n    const queue = [rootNodeId];\n    \n    while(queue.length) {\n        const nodeId = queue.shift();\n        \n        if(visited.has(nodeId)) {\n            return false;\n        }\n        visited.add(nodeId);\n        \n       const leftNode = leftChild[nodeId],\n             rightNode = rightChild[nodeId];\n        if(leftNode !== -1) {\n            queue.push(leftNode);\n        }\n        if(rightNode !== -1) {\n            queue.push(rightNode);\n        }\n    }\n\t// checking each node is visited at least once\n    return visited.size === n;};",
        "solution_java": "import java.util.Arrays;\n\nclass Solution {\n  static class UF {\n    int[] parents;\n    int size;\n    UF(int n) {\n      parents = new int[n];\n      size = n;\n      Arrays.fill(parents, -1);\n    }\n    \n    int find(int x) {\n      if (parents[x] == -1) {\n        return x;\n      }\n      return parents[x] = find(parents[x]);\n    }\n\n    boolean union(int a, int b) {\n      int pA = find(a), pB = find(b);\n      if (pA == pB) {\n        return false;\n      }\n      parents[pA] = pB;\n      size--;\n      return true;\n    }\n\n    boolean connected() {\n      return size == 1;\n    }\n  }\n  public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {\n    UF uf = new UF(n);\n    int[] indeg = new int[n];\n    for (int i = 0; i < n; i++) {\n      int l = leftChild[i], r = rightChild[i];\n      if (l != -1) {\n        /**\n         * i: parent node\n         * l: left child node\n         * if i and l are already connected or the in degree of l is already 1\n         */\n        if (!uf.union(i, l) || ++indeg[l] > 1) {\n          return false;\n        }\n      }\n      if (r != -1) {\n        // Same thing for parent node and the right child node\n        if (!uf.union(i, r) || ++indeg[r] > 1) {\n          return false;\n        }\n      }\n    }\n    return uf.connected();\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    int find_parent(vector<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};"
    },
    {
        "title": "Reduction Operations to Make the Array Elements Equal",
        "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",
        "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]))",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar reductionOperations = function(nums) {\n   nums.sort((a,b)=>a-b);\n    let count = 0;\n    for(let i = nums.length - 1;i>0;i--)\n        if(nums[i] !== nums[i-1])\n            count += nums.length - i\n    return count\n};",
        "solution_java": "class Solution {\n    public int reductionOperations(int[] nums) {\n        Map<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}",
        "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};"
    },
    {
        "title": "Minimum Number of K Consecutive Bit Flips",
        "algo_input": "You are given a binary array nums and an integer k.\n\nA k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\n\nReturn the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.\n\nA subarray is a contiguous part of an array.\n\n&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",
        "solution_py": "class Solution:\n    def minKBitFlips(self, nums: List[int], k: int) -> int:\n        flips = [0]*len(nums)\n        csum = 0\n\n        for left in range(0, len(nums)-k+1):\n            if (nums[left] + csum) % 2 == 0:\n                flips[left] += 1\n                csum += 1\n            if left >= k-1:\n                csum -= flips[left-k+1]\n\n        for check in range(len(nums)-k+1, len(nums)):\n            if (nums[check] + csum) % 2 == 0:\n                return -1\n            if check >= k-1:\n                csum -= flips[check-k+1]\n\n        return sum(flips)",
        "solution_js": "var minKBitFlips = function(nums, k) {\n    let count = 0\n    \n    for(let i=0; i<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};",
        "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}",
        "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};"
    },
    {
        "title": "Find Median from Data Stream",
        "algo_input": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.\n\n\n\tFor example, for arr = [2,3,4], the median is 3.\n\tFor example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.\n\n\nImplement the MedianFinder class:\n\n\n\tMedianFinder() initializes the MedianFinder object.\n\tvoid addNum(int num) adds the integer num from the data stream to the data structure.\n\tdouble findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.\n\n\n&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",
        "solution_py": "class MedianFinder:\n\n    def __init__(self):\n        self.min_hp = []\n        self.max_hp = []\n        \n    def addNum(self, num: int) -> None:\n        if len(self.min_hp) == len(self.max_hp):\n            if len(self.max_hp) and num<-self.max_hp[0]:\n                cur = -heapq.heappop(self.max_hp)\n                heapq.heappush(self.max_hp, -num)\n                heapq.heappush(self.min_hp, cur)\n            else:\n                heapq.heappush(self.min_hp, num)\n        else:\n            if num>self.min_hp[0]:\n                cur = heapq.heappop(self.min_hp)\n                heapq.heappush(self.min_hp, num)\n                heapq.heappush(self.max_hp, -cur)\n            else:\n                heapq.heappush(self.max_hp, -num)\n        \n    def findMedian(self) -> float:\n        if len(self.min_hp) == len(self.max_hp):\n            return (self.min_hp[0] + -self.max_hp[0]) /2\n        else:\n            return self.min_hp[0]",
        "solution_js": "var MedianFinder = function() {\n    this.left = new MaxPriorityQueue();\n  this.right = new MinPriorityQueue();\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nMedianFinder.prototype.addNum = function(num) {\nlet { right, left } = this\n  if (right.size() > 0 && num > right.front().element) {\n    right.enqueue(num)\n  } else {\n    left.enqueue(num)\n  }\n\n  if (Math.abs(left.size() - right.size()) == 2) {\n    if (left.size() > right.size()) {\n      right.enqueue(left.dequeue().element)\n    } else {\n      left.enqueue(right.dequeue().element)\n    }\n  }\n};\n\n/**\n * @return {number}\n */\nMedianFinder.prototype.findMedian = function() {\n  let { left, right } = this\n  if (left.size() > right.size()) {\n    return left.front().element\n  } else if(right.size() > left.size()) {\n    return right.front().element\n  } else{\n      // get the sum of all\n      return (left.front().element + right.front().element) / 2\n  }\n};\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * var obj = new MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */",
        "solution_java": "class MedianFinder {\n\n    PriorityQueue maxHeap;\n    PriorityQueue minHeap;\n\n    public MedianFinder() {\n        maxHeap= new PriorityQueue<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}",
        "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};"
    },
    {
        "title": "Reformat Date",
        "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",
        "solution_py": "class Solution:\n    def reformatDate(self, date: str) -> str:\n\n        m_dict_={\"Jan\":\"01\", \"Feb\":\"02\", \"Mar\":\"03\", \"Apr\":\"04\", \"May\":\"05\", \"Jun\":\"06\", \"Jul\":\"07\", \"Aug\":\"08\", \"Sep\":\"09\", \"Oct\":\"10\", \"Nov\":\"11\", \"Dec\":\"12\"}\n\n        day=date[:-11]\n\n        if len(day)==1:\n            day=\"0\"+day\n\n        return(date[-4:] + \"-\" + m_dict_[date[-8:-5]] + \"-\" + day)",
        "solution_js": "var reformatDate = function(date) {\n       const ans = [];\n       const month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n        \n        const [inputDate,inputMonth,inputYear] = date.split(' ');\n        ans.push(inputYear);\n        ans.push(\"-\");\n    \n        const monthIndex = month.findIndex(mon => mon === inputMonth);\n        const formatedMonth = String(monthIndex + 1).padStart(2,'0');\n        ans.push(formatedMonth);\n        ans.push(\"-\");\n    \n        const slicedDate = inputDate.slice(0,2);\n        if(+slicedDate >= 10){\n            ans.push(slicedDate);\n        }else{\n            const formatedDate = inputDate.slice(0,1).padStart(2,'0');\n            ans.push(formatedDate)\n        }\n          \n       return ans.join('');\n};",
        "solution_java": "class Solution {\n    public String reformatDate(String date) {\n        int len = date.length();\n        \n        String[] monthArray = {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"};\n        \n        String year = date.substring(len - 4);\n        int month = Arrays.asList(monthArray).indexOf(date.substring(len - 8, len - 5)) + 1;\n        String day = date.substring(0, len - 11);\n        \n        StringBuffer sb = new StringBuffer();\n        \n        sb.append(year + \"-\");\n        \n        if(month < 10)\n            sb.append(\"0\" + month + \"-\");\n        else\n            sb.append(month + \"-\");\n        \n        if(day.length() == 1) \n            sb.append(\"0\" + day);\n        else\n            sb.append(day);\n        \n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reformatDate(string date) {\n        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};"
    },
    {
        "title": "Count Lattice Points Inside a Circle",
        "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",
        "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)",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Distribute Candies to People",
        "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",
        "solution_py": "class Solution:\n    def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n        candy_dict = {}\n        for i in range(num_people) : \n            candy_dict[i] = 0 \n        \n        candy, i, totalCandy = 1, 0, 0\n        while totalCandy < candies : \n            if i >= num_people : \n                i = 0\n            if candies - totalCandy >= candy : \n                candy_dict[i] += candy \n                totalCandy += candy\n            else : \n                candy_dict[i] += candies - totalCandy\n                totalCandy += candies - totalCandy\n            i += 1 \n            candy += 1  \n        return candy_dict.values()",
        "solution_js": "var distributeCandies = function(candies, num_people) {\n\n    let i = 1, j=0;\n    const result = new Array(num_people).fill(0);\n    while(candies >0){\n        result[j] += i;\n        candies -= i;\n        if(candies < 0){\n            result[j] += candies;\n            break;\n        }\n        j++;\n        if(j === num_people)\n            j=0;\n\n        i++;\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] distributeCandies(int candies, int num_people) {\n        int n=num_people;\n        int a[]=new int[n];\n        int k=1;\n        while(candies>0){\n            for(int i=0;i<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}",
        "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};"
    },
    {
        "title": "Maximize Score After N Operations",
        "algo_input": "You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\n\nIn the ith operation (1-indexed), you will:\n\n\n\tChoose two elements, x and y.\n\tReceive a score of i * gcd(x, y).\n\tRemove x and y from nums.\n\n\nReturn the maximum score you can receive after performing n operations.\n\nThe function gcd(x, y) is the greatest common divisor of x and y.\n\n&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",
        "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)",
        "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};",
        "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)",
        "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};"
    },
    {
        "title": "Make Array Zero by Subtracting Equal Amounts",
        "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",
        "solution_py": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        return len(set(nums) - {0})",
        "solution_js": "var minimumOperations = function(nums) {\n    let k = new Set(nums) // convert array to set; [...nums] is destructuring syntax\n    return k.has(0) ? k.size-1 : k.size; // we dont need 0, hence if zero exists return size-1\n};",
        "solution_java": "class Solution {\n    public int minimumOperations(int[] nums) {\n        Set<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}",
        "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};"
    },
    {
        "title": "Multiply Strings",
        "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",
        "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      ",
        "solution_js": "var multiply = function(num1, num2) {\n    const m = num1.length;\n    const n = num2.length;\n\n    const steps = [];\n    let carry = 0;\n    for(let i = m - 1; i >= 0; i -= 1) {\n        const digitOne = parseInt(num1[i]);\n        let step = \"0\".repeat(m - 1 - i);\n\n        carry = 0;\n        for(let j = n - 1; j >= 0; j -= 1) {\n            const digitTwo = parseInt(num2[j]);\n\n            const product = digitOne * digitTwo + carry;\n            const newDigit = product % 10;\n            carry = Math.floor(product / 10);\n\n            step = newDigit + step;\n        }\n\n        if(carry > 0) step = carry + step;\n        steps.push(step);\n    }\n\n    for(let i = 0; i < steps.length - 1; i += 1) {\n        let nextStep = steps[i + 1];\n        let step = steps[i];\n        step = \"0\".repeat(nextStep.length - step.length) + step;\n\n        carry = 0;\n        let newStep = \"\";\n        for(let j = step.length - 1; j >= 0; j -= 1) {\n            const sum = parseInt(nextStep[j]) + parseInt(step[j]) + carry;\n            const digit = sum % 10;\n            carry = Math.floor(sum / 10);\n            newStep = digit + newStep;\n        }\n\n        if(carry > 0) newStep = carry + newStep;\n        steps[i + 1] = newStep;\n    }\n\n    let result = steps[steps.length - 1];\n    let leadingZeros = 0\n    while(leadingZeros < result.length - 1 && result[leadingZeros] === '0') {\n        leadingZeros += 1;\n    }\n\n    return result.slice(leadingZeros);\n};",
        "solution_java": "class Solution {\n    public String multiply(String num1, String num2) {\n        if(num1.equals(\"0\") || num2.equals(\"0\"))\n            return \"0\";\n        int[] arr=new int[num1.length()+num2.length()];\n\n        int index=0;\n        for(int i=num1.length()-1;i>=0;i--)\n        {\n            int carry=0;\n            int column=0;\n            for(int j=num2.length()-1;j>=0;j--)\n            {\n                int a=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');\n                int temp=(arr[index+column]+carry+a);\n                arr[index+column]=temp%10;\n                carry=temp/10;\n                column++;\n            }\n            if(carry!=0)\n            {\n                arr[index+column]=carry;\n            }\n            index++;\n        }\n        String ans=\"\";\n        index=arr.length-1;\n        while(arr[index]==0)\n        {\n            index--;\n        }\n        for(int i=index;i>=0;i--)\n        {\n            ans+=arr[i];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\n    void compute(string &num, int dig, int ind, string &ans){\n        int c = 0;  // carry digit..\n        int i = num.size()-1;\n        //  again travarsing the string in reverse\n        while(i >= 0){\n            int mul = dig*(num[i]-'0') + c;  // the curr digit's multiplication\n            c = mul/10; // carry update..\n            mul %= 10;  // mul update in  a single digit..\n            if(ind >= ans.length()){    // here if the index where we'll put the value is out of bounds...\n                ans.push_back('0' + mul);\n            }\n            else{\n                //  here adding the val with the previous digit and further computing the carry...\n                mul += (ans[ind] - '0');\n                c += mul/10;\n                mul %= 10;\n                ans[ind] = ('0' + mul);\n            }\n            i--;\n            ind++;  // increment the index where we'll put the val;\n        }\n        \n        if(c > 0){ //   if carry is non-zero...\n            ans.push_back('0' + c);\n        }\n        \n    } \npublic:\n    string multiply(string num1, string num2) {\n        string ans = \"\";    //  the string which we have to return as answer..\n        if(num1 == \"0\" || num2 == \"0\") return \"0\";  // base case..\n        int ind = 0;    // the index from which we'll add the multiplied value to the ans string\n        for(int i  = num1.size()-1; i >= 0; ind++,i--){     \n        // travarsing in reverse dir. on num1 and increasing ind bcz for every digit\n        //  of num1 we'll add the multiplication in a index greater than the previous iteration\n            int dig = num1[i]-'0';  // the digit with which we'll multiply by num2..\n            compute(num2, dig, ind, ans);   // function call for every digit and num2\n        }\n//   we have calculated the ans in a reverse way such that we can easily add a leading digit & now reversing it...\n        reverse(ans.begin(), ans.end());    \n        return ans;\n    }\n};"
    },
    {
        "title": "Best Sightseeing Pair",
        "algo_input": "You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.\n\nThe score of a pair (i &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",
        "solution_py": "class Solution:\n    \"\"\"\n    Approach: \n    O(n^2) is very straight forward\n    For all the possible pairs\n    for i in range(n)\n      for j in range(i+1, n)\n         value[i] = max(value[i], value[i] + value[j] + i - j`)\n    \n    we can do this problem in O(n) as well\n    values = [8, 1, 5, 2, 6]\n    max_val = [0, 0, 0, 0, 0]\n    max_val[i] = max(max_val[i-1]-1, values[i-1]-1)\n    we have to do it once from left side and then from right side\n    \"\"\"\n    def maxScoreSightseeingPair(self, values: List[int]) -> int:\n        left_max_vals = [float('-inf') for _ in range(len(values))]\n        right_max_vals = [float('-inf') for _ in range(len(values))]\n        \n        for i in range(1, len(values)):\n            left_max_vals[i] = max(left_max_vals[i-1]-1, values[i-1]-1)\n            \n        for i in range(len(values)-2, -1, -1):\n            right_max_vals[i] = max(right_max_vals[i+1]-1, values[i+1]-1)\n        \n        max_pair = float('-inf')\n        for i in range(len(values)):\n            max_pair = max(max_pair, values[i] + max(left_max_vals[i], right_max_vals[i]))\n        return max_pair",
        "solution_js": "/**\n * @param {number[]} values\n * @return {number}\n */\nvar maxScoreSightseeingPair = function(values) {\n    let n=values.length,\n        prevIndexMaxAddition=values[n-1],\n        maxValue=-2;\n    for(let i=n-2;i>-1;i--){\n        let curIndexMaxAddition=Math.max(values[i],prevIndexMaxAddition-1);\n        let curIndexMaxValue=values[i]+prevIndexMaxAddition-1;\n        if(maxValue<curIndexMaxValue){\n            maxValue=curIndexMaxValue;\n        }\n        prevIndexMaxAddition=curIndexMaxAddition;\n    }\n    return maxValue;\n};",
        "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}",
        "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};"
    },
    {
        "title": "Rectangle Overlap",
        "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",
        "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",
        "solution_js": "/**\n * @param {number[]} rec1\n * @param {number[]} rec2\n * @return {boolean}\n */\nvar isRectangleOverlap = function(rec1, rec2) {\n    if(rec1[0] >= rec2[2] || rec2[0] >= rec1[2] || rec1[1] >= rec2[3] || rec2[1] >= rec1[3]){\n        return false\n    }\n    return true\n};",
        "solution_java": "// Rectangle Overlap\n// https://leetcode.com/problems/rectangle-overlap/\n\nclass Solution {\n    public boolean isRectangleOverlap(int[] rec1, int[] rec2) {\n        int x1 = rec1[0];\n        int y1 = rec1[1];\n        int x2 = rec1[2];\n        int y2 = rec1[3];\n        int x3 = rec2[0];\n        int y3 = rec2[1];\n        int x4 = rec2[2];\n        int y4 = rec2[3];\n        if (x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3) {\n            return false;\n        }\n        return true;       \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isRectangleOverlap(vector<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};"
    },
    {
        "title": "Splitting a String Into Descending Consecutive Values",
        "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",
        "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",
        "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar splitString = function(s) {\n\n    const backtracking = (index, prevStringValue) => {\n        if(index === s.length) {\n            return true;\n        }\n        for(let i = index; i < s.length; i++) {\n            const currStringValue = s.slice(index ,i + 1);\n\n            if(parseInt(prevStringValue, 10) === parseInt(currStringValue, 10) + 1) {\n                if(backtracking(i + 1, currStringValue)) {\n                    return true;\n                }\n            }\n        }\n    }\n    // we need to have at least two values to compare, so we start with the for outside the backtracking function\n    for (let i = 1; i <= s.length - 1; i++) {\n        const currStringValue = s.slice(0, i);\n        if (backtracking(i, currStringValue)) {\n            return true;\n        }\n    }\n    return false\n};",
        "solution_java": "class Solution {\n    public boolean splitString(String s) {\n        return isRemainingValid(s, null);\n    }\n    private boolean isRemainingValid(String s, Long previous) {\n        long current =0;\n        for(int i=0;i<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}",
        "solution_c": "class Solution {\n    bool helper(string s, long long int tar) {\n        if (stoull(s) == tar) return true;\n        for (int i = 1; i < s.size(); ++i) {\n            if (stoull(s.substr(0, i)) != tar)    continue;\n            if (helper(s.substr(i, s.size()-i), tar-1))\n                return true;\n        }\n        return false;\n    }\npublic:\n    bool splitString(string s) {\n        for (int i = 1; i < s.size(); ++i) {\n            long long int tar = stoull(s.substr(0, i));\n            if (helper(s.substr(i, s.size()-i), tar-1))\n                return true;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Transpose Matrix",
        "algo_input": "Given a 2D integer array matrix, return the transpose of matrix.\n\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n\n\n\n&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",
        "solution_py": "class Solution:\n    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n        rows=len(matrix)\n        cols=len(matrix[0])\n        ans=[[0]*rows]*cols\n        for i in range(cols):\n            for j in range(rows):\n                ans[i][j]=matrix[j][i]\n        return ans",
        "solution_js": "var transpose = function(matrix){\n    let result = []\n    for(let i=0;i<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 ] ] ) )",
        "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}",
        "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};"
    },
    {
        "title": "Delete Node in a Linked List",
        "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",
        "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",
        "solution_js": "var deleteNode = function(node) {\n    let nextNode = node.next;\n    node.val = nextNode.val;\n    node.next = nextNode.next;\n};",
        "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}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void deleteNode(ListNode* node) {\n        int temp = node->val;\n        node->val = node->next->val;\n        node->next->val = temp;\n        \n        ListNode* delNode = node->next;\n        node->next = node->next->next;\n        delete delNode;\n    }\n};"
    },
    {
        "title": "Flatten a Multilevel Doubly Linked List",
        "algo_input": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.\n\nGiven the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.\n\nReturn the head of the flattened list. The nodes in the list must have all of their child pointers set to null.\n\n&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",
        "solution_py": "\"\"\"\n# Definition for a Node.\nclass Node:\n    def __init__(self, val, prev, next, child):\n        self.val = val\n        self.prev = prev\n        self.next = next\n        self.child = child\n\"\"\"\n\nclass Solution:\n    def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':    \n        node = head\n        while node:\n            if node.child: # If there is a child travel to last node of the child\n                child = node.child\n                while child.next:\n                    child = child.next\n                child.next = node.next # Update the next of child to the the next of the current node\n                if node.next: # update the prev of the next node to chile to make it valid doubly linked list\n                    node.next.prev = child\n                node.next = node.child # Update the child to become the next of the current\n                node.next.prev = node # update the prev of the next node to chile to make it valid doubly linked list\n                node.child = None # Make the child of the current node None to fulfill the requirements\n            node = node.next\n        return head\n\n# time and space complexity\n# time: O(n)\n# space: O(1)",
        "solution_js": "var flatten = function(head) {\n    var arr = [];\n    var temp = head;\n    var prev= null;\n    while(temp)\n        {\n            if(temp.child!= null)\n                {\n                    arr.push(temp.next);\n                    temp.next = temp.child;\n                    temp.child.prev = temp;\n                    temp.child = null;\n                }\n            prev = temp;\n            temp = temp.next\n        }\n    for(var j=arr.length-1; j>=0; j--)\n        {\n            if(arr[j] != null)\n                mergeOtherLists(arr[j]);\n        }\n    return head;\n\t\n\tfunction mergeOtherLists(root)\n\t\t{\n\t\t\tprev.next=root;\n\t\t\troot.prev=prev;\n\t\t   while(root)\n\t\t\t   {\n\t\t\t\t  prev = root;\n\t\t\t\t   root = root.next;\n\t\t\t   }\n\t\t}\n};",
        "solution_java": "class Solution {\n    public Node flatten(Node head) {\n        Node curr = head ; // for traversal\n        Node tail = head; // for keeping the track of previous node\n        Stack<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}",
        "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"
    },
    {
        "title": "Lucky Numbers in a Matrix",
        "algo_input": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.\n\nA lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.\n\n&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",
        "solution_py": "class Solution:\n    def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n        min_, max_ = 0, 0\n        min_temp = []\n        max_temp = []\n        m = len(matrix)\n        n = len(matrix[0])\n        for i in matrix:\n            min_temp.append(min(i))\n        print(min_temp)\n        if n >= m:\n            for i in range(n):\n                max_check = []\n                for j in range(m):\n                    max_check.append(matrix[j][i])\n                max_temp.append(max(max_check))\n            return set(min_temp).intersection(set(max_temp))\n        elif n == 1:\n            for i in range(m):\n                max_check = []\n                for j in range(n):\n                    max_check.append(matrix[i][j])\n                max_temp.append(max(max_check))\n            return [max(max_temp)]\n        else:\n            for i in range(n):\n                max_check = []\n                for j in range(m):\n                    max_check.append(matrix[j][i])\n                max_temp.append(max(max_check))\n            return set(min_temp).intersection(set(max_temp))",
        "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nvar luckyNumbers = function(matrix) {\n    let rowLucky = new Set();\n    let colLucky = new Set();\n    let cols = [...Array(matrix[0].length)].map(e => []);\n\n    for (let i = 0; i < matrix.length; i++) {\n        let row = matrix[i];\n        rowLucky.add(Math.min(...row));\n\n        // build columns\n        for (let j = 0; j < row.length; j++) {\n            cols[j].push(row[j]);\n        }\n    }\n\n    // Compare sets\n    for (const col of cols)\n        colLucky.add(Math.max(...col));\n    return [...rowLucky].filter(x => colLucky.has(x));\n};",
        "solution_java": "class Solution {\n    public List<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}",
        "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};"
    },
    {
        "title": "Bricks Falling When Hit",
        "algo_input": "You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:\n\n\n\tIt is directly connected to the top of the grid, or\n\tAt least one other brick in its four adjacent cells is stable.\n\n\nYou are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location&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",
        "solution_py": "from collections import defaultdict\n\nclass Solution:\n    def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n        parent = defaultdict()\n        sz = defaultdict(lambda:1)\n        empty = set()\n        def find(i):\n            if parent[i] != i:\n                parent[i] = find(parent[i])\n            return parent[i]\n        def union(i,j):\n            pi = find(i)\n            pj = find(j)\n            if pi != pj:\n                parent[pi] = pj\n                sz[pj] += sz[pi]\n        row = len(grid)\n        col = len(grid[0])\n        for r in range(row):\n            for c in range(col):\n                parent[(r,c)] = (r,c)\n        parent[(row,col)] = (row,col)\n        for r, c in hits:\n            if grid[r][c]:\n                grid[r][c] = 0\n            else:\n                empty.add((r,c))\n        for r in range(row):\n            for c in range(col):\n                if not grid[r][c]:\n                    continue\n                for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n                    if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n                        union((r, c),(r+dr, c+dc))\n                if r == 0:\n                    union((r,c),(row,col))\n        res = [0]*len(hits)\n        for i in range(len(hits)-1,-1,-1):\n            r, c = hits[i]\n            if (r,c) in empty:\n                continue\n            grid[r][c] = 1\n            curbricks = sz[find((row,col))]\n            for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n                if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n                    union((r,c),(r+dr,c+dc))\n            if r == 0:\n                union((r,c),(row,col))\n            nextbricks = sz[find((row,col))]\n            if nextbricks > curbricks:\n                res[i] = nextbricks - curbricks - 1\n        return res",
        "solution_js": " var hitBricks = function(grid, hits) {\n    let output = []\n    for (let i = 0; i < hits.length; i++) {\n        let map = {};\n        \n        if (grid[hits[i][0]][hits[i][1]] == 1) {\n            \n            grid[hits[i][0]][hits[i][1]] = 0;\n            \n            \n            for (let j = 0; j<grid[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}",
        "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}",
        "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};"
    },
    {
        "title": "Validate IP Address",
        "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",
        "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        ",
        "solution_js": "var validIPAddress = function(queryIP) {\n    const iPv4 = () => {\n        const address = queryIP.split('.');\n        if (address.length !== 4) return null;\n\n        for (const str of address) {\n            const ip = parseInt(str);\n            if (ip < 0 || ip > 255) return null;\n            if (ip.toString() !== str) return null;\n        }\n        return 'IPv4';\n    };\n\n    const iPv6 = () => {\n        const address = queryIP.split(':');\n        if (address.length !== 8) return null;\n        const config = '0123456789abcdefABCDEF';\n        const check = address.every(str => {\n            if (str === '' || str.length > 4) return false;\n            for (const s of str) {\n                if (!config.includes(s)) return false;\n            }\n            return true;\n        });\n        return check ? 'IPv6' : null;\n    };\n\n    return iPv4() ?? iPv6() ?? 'Neither';\n};",
        "solution_java": "class Solution {\n    public String validIPAddress(String queryIP) {\n        String regexIpv4 = \"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\";\n        \n        String regexIpv6 = \"((([0-9a-fA-F]){1,4})\\\\:){7}(([0-9a-fA-F]){1,4})\";\n        \n        if(queryIP.matches(regexIpv4))\n            return \"IPv4\";\n        else if(queryIP.matches(regexIpv6))\n            return \"IPv6\";\n        else\n            return \"Neither\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkforIPv6(string IP){\n        int n = IP.size();\n        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};"
    },
    {
        "title": "Minimum Moves to Equal Array Elements II",
        "algo_input": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\n\nIn one move, you can increment or decrement an element of the array by 1.\n\nTest cases are designed so that the answer will fit in a 32-bit integer.\n\n&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",
        "solution_py": "class Solution:\n    def minMoves2(self, nums: List[int]) -> int:\n        \n        n=len(nums)\n        nums.sort()\n        \n        if n%2==1:\n            median=nums[n//2]\n        else:\n            median = (nums[n//2 - 1] + nums[n//2]) // 2\n        \n        ans=0\n        \n        for val in nums:\n            ans+=abs(val-median)\n        \n        return ans\n        ",
        "solution_js": "var minMoves2 = function(nums) {\n    // Sort the array low to high\n    nums.sort(function(a, b) { return a-b;});\n    let i = 0;\n    let j = nums.length - 1;\n    let res = 0;\n    /**\n     * Sum up the difference between the next highest and lowest numbers. Regardless of what number we wish to move towards, the number of moves is the same.\n     */\n    while (i < j){\n        res += nums[j] - nums[i];\n        i++;\n        j--;\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public int minMoves2(int[] nums) {\n        Arrays.sort(nums);\n        int idx=(nums.length-1)/2;\n        int sum=0;\n        for(int i=0;i<nums.length;i++){\n            sum+=Math.abs(nums[i]-nums[idx]);\n        }\n        return sum;\n    }\n}",
        "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};"
    },
    {
        "title": "Longest ZigZag Path in a Binary Tree",
        "algo_input": "You are given the root of a binary tree.\n\nA ZigZag path for a binary tree is defined as follow:\n\n\n\tChoose any node in the binary tree and a direction (right or left).\n\tIf the current direction is right, move to the right child of the current node; otherwise, move to the left child.\n\tChange the direction from right to left or from left to right.\n\tRepeat the second and third steps until you can't move in the tree.\n\n\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\n\nReturn the longest ZigZag path contained in that tree.\n\n&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",
        "solution_py": "class Solution:\n    def longestZigZag(self, root: Optional[TreeNode]) -> int:\n        self.res = 0\n\n        def helper(root):\n            if root is None:\n                return -1, -1\n\n            leftRight = helper(root.left)[1] + 1\n            rightLeft = helper(root.right)[0] + 1\n            self.res = max(self.res, leftRight, rightLeft)\n            return leftRight, rightLeft\n\n        helper(root)\n        return self.res",
        "solution_js": "/** https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nvar longestZigZag = function(root) {\n  this.out = 0;\n\n  // Recursive left and right node and find the largest height\n  let left = dfs(root.left, false) + 1;\n  let right = dfs(root.right, true) + 1;\n  this.out = Math.max(this.out, Math.max(left, right));\n  \n  return this.out;\n};\n\nvar dfs = function(node, isLeft) {\n  // Node is null, we return -1 because the caller will add 1, so result in 0 (no node visited)\n  if (node == null) {\n    return -1;\n  }\n  \n  // No left or right node, we return 0 because the caller will add 1, so result in 1 (visited 1 node - this one)\n  if (node.left == null && node.right == null) {\n    return 0;\n  }\n  \n  // Recursive to see which one is higher, zigzag to left or zigzag to right\n  let left = dfs(node.left, false) + 1;\n  let right = dfs(node.right, true) + 1;\n  this.out = Math.max(this.out, Math.max(left, right));\n  \n  return isLeft === true ? left : right;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n   static class Pair{\n       int left=-1;\n       int right=-1;\n       int maxLen=0;\n   }\n    public int longestZigZag(TreeNode root) {\n        Pair ans=longestZigZag_(root);\n        return ans.maxLen;\n    }\n\n    public Pair longestZigZag_(TreeNode root) {\n        if(root==null)\n            return new Pair();\n        Pair l=longestZigZag_(root.left);\n        Pair r=longestZigZag_(root.right);\n\n        Pair myAns=new Pair();\n        myAns.left=l.right+1;\n        myAns.right=r.left+1;\n        int max=Math.max(myAns.left,myAns.right);\n        myAns.maxLen=Math.max(max,Math.max(l.maxLen,r.maxLen));\n        return myAns;\n\n    }\n\n}",
        "solution_c": "class Solution {\n    typedef long long ll;\n    typedef pair<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};"
    },
    {
        "title": "Rearrange Array Elements by Sign",
        "algo_input": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.\n\nYou should rearrange the elements of nums such that the modified array follows the given conditions:\n\n\n\tEvery consecutive pair of integers have opposite signs.\n\tFor all integers with the same sign, the order in which they were present in nums is preserved.\n\tThe rearranged array begins with a positive integer.\n\n\nReturn the modified array after rearranging the elements to satisfy the aforementioned conditions.\n\n&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",
        "solution_py": "class Solution:\n    def rearrangeArray(self, nums: List[int]) -> List[int]:\n        return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]",
        "solution_js": "var rearrangeArray = function(nums) {\n   let result = Array(nums.length).fill(0);\n    let posIdx = 0, negIdx = 1;\n   for(let i=0;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 };",
        "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}",
        "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};"
    },
    {
        "title": "Sum of Square Numbers",
        "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",
        "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",
        "solution_js": "var judgeSquareSum = function(c) {\n\tlet a = 0;\n\tlet b = Math.sqrt(c) | 0;\n\n\twhile (a <= b) {\n\t\tconst sum = a ** 2 + b ** 2;\n\t\tif (sum === c) return true;\n\t\tsum > c ? b -= 1 : a += 1;\n\t}\n\treturn false;\n};",
        "solution_java": "class Solution {\n    public boolean judgeSquareSum(int c) {\n        long a = 0;\n        long b = (long) Math.sqrt(c);\n\n        while(a<=b){\n            if(((a*a) + (b*b)) == c){\n                return true;\n            }\n            else if((((a*a)+(b*b)) < c)){\n                a++;\n            }\n            else{\n                b--;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool judgeSquareSum(int c) {\n        long long start=0,end=0;\n        while(end*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};"
    },
    {
        "title": "Most Stones Removed with Same Row or Column",
        "algo_input": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.\n\nA stone can be removed if it shares either the same row or the same column as another stone that has not been removed.\n\nGiven an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.\n\n&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",
        "solution_py": "class Solution:\n    def removeStones(self, stones: List[List[int]]) -> int:\n        def dfs(row,col):\n            if seen[(row,col)]:\n                return 0\n            seen[(row,col)] = True\n            for r,c in tableRow[row]:\n                dfs(r,c)\n            for r,c in tableCol[col]:\n                dfs(r,c)\n            return 1\n\n        tableRow, tableCol = {},{}\n        for row,col in stones:\n            if row not in tableRow:\n                tableRow[row] = set()\n            if col not in tableCol:\n                tableCol[col] = set()\n            tableRow[row].add((row,col))\n            tableCol[col].add((row,col))\n\n        count,seen= 0, {(row,col):False for row,col in stones}\n        for row,col in stones:\n            count += dfs(row,col)\n        return abs(len(stones)-count)",
        "solution_js": "/**\n * @param {number[][]} stones\n * @return {number}\n */\nvar removeStones = function(stones) {\n    \n    const n = stones.length\n    // initial number of components(a.k.a island)\n    let numComponents = n\n    \n    //initial forest for union find\n    let forest = new Array(n).fill(0).map((ele, index) => index)\n\n    // recursively finding the root of rarget node\n    const find = (a) => {\n        if(forest[a] === a) {\n            return a\n        }\n        return find(forest[a])\n    }\n    \n    // function for uniting two stones\n    const union = (a, b) => {\n        const rootA = find(a)\n        const rootB = find(b)\n        if(rootA != rootB) {\n            //connect their roots if currently they are not connected\n            forest[rootA] = rootB\n            //subtract the number of islands by one since two islands are connected now\n            numComponents -= 1\n        }\n    }\n    \n    for(let i = 0; i < stones.length - 1; i++) {\n        for(let j = i + 1; j < stones.length; j++) {\n            // if two stones are connected(i.e. share same row or column), unite them\n            if(stones[i][0] === stones[j][0] || stones[i][1] === stones[j][1]) {\n                union(i, j)\n            }\n        }\n    }\n\n    // this is the most confusing part.\n    // The number of stones can be removed is not equal to the number of islands.\n    // e.g. we have two islands with total of 10 stores, each island will leave one extra stone after the \n    // removal, therefore we can remove 10 - 2 = 8 stones in total\n    return n - numComponents\n};",
        "solution_java": "class Solution {\n    public int removeStones(int[][] stones) {\n        int ret=0;\n        DisjointSet ds=new DisjointSet(stones.length);\n\n        for(int i=0;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}",
        "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};"
    },
    {
        "title": "Friends Of Appropriate Ages",
        "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",
        "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",
        "solution_js": "var numFriendRequests = function(ages) {\n    const count = new Array(121).fill(0);\n\n    ages.forEach((age) => count[age]++);\n\n    let res = 0; // total friend request sent\n    let tot = 0; // cumulative count of people so far\n\n    for (let i = 0; i <= 120; i++) {\n\n        if (i > 14 && count[i] != 0) {\n            const limit = Math.floor(0.5 * i) + 7;\n            const rest = tot - count[limit];\n\n            res += (count[i] * rest); // current age group send friend request to other people who are within their limit\n            res += (count[i] * (count[i] - 1)); // current age group send friend request to each other\n        }\n\n        tot += count[i];\n        count[i] = tot;\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    static int upperBound(int arr[], int target) {\n        int l = 0, h = arr.length - 1;\n        for (; l <= h;) {\n            int mid = (l + h) >> 1;\n            if (arr[mid] <= target)\n                l = mid + 1;\n            else\n                h = mid - 1;\n        }\n        return l;\n    }\n    public int numFriendRequests(int[] ages) {\n        long ans = 0;\n        Arrays.sort(ages);\n\t\t// traversing order doesn't matter as we are doing binary-search in whole array\n\t\t// you can traverse from left side also\n        for(int i = ages.length - 1;i >= 0;--i){\n            int k = upperBound(ages,ages[i] / 2 + 7);\n            int t = upperBound(ages,ages[i]);\n            ans += Math.max(0,t - k - 1);\n        }\n        return (int)ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numFriendRequests(vector<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};"
    },
    {
        "title": "Rank Teams by Votes",
        "algo_input": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.\n\nThe ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.\n\nGiven an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.\n\nReturn a string of all teams sorted by the ranking system.\n\n&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",
        "solution_py": "#[\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\n#d = {\n#    \"A\": [5, 0, 0],\n#    \"B\": [0, 2, 3],\n#    \"C\": [0, 3, 2]\n#}\n#keys represent the candidates\n#index of array in dict represent the rank\n#value of array item represent number of votes casted\n#ref: https://www.programiz.com/python-programming/methods/built-in/sorted\nclass Solution:\n    #T=O(mn + mlgm), S=O(mn)\n\t#n=number of votes\n\t#m=number of candidates and m(number of ranks) is constant(26)\n    def rankTeams(self, votes: List[str]) -> str:\n        d = {}\n        #build the dict\n        #T=O(mn), S=O(mn)\n\t\t#n=number of votes, m=number of candidates(26)\n        for vote in votes:\n            for i, c in enumerate(vote):\n                #if key not in dict\n                if c not in d:\n                    #d[char] = [0, 0, 0]\n                    d[c] = [0]*len(vote)\n                #increment the count of votes for each rank\n                #d[\"A\"][0] = 1\n                d[c][i] += 1\n        #sort the dict keys in ascending order because if there is a tie we return in ascending order\n\t\t#sorted uses a stable sorting algorithm\n        #T=O(mlgm), S=O(m)\n        vote_names = sorted(d.keys()) #d.keys()=[\"A\", \"B\", \"C\"]\n        #sort the dict keys based on votes for each rank in descending order\n        #T=O(mlgm), S=O(m)\n        #sorted() always returns a list\n        vote_rank = sorted(vote_names, reverse=True, key= lambda x: d[x])\n        #join the list\n        return \"\".join(vote_rank)",
        "solution_js": "var rankTeams = function(votes) {\n     if(votes.length == 1)\n        return votes[0];\n    let map = new Map()\n    for(let vote of votes){\n        for(let i = 0; i < vote.length;i++){\n            if(!(map.has(vote[i]))){\n            //create all the values set as zero\n                map.set(vote[i],Array(vote.length).fill(0))\n            }\n            let val = map.get(vote[i])\n            val[i] = val[i] + 1\n            map.set(vote[i], val)\n        }\n    }\n\n    let obj = [...map.entries()]; //converting as array [\"A\",[5,0,0]]\n    obj = obj.sort((a,b) => {\n        for(let i = 0; i < a[1].length;i++){\n            if(a[1][i] > b[1][i])\n                return -1;\n            else if(a[1][i] < b[1][i])\n                return 1;\n        }\n        // if all chars are in same positon return the value charcode\n        return a[0].charCodeAt(0) - b[0].charCodeAt(0);\n    })\n    return obj.map(item => item[0]).join('')\n};",
        "solution_java": "class Solution {\n    public String rankTeams(String[] votes) {\n        int n = votes.length;\n        int teams = votes[0].length();\n        Map<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}",
        "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};"
    },
    {
        "title": "Flatten Binary Tree to Linked List",
        "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)?",
        "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).",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {void} Do not return anything, modify root in-place instead.\n */\nvar flatten = function(root) {\n    const dfs = (node) => {\n        if (!node) return\n\n        if (!node.left && !node.right) return node\n\n        const leftNode = node.left\n        const rightNode = node.right\n\n        const leftTree = dfs(leftNode)\n        const rightTree = dfs(rightNode)\n\n        if (leftTree) leftTree.right = rightNode\n\n        node.left = null\n        node.right = leftNode || rightNode\n\n        return rightTree || leftTree\n    }\n\n    dfs(root)\n    return root\n};",
        "solution_java": "class Solution {\n    public void flatten(TreeNode root) {\n        TreeNode curr=root;\n        while(curr!=null)\n        {\n            if(curr.left!=null)\n            {\n               TreeNode prev=curr.left;\n               while(prev.right!=null)\n                   prev=prev.right;\n               prev.right=curr.right;\n               curr.right=curr.left; \n               curr.left=null; \n            }\n            curr=curr.right;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* prev= NULL;\n    \n    void flatten(TreeNode* root) {\n        if(root==NULL) return;\n        \n        flatten(root->right);\n        flatten(root->left);\n        \n        root->right=prev;\n        root->left= NULL;\n        prev=root;\n    }\n};"
    },
    {
        "title": "Minimum Insertion Steps to Make a String Palindrome",
        "algo_input": "Given a string s. In one step you can insert any character at any index of the string.\n\nReturn the minimum number of steps to make s&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",
        "solution_py": "class Solution:\n    def minInsertions(self, s: str) -> int:\n        n = len(s)\n        prev_prev = [0]*n\n        prev = [0]*n\n        curr = [0] * n\n\n        for l in range(1, n):\n            for i in range(l, n):\n                if s[i] == s[i-l]:\n                    curr[i] = prev_prev[i-1]\n                else:\n                    curr[i] = min(prev[i-1], prev[i])+1\n            # print(curr)\n            prev_prev, prev, curr = prev, curr, prev_prev\n        \n        return prev[-1]",
        "solution_js": "var minInsertions = function(s) {\n    const len = s.length;\n    const dp = new Array(len).fill(0).map(() => {\n        return new Array(len).fill(-1);\n    });\n\n    const compute = (i = 0, j = len - 1) => {\n        if(i >= j) return 0;\n\n        if(dp[i][j] != -1) return dp[i][j];\n\n        if(s[i] == s[j]) return compute(i + 1, j - 1);\n\n        return dp[i][j] = Math.min(\n            compute(i + 1, j),\n            compute(i, j - 1)\n        ) + 1;\n    }\n    return compute();\n};",
        "solution_java": "class Solution {\n    public int minInsertions(String s) {\n        StringBuilder sb = new StringBuilder(s);\n         String str = sb.reverse().toString();\n        int m=s.length();\n        int n=str.length();\n         System.out.println(str);\n        return LCS(s,str,m,n);\n\n    }\n    public int LCS(String x, String y,int m,int n){\n        int [][] t = new int [m+1][n+1];\n        for(int i=0;i<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}",
        "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};"
    },
    {
        "title": "Rearrange Words in a Sentence",
        "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",
        "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()",
        "solution_js": "var arrangeWords = function(text) {\n    let sorted = text.toLowerCase().split(' ');\n    \n    sorted.sort((a, b) => a.length - b.length);\n    \n    sorted[0] = sorted[0].charAt(0).toUpperCase() + sorted[0].slice(1);\n    \n    return sorted.join(' ');\n};",
        "solution_java": "class Solution {\n    public String arrangeWords(String text) {\n        String[] words = text.split(\" \");\n        for (int i = 0; i < words.length; i++) {\n            words[i] = words[i].toLowerCase();\n        }\n        Arrays.sort(words, (s, t) -> s.length() - t.length());\n        words[0] = Character.toUpperCase(words[0].charAt(0)) + words[0].substring(1);\n        return String.join(\" \", words);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<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};"
    },
    {
        "title": "Maximum Depth of N-ary Tree",
        "algo_input": "Given a n-ary tree, find its maximum depth.\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n\n&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",
        "solution_py": "class Solution:\n    def maxDepth(self, root: 'Node') -> int:\n        \n        if not root : return 0\n        \n        if root.children :\n            return 1 + max([self.maxDepth(x) for x in root.children])\n        else :\n            return 1 ",
        "solution_js": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n\n/**\n * @param {Node|null} root\n * @return {number}\n */\nvar maxDepth = function(root) {\n  let max = 0;\n\n  if (!root) {\n    return max;\n  }\n\n  const search = (root, index) => {\n    max = Math.max(index, max);\n\n    if (root?.children && root?.children.length > 0) {\n      for (let i = 0; i < root.children.length; i++) {\n        search(root.children[i], index+1);\n      }\n    }\n  }\n\n  search(root, 1);\n\n  return max;\n};",
        "solution_java": "class Solution {\n    public int maxDepth(Node root) {\n        if (root == null) return 0;\n        int[] max = new int[]{0};\n        dfs(root,1,max);\n        return max[0];\n    }\n    public static void dfs(Node root, int depth, int[] max) {\n        if (depth>max[0]) max[0] = depth;\n        if(root==null){\n            return;\n        }\n        ++depth;\n        for(Node n:root.children) dfs(n, depth, max);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDepth(Node* root) \n    {\n        if(root == NULL)\n        {\n            return 0;\n        }\n        int dep = 1, mx = INT_MIN;\n        helper(root, dep, mx);\n        return mx;\n    }\n    \n    void helper(Node *root, int dep, int& mx)\n    {\n        if(root->children.size() == 0)\n        {\n            mx = max(mx, dep);\n        }\n        for(int i = 0 ; i<root->children.size() ; i++)\n        {\n            helper(root->children[i], dep+1, mx);\n        }\n    }\n};"
    },
    {
        "title": "Smallest String With A Given Numeric Value",
        "algo_input": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.\n\nThe numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8.\n\nYou are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.\n\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n\n&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",
        "solution_py": "class Solution:\n    def getSmallestString(self, n: int, k: int) -> str:\n        ans = ['a']*n # Initialize the answer to be 'aaa'.. length n\n        val = n #Value would be length as all are 'a'\n\n        for i in range(n-1, -1, -1):\n            if val == k: # if value has reached k, we have created our lexicographically smallest string\n                break\n            val -= 1 # reduce value by one as we are removing 'a' and replacing by a suitable character\n            ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or 'z'\n            val += ord(ans[i]) - 96 # add the value of newly appended character to value\n\n        return ''.join(ans) # return the ans string in the by concatenating the list",
        "solution_js": "var getSmallestString = function(n, k) {\n    k -= n\n    let alpha ='_bcdefghijklmnopqrstuvwxy_',\n        ans = 'z'.repeat(~~(k / 25))\n    if (k % 25) ans = alpha[k % 25] + ans\n    return ans.padStart(n, 'a')\n};",
        "solution_java": "class Solution {\n    public String getSmallestString(int n, int k) {\n        char[] ch = new char[n];\n        for(int i=0;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}",
        "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// "
    },
    {
        "title": "Maximum XOR of Two Numbers in an Array",
        "algo_input": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 &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",
        "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",
        "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};",
        "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}",
        "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};"
    },
    {
        "title": "Valid Number",
        "algo_input": "A valid number can be split up into these components (in order):\n\n\n\tA decimal number or an integer.\n\t(Optional) An 'e' or 'E', followed by an integer.\n\n\nA decimal number can be split up into these components (in order):\n\n\n\t(Optional) A sign character (either '+' or '-').\n\tOne of the following formats:\n\t\n\t\tOne or more digits, followed by a dot '.'.\n\t\tOne or more digits, followed by a dot '.', followed by one or more digits.\n\t\tA dot '.', followed by one or more digits.\n\t\n\t\n\n\nAn integer can be split up into these components (in order):\n\n\n\t(Optional) A sign character (either '+' or '-').\n\tOne or more digits.\n\n\nFor example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"], while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"].\n\nGiven a string s, return true if s is a valid number.\n\n&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",
        "solution_py": "class Solution:\n    def isNumber(self, s: str) -> bool:\n        if s == \"inf\" or s == \"-inf\" or s == \"+inf\" or s == \"Infinity\" or s == \"-Infinity\" or s == \"+Infinity\":\n            return False\n        try:\n            float(s)\n        except (Exception):\n            return False\n        return True",
        "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar isNumber = function(s) {\n    const n = s.length;\n    const CHAR_CODE_UPPER_E = 'E'.charCodeAt(0);\n    const CHAR_CODE_LOWER_E = 'e'.charCodeAt(0);\n    const CHAR_CODE_UPPER_A = 'A'.charCodeAt(0);\n    const CHAR_CODE_UPPER_Z = 'Z'.charCodeAt(0);\n    const CHAR_CODE_LOWER_A = 'a'.charCodeAt(0);\n    const CHAR_CODE_LOWER_Z = 'z'.charCodeAt(0);\n\n    let sign = '';\n    let decimal = '';\n    let exponential = '';\n    let exponentialSign = '';\n    let num = '';\n    for(let i = 0; i < n; i += 1) {\n        const char = s[i];\n        const charCode = s.charCodeAt(i);\n\n        if(char === '+' || char === '-') {\n            if(i === n - 1) return false;\n            if(i === 0) {\n                sign = char;\n                continue;\n            }\n\n            if(exponentialSign.length > 0) return false;\n            if(!(s[i - 1] === 'e' || s[i - 1] === 'E')) return false;\n            exponentialSign = char;\n            continue;\n        }\n\n        if(char === '.') {\n            if(decimal.length > 0) return false;\n            if(exponential.length > 0) return false;\n            if(num.length === 0 && i === n - 1) return false;\n\n            decimal = char;\n            continue;\n        }\n\n        if(charCode === CHAR_CODE_UPPER_E || charCode === CHAR_CODE_LOWER_E) {\n            if(exponential.length > 0) return false;\n            if(i === n - 1) return false;\n            if(num.length === 0) return false;\n\n            exponential = char;\n            continue;\n        }\n\n        if(charCode >= CHAR_CODE_UPPER_A && charCode <= CHAR_CODE_UPPER_Z) {\n            return false;\n        }\n\n        if(charCode >= CHAR_CODE_LOWER_A && charCode <= CHAR_CODE_LOWER_Z) {\n            return false;\n        }\n\n        num += char;\n    }\n\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isNumber(String s) {\n        try{\n            int l=s.length();\n            if(s.equals(\"Infinity\")||s.equals(\"-Infinity\")||s.equals(\"+Infinity\")||s.charAt(l-1)=='f'||s.charAt(l-1)=='d'||s.charAt(l-1)=='D'||s.charAt(l-1)=='F')\n            return false;\n            double x=Double.parseDouble(s);\n            return true;\n        }\n        catch(Exception e){\n            return false;\n        }\n        \n    }\n}",
        "solution_c": "/*\nMax Possible combination of characters in the string has followig parts(stages) :\n            +/- number . number e/E +/- number\nstages: 0 1 2 3 4 5 6 7\n\nNow check each characters at there correct stages or not and increament the stage\nas per the character found at ith position.\n\n*/\n\nclass Solution {\npublic:\n    bool isNumber(string s){\n        char stage = 0;\n        for(int i = 0; i<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};"
    },
    {
        "title": "Sort Integers by The Number of 1 Bits",
        "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",
        "solution_py": "class Solution:\n    def sortByBits(self, arr: List[int]) -> List[int]:\n        binary = []\n        final = []\n        arr.sort()\n        for i in arr:\n            binary.append(bin(i).count(\"1\"))\n        for i,j in zip(arr,binary):\n            final.append((i,j))\n        z = sorted(final, key=lambda x:x[1])\n        \n        ls = []\n        for k in z:\n            ls.append(k[0])\n        \n        return ls",
        "solution_js": "var sortByBits = function(arr) {\n    const map = {};\n    \n    for (let n of arr) {\n        let counter = 0, item = n;\n        \n        while (item > 0) {\n\t\t\tcounter += (item & 1);    //increment counter if the lowest (i.e. the rightest) bit is 1\n\t\t\titem = (item >> 1);        //bitwise right shift (here is equivalent to division by 2)\n        }\n        \n        map[n] = counter;\n    }\n\n    return arr.sort((a, b) => map[a] - map[b] || a - b) //sort by number of 1 bits; if equal, sort by value\n};",
        "solution_java": "class Solution {\n    public int[] sortByBits(int[] arr) {\n\n        Integer[] arrInt = new Integer[arr.length];\n\n        for(int i=0;i<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}",
        "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};"
    },
    {
        "title": "Valid Palindrome II",
        "algo_input": "Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n\n&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",
        "solution_py": "class Solution:\n    def validPalindrome(self, s: str) -> bool:\n        has_deleted = False\n\n        def compare(s, has_deleted):\n\n            if len(s) <= 1:\n                return True\n\n            if s[0] == s[-1]:\n                return compare(s[1:-1], has_deleted)\n            else:\n                if not has_deleted:\n                    return compare(s[1:], True) or compare(s[:-1], True)\n                else:\n                    return False\n\n        return compare(s, has_deleted)",
        "solution_js": "/*\nSolution:\n\n1. Use two pointers, one initialised to 0 and the other initialised to end of string. Check if characters at each index\nare the same. If they are the same, shrink both pointers. Else, we have two possibilities: one that neglects character\nat left pointer and the other that neglects character at right pointer. Hence, we check if s[low+1...right] is a palindrome\nor s[low...right-1] is a palindrome. If one of them is a palindrome, we know that we can form a palindrome with one deletion and return true. Else, we require more than one deletion, and hence we return false.\n*/\nvar validPalindrome = function(s) {\n    let low = 0, high = s.length-1;\n    while (low < high) {\n        if (s[low] !== s[high]) {\n            return isPalindrome(s, low+1, high) || isPalindrome(s, low, high-1);\n        }\n        low++, high--;\n    }\n    return true;\n    // T.C: O(N)\n    // S.C: O(1)\n};\n\nfunction isPalindrome(str, low, high) {\n    while (low < high) {\n        if (str[low] !== str[high]) return false;\n        low++, high--;\n    }\n    return true;\n}",
        "solution_java": "class Solution {\n    boolean first = false;\n    public boolean validPalindrome(String s) {\n        int left = 0;\n        int right = s.length()-1;\n        \n        \n        while(left <= right){\n            if( s.charAt(left) == (s.charAt(right))){\n                left++;\n                right--;\n            }else if(!first){\n                first = true;\n                String removeLeft = s.substring(0,left).concat(s.substring(left+1));\n                String removeright = s.substring(0,right).concat(s.substring(right+1));\n                left++;\n                right--;\n                return validPalindrome(removeLeft) || validPalindrome(removeright);   \n            } else {\n                return false;\n            }\n        }\n     return true;   \n    }\n}",
        "solution_c": "class Solution {\n  int first_diff(string s) {\n    for (int i = 0; i < (s.size() + 1) / 2; ++i) {\n      if (s[i] != s[s.size() - 1 - i]) {\n        return i;\n      }\n    }\n    return -1;\n  }\npublic:\n    bool validPalindrome(string s) {\n      int diff = first_diff(s);\n      if (diff == -1 || (s.size() % 2 == 0 && diff + 1 == s.size() / 2)) {\n        // abca. If we have pattern like this than we can delete one of the symbols\n        return true;\n      }\n      \n      bool first_valid = true;\n      for (int i = diff; i < (s.size() + 1) / 2; ++i) {\n        if (s[i] != s[s.size() - 2 - i]) {\n          first_valid = false;\n          break;\n        }\n      }\n      \n      bool second_valid = true;\n      for (int i = diff; i < (s.size() + 1) / 2; ++i) {\n        if (s[i + 1] != s[s.size() - 1 - i]) {\n          second_valid = false;\n          break;\n        }\n      }\n      return first_valid || second_valid;\n    }\n};"
    },
    {
        "title": "Add Two Numbers",
        "algo_input": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\n&nbsp;\nExample 1:\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [7,0,8]\nExplanation: 342 + 465 = 807.\n\n\nExample 2:\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\nExample 3:\n\nInput: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput: [8,9,9,9,0,0,0,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in each linked list is in the range [1, 100].\n\t0 &lt;= Node.val &lt;= 9\n\tIt is guaranteed that the list represents a number that does not have leading zeros.\n\n",
        "solution_py": "class Solution:\n    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n        dummyHead = ListNode(0)\n        tail = dummyHead\n        carry = 0\n\n        while l1 is not None or l2 is not None or carry != 0:\n            digit1 = l1.val if l1 is not None else 0\n            digit2 = l2.val if l2 is not None else 0\n\n            sum = digit1 + digit2 + carry\n            digit = sum % 10\n            carry = sum // 10\n\n            newNode = ListNode(digit)\n            tail.next = newNode\n            tail = tail.next\n\n            l1 = l1.next if l1 is not None else None\n            l2 = l2.next if l2 is not None else None\n\n        result = dummyHead.next\n        dummyHead.next = None\n        return result",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n *     this.val = val;\n *     this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nvar addTwoNumbers = function(l1, l2) {\n    var List = new ListNode(0);\n    var head = List;\n    var sum = 0;\n    var carry = 0;\n\n    while(l1!==null||l2!==null||sum>0){\n\n        if(l1!==null){\n            sum = sum + l1.val;\n            l1 = l1.next;\n        }\n        if(l2!==null){\n            sum = sum + l2.val;\n            l2 = l2.next;\n        }\n        if(sum>=10){\n            carry = 1;\n            sum = sum - 10;\n        }\n\n        head.next = new ListNode(sum);\n        head = head.next;\n\n        sum = carry;\n        carry = 0;\n\n    }\n\n    return List.next;\n};",
        "solution_java": "class Solution {\n    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n        if(l1 == null) return l2;\n        if(l2 == null) return l1;\n        \n        ListNode dummy = new ListNode(-1);\n        ListNode temp = dummy;\n        int carry = 0;\n        while(l1 != null || l2 != null || carry != 0){\n            int sum = 0;\n            if(l1 != null){\n                sum += l1.val;\n                l1 = l1.next;\n            }\n            if(l2 != null){\n                sum += l2.val;\n                l2 = l2.next;\n            } \n            sum += carry;\n            carry = sum / 10;\n            ListNode node = new ListNode(sum % 10);\n            temp.next = node;\n            temp = temp.next;\n        }\n        return dummy.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n        ListNode *head1, *head2, *head3, *temp;\n        head1=l1;\n        head2 = l2;\n        head3=NULL;\n        int carry = 0, res = 0;\n        while(head1 && head2){\n            res = head1->val +head2->val + carry;\n            carry = res/10;\n            head1->val = res%10;\n            if(!head3){\n                head3 = head1;\n                temp = head3;\n            }\n            else{\n                temp->next = head1;\n                temp = temp->next;\n            }\n            head1 = head1->next;\n            head2 = head2->next;\n        }\n        while(head1){\n            res = head1->val + carry;\n            carry = res/10;\n            head1->val = res%10;\n            temp->next = head1;\n            temp = temp->next;\n            head1 = head1->next;\n        }\n        while(head2){\n            res = head2->val + carry;\n            carry = res/10;\n            head2->val = res%10;\n            temp->next = head2;\n            temp = temp->next;\n            head2 = head2->next;\n        }\n        if(carry){\n            ListNode* result = new ListNode();\n            result->val = carry;\n            result->next = NULL;\n            temp->next = result;\n            temp = temp->next;\n        }\n        return head3;\n    }\n};"
    },
    {
        "title": "Next Greater Numerically Balanced Number",
        "algo_input": "An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.\n\nGiven an integer n, return the smallest numerically balanced number strictly greater than n.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 22\nExplanation: \n22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.\n\n\nExample 2:\n\nInput: n = 1000\nOutput: 1333\nExplanation: \n1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.\n\n\nExample 3:\n\nInput: n = 3000\nOutput: 3133\nExplanation: \n3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def nextBeautifulNumber(self, n: int) -> int:\n        n_digits = len(str(n))\n        \n        next_max = {\n            1: [1],\n            2: [22],\n            3: [122, 333],\n            4: [1333, 4444],\n            5: [14444, 22333, 55555],\n            6: [122333, 224444, 666666, 155555],\n            7: [1224444, 2255555, 3334444, 1666666, 7777777]\n                }\n        \n        if n >= int(str(n_digits) * n_digits):\n            n_digits += 1\n            return min(next_max[n_digits])\n        \n        ans = float('inf')\n        for num in sorted(next_max[n_digits]):      \n            cands = set(permutations(str(num)))\n            cands = sorted(map(lambda x: int(\"\".join(x)), cands))\n        \n            loc = bisect.bisect(cands, n)\n            if loc < len(cands):           \n                ans = min(ans, cands[loc])\n        \n        return ans",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar nextBeautifulNumber = function(n) {\n    //1224444 is next minimum balanced number after 10^6\n    for(let i=n+1; i<=1224444;i++){//Sequency check each number from n+1 to 1224444\n        if(isNumericallyBalanced(i)){\n            return i;//Return the number if is a balanced number\n        }\n    }\n    function isNumericallyBalanced(n){\n        let map={},d,nStr=n.toString();\n        while(n>0){//Create a map of digits with frequency\n            d = n%10;\n            if(d>nStr.length){//If we have found a digit greater than the lenght of the number like 227333, here when we see 7, we can return false\n                return false;\n            }\n            if(map[d]===undefined){\n                map[d]=1;\n            }else{\n                map[d]++;\n                if(map[d]>d){//If a digit has frequency more than its value, for example 22333344, here when we see fourth 3 than we can return false\n                    return false;\n                }\n            }\n            n = Math.floor(n/10);\n        }\n        for(let key in map){//Check if frequency is equal to the digit\n            if(map[key]!==parseInt(key)){\n                return false;\n            }\n        }\n        return true;\n    }\n};",
        "solution_java": "class Solution {\n    public int nextBeautifulNumber(int n) {\n\n        while(true){\n            n++;\n           int num = n; //test this number\n           int [] freq = new int[10]; // 0 to 9\n\n            while(num > 0){ //calculate freq of each digit in the num\n                int rem = num % 10; //this is remainder\n                num = num / 10; //this is quotient\n                freq[rem] = freq[rem] + 1; //increase its frequency\n                if(freq[rem] > rem) break;\n            }\n\n            boolean ans = true;\n\n            for(int i = 0;i<10;i++){ //check frequency of each digit\n              if(freq[i] != i && freq[i] != 0){\n                  ans = false;\n                  break;\n              }\n            }\n\n            if(ans == true){\n                return n;\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool valid(int n)\n    {\n        vector<int> map(10,0);\n        while(n)\n        {\n            int rem = n%10;\n            map[rem]++;\n            n = n/10;\n        }\n        for(int i=0; i<10; i++)\n            if(map[i] && map[i]!=i) return false;\n        return true;\n    }\n    \n    int nextBeautifulNumber(int n) {\n     \n        while(true) \n        {\n            ++n;\n            if(valid(n))\n                return n;\n        }\n        return 1;\n    }\n};"
    },
    {
        "title": "Is Subsequence",
        "algo_input": "Given two strings s and t, return true if s is a subsequence of t, or false otherwise.\n\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n\n&nbsp;\nExample 1:\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nExample 2:\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 100\n\t0 &lt;= t.length &lt;= 104\n\ts and t consist only of lowercase English letters.\n\n\n&nbsp;\nFollow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k &gt;= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?",
        "solution_py": "class Solution:\n    def isSubsequence(self, s: str, t: str) -> bool:\n        if len(s) > len(t):return False\n        if len(s) == 0:return True\n        subsequence=0\n        for i in range(0,len(t)):\n            if subsequence <= len(s) -1:\n                print(s[subsequence])\n                if s[subsequence]==t[i]:\n\n                    subsequence+=1\n        return  subsequence == len(s) ",
        "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isSubsequence = function(s, t) {\n    for (let i = 0, n = s.length; i < n; i++)\n        if (t.includes(s[i]))\n            t = t.slice(t.indexOf(s[i]) + 1);\n        else return false;\n    \n    return true;\n}",
        "solution_java": "class Solution \n{\n    public boolean isSubsequence(String s, String t) \n    {\n        int i,x,p=-1;\n        if(s.length()>t.length())\n            return false;\n        for(i=0;i<s.length();i++)\n        {\n            x=t.indexOf(s.charAt(i),p+1);\n            if(x>p)\n                p=x;\n            else\n                return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSubsequence(string s, string t) {\n        int n = s.length(),m=t.length();\n        int j = 0; \n    // For index of s (or subsequence\n \n    // Traverse s and t, and\n    // compare current character\n    // of s with first unmatched char\n    // of t, if matched\n    // then move ahead in s\n    for (int i = 0; i < m and j < n; i++)\n        if (s[j] == t[i])\n            j++;\n \n    // If all characters of s were found in t\n    return (j == n);\n    }\n};"
    },
    {
        "title": "Permutation in String",
        "algo_input": "Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.\n\nIn other words, return true if one of s1's permutations is the substring of s2.\n\n&nbsp;\nExample 1:\n\nInput: s1 = \"ab\", s2 = \"eidbaooo\"\nOutput: true\nExplanation: s2 contains one permutation of s1 (\"ba\").\n\n\nExample 2:\n\nInput: s1 = \"ab\", s2 = \"eidboaoo\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s1.length, s2.length &lt;= 104\n\ts1 and s2 consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def checkInclusion(self, s1: str, s2: str) -> bool:\n        if len(s1) > len(s2):\n            return False\n        s1_map = {}\n        s2_map = {}\n        for i in range(ord('a') , ord('z') + 1):\n            s1_map[chr(i)] = 0\n            s2_map[chr(i)] = 0\n        \n        for i in s1:\n            s1_map[i] += 1\n            \n        l = 0\n        r = 0\n        \n        while r < len(s2):\n            print(s2_map , l ,r)\n            if r == 0:\n                while r < len(s1):\n                    s2_map[s2[r]] += 1\n                    r += 1\n                if s2_map == s1_map:\n                    return True\n\n            else:\n                s2_map[s2[l]] -= 1\n                s2_map[s2[r]] += 1\n                \n                if s2_map == s1_map:\n                    return True\n                else:\n                    l += 1\n                    r += 1\n            \n        return False      ",
        "solution_js": "const getCharIdx = (c) => c.charCodeAt(0) - 'a'.charCodeAt(0);\nconst isEqual = (a, b) => a.every((v, i) => v == b[i]);\n\nvar checkInclusion = function(s1, s2) {\n    const occS1 = new Array(26).fill(0);\n    const occS2 = new Array(26).fill(0);\n\n    const s1Len = s1.length, s2Len = s2.length;\n\n    if(s1Len > s2Len) return false;\n\n    let l = 0, r = 0;\n    for(; r < s1Len ; r++) {\n        occS1[getCharIdx(s1[r])]++;\n        occS2[getCharIdx(s2[r])]++;\n    }\n\n    if(isEqual(occS1, occS2)) {\n        return true;\n    }\n\n    for(; r < s2Len; r++) {\n        occS2[getCharIdx(s2[r])]++;\n        occS2[getCharIdx(s2[l++])]--;\n\n        if(isEqual(occS1, occS2)) return true;\n    }\n\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean checkInclusion(String s1, String s2) {\n        if(s1.length() > s2.length()) {\n            return false;\n        }\n        \n        int[]s1Count = new int[26];\n        int[]s2Count = new int[26];\n        \n        for(int i = 0; i < s1.length(); i++) {\n            char c = s1.charAt(i);\n            char s = s2.charAt(i);\n            s1Count[c - 'a'] += 1;\n            s2Count[s - 'a'] += 1;\n        }\n        \n        int matches = 0;\n        \n        for(int i = 0; i < 26;i++) {\n            if(s1Count[i] == s2Count[i]) {\n                matches+=1;\n            }\n        }\n        \n        int left = 0;\n        for(int right = s1.length(); right < s2.length();right++) {\n            if(matches == 26) {\n                return true;\n            }\n            \n            int index = s2.charAt(right) - 'a';\n            s2Count[index] += 1;\n            if(s1Count[index] == s2Count[index]) {\n                matches += 1;\n            }\n            else if(s1Count[index] + 1 == s2Count[index]) {\n                matches -= 1;\n            }\n            \n            index = s2.charAt(left) - 'a';\n            s2Count[index] -= 1;\n            if(s1Count[index] == s2Count[index]) {\n                matches += 1;\n            }\n            else if(s1Count[index] - 1 == s2Count[index]) {\n                matches -= 1;\n            }\n            left += 1;\n        }\n        \n        if(matches == 26) {\n            return true;\n        }\n        \n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool checkInclusion(string s1, string s2) {\n\t\tsort(s1.begin(),s1.end());\n\t\tint n = s1.size(), m = s2.size();\n\t\tfor(int i=0;i<=m-n;i++)\n\t\t{\n\t\t\tstring s = s2.substr(i,n);\n\t\t\tsort(s.begin(),s.end());\n\t\t\tif(s1 == s)     return true;\n\t\t}\n\t\treturn false;\n\t}\n};"
    },
    {
        "title": "Egg Drop With 2 Eggs and N Floors",
        "algo_input": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.\n\nYou know that there exists a floor f where 0 &lt;= f &lt;= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\n\nIn each move, you may take an unbroken egg and drop it from any floor x (where 1 &lt;= x &lt;= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 2\nExplanation: We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.\n\n\nExample 2:\n\nInput: n = 100\nOutput: 14\nExplanation: One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    @cache\n    def twoEggDrop(self, n: int) -> int:\n        return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1)",
        "solution_js": "/** https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/\n * @param {number} n\n * @return {number}\n */\nvar twoEggDrop = function(n) {\n  // Writing down strategy on example 2 we can observe following pattern:\n  // Drop at floor:   9   22    34    45    55    64    72    79    85    90    94    97    99    100\n  // Diff from prev:      13    12    11    10    9     8     7     6     5     4     3     2     1\n  \n  // So we have hypothesis algorithm\n  // That is, `n` minus `d` until `result(n)` is smaller than `d`, where `d` start at 1 and increment by 1 for each iteration. If `result(n)` is 0, subtract 1, else return the result\n  \n  let d = 1;\n  \n  while (n > d) {\n    n -= d;\n    d++;\n  }\n  \n  if (n == 0) {\n    d--;\n  }\n  \n  return d;\n};",
        "solution_java": "class Solution {\n    public int twoEggDrop(int n) {\n        int egg = 2; // hard coded to 2 eggs for this problem\n        int[][] dp = new int[n+1][egg+1];\n        return eggDrop(n, egg, dp);\n    }\n\n    int eggDrop(int n, int egg, int[][] dp) {\n        if(n <= 2 || egg == 1) return n;\n        if(dp[n][egg] != 0) return dp[n][egg];\n        int min = n; // when you drop at each floor starting from 1\n        for(int i = 1; i < n; i++) {\n            int eggBreak = 1 + eggDrop(i-1, egg-1, dp); // drops needed if egg breaks at this floor\n            int noEggBreak = 1 + eggDrop(n-i, egg, dp); // drops needed if egg does not break at this floor\n            int moves = Math.max(eggBreak, noEggBreak); // since we want certain moves for n floor take max\n            min = Math.min(min, moves);\n        }\n        dp[n][egg] = min;\n        return min;\n    }\n}",
        "solution_c": "int dp[1001][1001];\nclass Solution {\npublic:\n    int solve(int e, int f){\n        if(f == 0 || f == 1){\n            return f;\n        }\n        if(e == 1){\n            return f;\n        }\n        if(dp[e][f] != -1) return dp[e][f];\n        int mn = INT_MAX;\n        int left = 1, right = f;\n        while(left <= right){\n            int mid = left + (right-left)/2;\n            int left_result = solve(e-1,mid-1);\n            int right_result = solve(e,f-mid);\n            mn = min(mn,1+max(left_result, right_result));\n            if(left_result<right_result)\n                left = mid+1;\n            else\n                right = mid-1;\n        }\n        return dp[e][f] = mn;\n    }\n    int twoEggDrop(int n) {\n        memset(dp, -1, sizeof(dp));\n        return solve(2,n);\n    }\n};"
    },
    {
        "title": "Maximum Ice Cream Bars",
        "algo_input": "It is a sweltering summer day, and a boy wants to buy some ice cream bars.\n\nAt the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.&nbsp;\n\nReturn the maximum number of ice cream bars the boy can buy with coins coins.\n\nNote: The boy can buy the ice cream bars in any order.\n\n&nbsp;\nExample 1:\n\nInput: costs = [1,3,2,4,1], coins = 7\nOutput: 4\nExplanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\n\n\nExample 2:\n\nInput: costs = [10,6,8,7,7,8], coins = 5\nOutput: 0\nExplanation: The boy cannot afford any of the ice cream bars.\n\n\nExample 3:\n\nInput: costs = [1,6,3,1,2,5], coins = 20\nOutput: 6\nExplanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n\n\n&nbsp;\nConstraints:\n\n\n\tcosts.length == n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= costs[i] &lt;= 105\n\t1 &lt;= coins &lt;= 108\n",
        "solution_py": "class Solution:\n    def maxIceCream(self, costs: List[int], coins: int) -> int:\n        costs.sort()\n        i= 0\n        for price in costs:\n            if price<= coins:\n                i+= 1\n                coins-= price\n            else:\n                break\n        return i",
        "solution_js": "var maxIceCream = function(costs, coins) {\n  costs.sort((a, b) => a - b);\n  let count = 0;\n\n  for (let i = 0; i < costs.length; i++) {\n    if (costs[i] <= coins) {\n      count++;\n      coins -= costs[i]\n    } else {\n      break; // a small optimization, end the loop early if coins go down to zero before we reach end of the length of costs.\n    }\n  }\n  return count;\n};",
        "solution_java": "class Solution {\n    public int maxIceCream(int[] costs, int coins) {\n\n        //Greedy Approach\n        //a. sort cost in increasing order\n\n        Arrays.sort(costs);\n\n        int count = 0;\n        for(int cost : costs){\n\n            //b. check remainig coin is greater or equal than cuurent ice - cream cost\n            if(coins - cost >= 0) {\n                coins -= cost;\n                count++;\n            }\n        }\n\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxIceCream(vector<int>& costs, int coins) {\n        int n=costs.size();\n\n        sort(costs.begin(),costs.end());\n        \n        int i=0;\n        for(;i<n && coins>=costs[i];i++){\n            coins-=costs[i];\n        }\n        \n        return i;\n    }\n};"
    },
    {
        "title": "Lowest Common Ancestor of Deepest Leaves",
        "algo_input": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.\n\nRecall that:\n\n\n\tThe node of a binary tree is a leaf if and only if it has no children\n\tThe depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.\n\tThe lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\n\nExample 2:\n\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree, and it's the lca of itself.\n\n\nExample 3:\n\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 1000].\n\t0 &lt;= Node.val &lt;= 1000\n\tThe values of the nodes in the tree are unique.\n\n\n&nbsp;\nNote: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/\n",
        "solution_py": "class Solution:\n    def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n\n        self.max_lvl = (0,[])\n        self.pathes = {}\n        def rec(root,parent,lvl):\n            if not root:\n                return\n            if lvl > self.max_lvl[0]:\n                self.max_lvl = (lvl,[root])\n            elif lvl == self.max_lvl[0]:\n                self.max_lvl = (lvl,self.max_lvl[1]+[root])\n            self.pathes[root] = parent\n            rec(root.left,root,lvl+1)\n            rec(root.right,root,lvl+1)\n        rec(root,None,0)\n        print(self.max_lvl)\n        # for key in self.pathes:\n        # if key!=None and self.pathes[key]!=None:\n        # print(key.val,\"-\",self.pathes[key].val)\n        if len(self.max_lvl[1]) < 2:\n            return self.max_lvl[1][0]\n        parent = self.max_lvl[1]\n        while len(parent) > 1:\n            temp = set()\n            for p in parent:\n                temp.add(self.pathes.get(p,None))\n            parent = temp\n        return parent.pop()",
        "solution_js": "var lcaDeepestLeaves = function(root) {\n    if(!root) return root;\n    // keep track of max depth if node have both deepest node\n    let md = 0, ans = null;\n    const compute = (r = root, d = 0) => {\n        if(!r) {\n            md = Math.max(md, d);\n            return d;\n        }\n\n        const ld = compute(r.left, d + 1);\n        const rd = compute(r.right, d + 1);\n\n        if(ld == rd && ld == md) {\n            ans = r;\n        }\n\n        return Math.max(ld, rd);\n    }\n    compute();\n    return ans;\n};",
        "solution_java": "class Solution {\n    public TreeNode lcaDeepestLeaves(TreeNode root) {\n        if (root.left == null && root.right == null) return root;\n        int depth = findDepth(root);\n        Queue<TreeNode> q = new LinkedList<>();\n        q.offer(root);\n        int count = 0;\n        while (!q.isEmpty()) {\n            int size = q.size();\n            count++;\n            if (count == depth) {\n                break;\n            }\n            for (int i = 0; i < size; i++) {\n                TreeNode cur = q.poll();\n                if (cur.left != null) q.offer(cur.left);\n                if (cur.right != null) q.offer(cur.right);\n            }\n        }\n        Set<Integer> set = new HashSet<>();\n        while (!q.isEmpty()) {\n            set.add(q.poll().val);\n        }\n        return find(root, set);\n    }\n\n    public int findDepth(TreeNode root) {\n        if (root == null) return 0;\n        int left = findDepth(root.left);\n        int right = findDepth(root.right);\n        return 1 + Math.max(left, right);\n    }\n\n    public TreeNode find(TreeNode root, Set<Integer> set) {\n        if (root == null) return root;\n        if (set.contains(root.val)) return root;\n        TreeNode left = find(root.left, set);\n        TreeNode right = find(root.right, set);\n        if (left != null && right != null) return root;\n        else if (left != null) return left;\n        else if (right != null) return right;\n        else return null;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    stack<TreeNode *>st;\n    \n    vector<TreeNode * >vec;\n    int mx = INT_MIN;\n    \n    void ch(TreeNode * root, int h){\n        if(!root) return ;\n        ch(root->left, h+1);\n        ch(root->right, h+1);\n        \n        if(h==mx){\n            vec.push_back(root);\n        }\n        else if(h>mx){\n            vec.clear();\n            vec.push_back(root);\n            mx = h;\n        }\n    }\n    \n    bool uf = 0;\n    \n    void check(TreeNode * root, TreeNode * it){\n        \n        if(!root or uf) return ;\n        \n        st.push(root);\n        \n        if(root->val == it->val){\n            uf = 1;\n            return ;\n        }\n        \n        check(root->left, it);\n        check(root->right, it);\n        \n        if(!uf)\n            st.pop();\n    }\n    \n    TreeNode* lcaDeepestLeaves(TreeNode* root) {\n        vec.clear();\n        ch(root, 0);\n        vector<vector<TreeNode *>>ans;\n        ans.clear();\n        int mnx = INT_MAX;\n        for(auto it:vec){\n            uf = 0;\n            check(root, it);\n            vector<TreeNode *>temp;\n            \n            while(!st.empty()){\n                temp.push_back(st.top());\n                st.pop();\n            }\n            reverse(temp.begin(), temp.end());\n            ans.push_back(temp);\n            int p = temp.size();\n            mnx = min(mnx, p);\n        }\n        \n        TreeNode * rt = new TreeNode(0);\n        if(ans.size() == 1){\n            return ans[0][ans[0].size()-1];\n        }\n        bool lb = 0;\n        \n        \n        for(int j=0; j<mnx; j++){\n            for(int i=0; i<ans.size()-1; i++){\n                \n                if(ans[i][j]==ans[i+1][j]){\n                    continue;\n                }\n                else{\n                    rt = ans[i][j-1];\n                    lb = 1;\n                    break;\n                }\n            }\n            if(lb) break;\n        }\n        \n        return rt;\n        \n    }\n};"
    },
    {
        "title": "Maximum Average Pass Ratio",
        "algo_input": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.\n\nYou are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.\n\nThe pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.\n\nReturn the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: classes = [[1,2],[3,5],[2,2]], extraStudents = 2\nOutput: 0.78333\nExplanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\n\n\nExample 2:\n\nInput: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4\nOutput: 0.53485\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= classes.length &lt;= 105\n\tclasses[i].length == 2\n\t1 &lt;= passi &lt;= totali &lt;= 105\n\t1 &lt;= extraStudents &lt;= 105\n\n",
        "solution_py": "class Solution:\n\tdef maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact  for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount)  # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact  for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n",
        "solution_js": "/**\n * @param {number[][]} classes\n * @param {number} extraStudents\n * @return {number}\n */\nclass MaxHeap {\n    constructor() {\n        this.heap = [];\n    }\n\n    push(value) {\n        this.heap.push(value);\n        this.heapifyUp(this.heap.length - 1);\n    }\n\n    pop() {\n        if (this.heap.length === 0) {\n            return null;\n        }\n        if (this.heap.length === 1) {\n            return this.heap.pop();\n        }\n\n        const top = this.heap[0];\n        this.heap[0] = this.heap.pop();\n        this.heapifyDown(0);\n\n        return top;\n    }\n\n    heapifyUp(index) {\n        while (index > 0) {\n            const parent = Math.floor((index - 1) / 2);\n            if (this.heap[parent][0] < this.heap[index][0]) {\n                [this.heap[parent], this.heap[index]] = [this.heap[index], this.heap[parent]];\n                index = parent;\n            } else {\n                break;\n            }\n        }\n    }\n\n    heapifyDown(index) {\n        const n = this.heap.length;\n        while (true) {\n            let largest = index;\n            const left = 2 * index + 1;\n            const right = 2 * index + 2;\n\n            if (left < n && this.heap[left][0] > this.heap[largest][0]) {\n                largest = left;\n            }\n            if (right < n && this.heap[right][0] > this.heap[largest][0]) {\n                largest = right;\n            }\n\n            if (largest !== index) {\n                [this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];\n                index = largest;\n            } else {\n                break;\n            }\n        }\n    }\n\n    size() {\n        return this.heap.length;\n    }\n}\n\nvar maxAverageRatio = function(classes, extraStudents) {\n    const n = classes.length;\n\n    // Helper function to calculate pass ratio increase\n    const passRatioIncrease = (pass, total) => (pass + 1) / (total + 1) - pass / total;\n\n    // Initialize max heap to keep track of classes with maximum improvement\n    const maxHeap = new MaxHeap();\n\n    for (let j = 0; j < n; j++) {\n        const [pass, total] = classes[j];\n        if (pass !== total) {\n            const increase = passRatioIncrease(pass, total);\n            maxHeap.push([increase, j]);\n        }\n    }\n\n    let totalPassRatio = 0;\n\n    for (let j = 0; j < n; j++) {\n        totalPassRatio += classes[j][0] / classes[j][1];\n    }\n\n    for (let i = 0; i < extraStudents; i++) {\n        if (maxHeap.size() === 0) {\n            break; // No more classes to consider\n        }\n\n        const [increase, maxIndex] = maxHeap.pop();\n        const [pass, total] = classes[maxIndex];\n        const newPass = pass + 1;\n        const newTotal = total + 1;\n        const newIncrease = passRatioIncrease(newPass, newTotal);\n        const newAvg = (totalPassRatio - (pass / total)) + (newPass / newTotal);\n\n        if (newAvg <= totalPassRatio) {\n            break; // No further improvement possible\n        }\n\n        totalPassRatio = newAvg;\n        classes[maxIndex][0]++;\n        classes[maxIndex][1]++;\n        maxHeap.push([newIncrease, maxIndex]);\n    }\n\n    return totalPassRatio / n;\n};",
        "solution_java": "class Solution {\n    public double maxAverageRatio(int[][] classes, int extraStudents) {\n        PriorityQueue<double[]> pq = new PriorityQueue<>(new Comparator<double[]>(){\n            public int compare(double[] a, double[] b){\n                double adiff = (a[0]+1)/(a[1]+1) - (a[0]/a[1]);\n                double bdiff = (b[0]+1)/(b[1]+1) - (b[0]/b[1]);\n                if(adiff==bdiff) return 0;\n                return adiff>bdiff? -1:1;\n            }\n        });\n\n        for(int[] c:classes) pq.add(new double[]{c[0],c[1]});\n\n        for(int i =0;i<extraStudents;i++){\n            double[] curr = pq.poll();\n            pq.add(new double[]{curr[0]+1,curr[1]+1});\n        }\n\n        double sum = 0;\n        while(!pq.isEmpty()){\n            double[] curr = pq.poll();\n            sum+=curr[0]/curr[1];\n        }\n\n        return sum/classes.length;\n    }\n}",
        "solution_c": "struct cmp{\n    bool operator()(pair<int,int> a, pair<int,int> b){\n        double ad = (a.first+1)/(double)(a.second+1) - (a.first)/(double)a.second;\n        double bd = (b.first+1)/(double)(b.second+1) - (b.first)/(double)b.second;\n        return ad < bd;\n    }\n};\n\nclass Solution {\npublic:\n    double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {\n        double acc = 0;\n        priority_queue<pair<int,int>, vector<pair<int,int>>, cmp> que;\n        for(vector<int> i: classes)\n            que.push(make_pair(i[0],i[1]));\n        while(extraStudents--){\n            pair<int,int> cur = que.top(); que.pop();\n            cur.first++, cur.second++;\n            que.push(cur);\n        }\n        while(!que.empty()){\n            pair<int,int> cur = que.top(); que.pop();\n            acc += cur.first / (double) cur.second;\n        }\n        return acc / (double) classes.size();\n    }\n};"
    },
    {
        "title": "Domino and Tromino Tiling",
        "algo_input": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.\n\nGiven an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.\n\nIn a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are show above.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def numTilings(self, n):\n        dp = [1, 2, 5] + [0] * n\n        for i in range(3, n):\n            dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007\n        return dp[n - 1]",
        "solution_js": "var numTilings = function(n) {\n    let mod = 10 ** 9 + 7;\n    let len = 4;\n    let ways = new Array(len).fill(0);\n\n    // base cases\n    ways[0] = 1;\n    ways[1] = 1;\n    ways[2] = 2;\n\n    // already calculated above\n    if (n < len - 1) {\n        return ways[n];\n    }\n\n    // use % len to circulate values inside our array\n    for (var i = len - 1; i <= n;i++) {\n        ways[i % len] = (\n            ways[(len + i - 1) % len] * 2\n            +\n            ways[(len + i - 3) % len]\n        ) % mod;\n    }\n\n    return ways[(i - 1) % len];\n};",
        "solution_java": "class Solution {\n    public int numTilings(int n) {\n        long[] dp = new long[n + 3]; dp[0] = 1; dp[1] = 2; dp[2] = 5;\n        for (int i = 3; i < n; i ++) {\n            dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007;\n        }\n        return (int)dp[n - 1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numTilings(int n) {\n        long dp[n+1];\n        dp[0]=1;\n        for(int i=1; i<=n; i++){\n            if(i<3)\n                dp[i]=i;\n            else\n                dp[i] = (dp[i-1]*2+dp[i-3])%1000000007;\n        }\n        return (int)dp[n];\n    }\n};"
    },
    {
        "title": "Largest Number At Least Twice of Others",
        "algo_input": "You are given an integer array nums where the largest integer is unique.\n\nDetermine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,6,1,0]\nOutput: 1\nExplanation: 6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: -1\nExplanation: 4 is less than twice the value of 3, so we return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 50\n\t0 &lt;= nums[i] &lt;= 100\n\tThe largest element in nums is unique.\n\n",
        "solution_py": "class Solution:\n    def dominantIndex(self, nums: List[int]) -> int:\n        if len(nums) is 1:\n            return 0\n        dom = max(nums)\n        i = nums.index(dom)\n        nums.remove(dom)\n        if max(nums) * 2 <= dom:\n            return i\n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar dominantIndex = function(nums) {\n  let first = -Infinity;\n  let second = -Infinity;\n  let ans = 0;\n  for (let i = 0; i < nums.length; i++) {\n    if (nums[i] > first) {\n      second = first;\n      first = nums[i];\n      ans = i;\n    } else if (nums[i] > second) {\n      second = nums[i];\n    }\n  }\n  return first >= second * 2 ? ans : -1;\n};",
        "solution_java": "class Solution {\n    public int dominantIndex(int[] nums) {\n        if(nums == null || nums.length == 0){\n            return -1;\n        }\n        \n        if(nums.length == 1){\n            return 0;\n        }\n        int max = Integer.MIN_VALUE + 1;\n        int secondMax = Integer.MIN_VALUE;\n        int index = 0;\n        \n        for(int i = 0; i < nums.length; i++){\n            if(nums[i] > max){\n                secondMax = max;\n                max = nums[i];\n                index = i;\n            } else if(nums[i] != max && nums[i] > secondMax){\n                secondMax = nums[i];\n            }\n        }\n        if(secondMax * 2 <= max){\n            return index;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dominantIndex(vector<int>& nums) {\n        if(nums.size() < 2){\n            return nums.size()-1;\n        }\n        int max1 = INT_MIN;\n        int max2 = INT_MIN;\n        int result = -1;\n        for(int i=0;i<nums.size();i++){\n            if(nums[i] > max1){\n                result = i;\n                max2 = max1;\n                max1 = nums[i];\n            }else if(nums[i] > max2){\n                max2 = nums[i];\n            }\n        }\n        return max1 >= 2*max2 ? result : -1;\n    }\n};"
    },
    {
        "title": "First Letter to Appear Twice",
        "algo_input": "Given a string s consisting of lowercase English letters, return the first letter to appear twice.\n\nNote:\n\n\n\tA letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.\n\ts will contain at least one letter that appears twice.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"abccbaacz\"\nOutput: \"c\"\nExplanation:\nThe letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.\n\n\nExample 2:\n\nInput: s = \"abcdd\"\nOutput: \"d\"\nExplanation:\nThe only letter that appears twice is 'd' so we return 'd'.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 100\n\ts consists of lowercase English letters.\n\ts has at least one repeated letter.\n\n",
        "solution_py": "class Solution:\n    def repeatedCharacter(self, s: str) -> str:\n        occurences = defaultdict(int)\n        for char in s:\n            occurences[char] += 1\n            if occurences[char] == 2:\n                return char",
        "solution_js": " var repeatedCharacter = function(s) {\n    const m = {};\n    \n    for(let i of s) {\n        if(i in m) {\n            m[i]++\n        } else {\n            m[i] = 1\n        }\n        \n        if(m[i] == 2) {\n            return i\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public char repeatedCharacter(String s) {\n        HashSet<Character> hset = new HashSet<>();\n        for(char ch:s.toCharArray())\n        {\n            if(hset.contains(ch))\n                return ch;\n            else\n                hset.add(ch);\n        }\n        return ' ';\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    char repeatedCharacter(string s)\n    {\n        unordered_map<char, int> mp; //for storing occurrences of char\n\n        char ans;\n        for(auto it:s)\n        {\n            if(mp.find(it) != mp.end()) //any char which comes twice first will be the ans;\n            {\n                ans = it;\n                break;\n            }\n            mp[it]++; //increase the count of char\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Check If It Is a Good Array",
        "algo_input": "Given an array nums of&nbsp;positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers.&nbsp;The array is said to be&nbsp;good&nbsp;if you can obtain a sum of&nbsp;1&nbsp;from the array by any possible subset and multiplicand.\n\nReturn&nbsp;True&nbsp;if the array is good&nbsp;otherwise&nbsp;return&nbsp;False.\n\n&nbsp;\nExample 1:\n\nInput: nums = [12,5,7,23]\nOutput: true\nExplanation: Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1\n\n\nExample 2:\n\nInput: nums = [29,6,10]\nOutput: true\nExplanation: Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1\n\n\nExample 3:\n\nInput: nums = [3,6]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 10^5\n\t1 &lt;= nums[i] &lt;= 10^9\n\n",
        "solution_py": "class Solution:\n    def isGoodArray(self, nums: List[int]) -> bool:\n        def gcd(a,b):\n            while a:\n                a, b = b%a, a\n            return b\n        return reduce(gcd,nums)==1",
        "solution_js": "var isGoodArray = function(nums) {\n    let gcd = nums[0]\n\n    for(let n of nums){while(n){[gcd, n] = [n, gcd % n]}}\n\n    return (gcd === 1)\n};",
        "solution_java": "class Solution {\n    public boolean isGoodArray(int[] nums) {\n        int gcd = nums[0];\n        for(int i =1; i<nums.length; i++){\n           gcd = GCD(gcd, nums[i]);\n            if (gcd==1)\n                return true;\n        }\n        return gcd ==1;\n        \n    }\n    int GCD(int a, int b){\n        if(b==0){\n            return a;\n        }\n        else{\n            return GCD(b, a%b);\n        }\n            \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isGoodArray(vector<int>& nums) {\n        int gcd=0;\n        for(int i=0; i<nums.size(); i++){\n            gcd=__gcd(gcd,nums[i]);\n        }return gcd==1;\n    }\n};"
    },
    {
        "title": "Climbing Stairs",
        "algo_input": "You are climbing a staircase. It takes n steps to reach the top.\n\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 2\nExplanation: There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n\n\nExample 2:\n\nInput: n = 3\nOutput: 3\nExplanation: There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 45\n\n",
        "solution_py": "class Solution(object):\n    def climbStairs(self, n):\n        \"\"\"\n        :type n: int\n        :rtype: int\n        \"\"\"\n        memo ={}\n        memo[1] = 1\n        memo[2] = 2\n        \n        def climb(n):\n            if n in memo: # if the recurssion already done before first take a look-up in the look-up table\n                return memo[n]\n            else:   # Store the recurssion function in the look-up table and reuturn the stored look-up table function\n                memo[n] =  climb(n-1) + climb(n-2)\n                return memo[n]\n        \n        return climb(n)",
        "solution_js": "/*\nDP\n\ndp[i] represents the total number of different ways to take i steps\nSo, we want to get dp[n].\ndp[n] = dp[n-1] + dp[n-2] because we can either take 1 or 2 steps.\n\nWe have two base cases: dp[1] = 1 and dp[2] = 2 because\nthere is one way to take 1 step and there are two ways to take 2 steps (1 step + 1 step OR 2 step)\n*/\nvar climbStairs = function(n) {\n    let dp = new Array(n + 1);\n    dp[1] = 1, dp[2] = 2;\n    for (let i = 3; i <= n; i++) {\n        dp[i] = dp[i-1] + dp[i-2];\n    }\n    return dp[n];\n    // T.C: O(N)\n    // S.C: O(N)\n};",
        "solution_java": "class Solution {\n    public int climbStairs(int n) {\n        int[] memo = new int[n + 1];\n        return calculateWays(n, memo);\n    }\n    \n    private int calculateWays(int n, int[] memo) {\n        if (n == 1 || n == 2) {\n            return n;\n        }\n        \n        if (memo[n] != 0) {\n            return memo[n];\n        }\n        \n        memo[n] = calculateWays(n - 1, memo) + calculateWays(n - 2, memo);\n        return memo[n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int climbStairs(int n) {\n        if (n <= 2) return n;\n        int prev = 2, prev2 = 1, res;\n        for (int i = 3; i <= n; i++) {\n            res = prev + prev2;\n            prev2 = prev;\n            prev = res;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Paths with Max Score",
        "algo_input": "You are given a square board&nbsp;of characters. You can move on the board starting at the bottom right square marked with the character&nbsp;'S'.\n\nYou need&nbsp;to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character&nbsp;1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\n\nReturn a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.\n\nIn case there is no path, return&nbsp;[0, 0].\n\n&nbsp;\nExample 1:\nInput: board = [\"E23\",\"2X2\",\"12S\"]\nOutput: [7,1]\nExample 2:\nInput: board = [\"E12\",\"1X1\",\"21S\"]\nOutput: [4,2]\nExample 3:\nInput: board = [\"E11\",\"XXX\",\"11S\"]\nOutput: [0,0]\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= board.length == board[i].length &lt;= 100\n",
        "solution_py": "class Solution:\n    def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n\n        ## Basic information: height and width of board\n        h, w = len(board), len(board[0])\n\n        # ----------------------------------------------------------------------------\n\n        # Use pathon native cahce as memoization for DP\n        @cache\n        def visit(i, j):\n\n            if i == h-1 and j == w-1:\n                ## Base case:\n\n                # score for start coordinate = 0\n                # paht count for start coordinate = 1\n                return 0, 1\n\n            elif i >= w or j >= h or board[i][j] == 'X':\n\n                ## Base case:\n                # Out-of-boundary, or meet obstacle\n                return 0, 0\n\n            ## General case:\n            # update from three possible preivous moves from right, down, and diagonal\n\n            right_score, right_path_count = visit(i, j+1)\n            down_score, down_path_count = visit(i+1, j)\n            diag_score, diag_path_count = visit(i+1, j+1)\n\n            max_prevScore = max(right_score, down_score, diag_score)\n\n            cur_path_count = 0\n            cur_score = int(board[i][j]) if board[i][j] != \"E\" else 0\n\n            if right_score == max_prevScore : cur_path_count += right_path_count\n            if down_score == max_prevScore : cur_path_count += down_path_count\n            if diag_score == max_prevScore : cur_path_count += diag_path_count\n\n            return max_prevScore + cur_score, cur_path_count\n        # ----------------------------------------------------------------------------\n\n        ## Remark: Remember to take modulo by constant, this is defined by description\n        CONST = 10**9 + 7\n        maxScore, validPathCount = visit(0, 0)\n\n        return [maxScore % CONST, validPathCount % CONST] if validPathCount else [0, 0]",
        "solution_js": "var pathsWithMaxScore = function(board) {\n  let n = board.length, dp = Array(n + 1).fill(0).map(() => Array(n + 1).fill(0).map(() => [-Infinity, 0]));\n  let mod = 10 ** 9 + 7;\n  dp[n - 1][n - 1] = [0, 1]; // [max score, number of paths]\n\n  for (let i = n - 1; i >= 0; i--) {\n    for (let j = n - 1; j >= 0; j--) {\n      if (board[i][j] === 'X' || board[i][j] === 'S') continue;\n\n      let paths = [dp[i][j + 1], dp[i + 1][j + 1], dp[i + 1][j]];\n      for (let [maxScore, numPaths] of paths) {\n        if (dp[i][j][0] < maxScore) {\n          dp[i][j] = [maxScore, numPaths];\n        } else if (dp[i][j][0] === maxScore) {\n          dp[i][j][1] = (dp[i][j][1] + numPaths) % mod;\n        }\n      }\n      let score = board[i][j] === 'E' ? 0 : Number(board[i][j]);\n      dp[i][j][0] += score;\n    }\n  }\n  return dp[0][0][1] === 0 ? [0, 0] : dp[0][0];\n};",
        "solution_java": "class Solution {\n    public int[] pathsWithMaxScore(List<String> board) {\n        int M = (int)1e9+7;\n        int m = board.size();\n        int n = board.get(0).length();\n        int[][] dp = new int[m][n];\n        int[][] ways = new int[m][n];\n        ways[0][0]=1; // base case.\n        int[][] dirs = {{-1, 0}, {0, -1}, {-1, -1}}; // all 3 ways where we can travel.\n        for (int i=0;i<m;i++){\n            for (int j=0;j<n;j++){\n                if (board.get(i).charAt(j)=='X'){\n                    continue;\n                }\n                int cur = Character.isDigit(board.get(i).charAt(j))?board.get(i).charAt(j)-'0':0;\n                for (int[] d : dirs){\n                    int x = d[0]+i;\n                    int y = d[1]+j;\n                    if (x < 0 || y < 0 || ways[x][y] == 0){\n                        continue;\n                    }\n                    if (cur+dp[x][y]>dp[i][j]){\n                        dp[i][j]=cur+dp[x][y];\n                        ways[i][j]=0;\n                    }\n                    if (cur+dp[x][y]==dp[i][j]){\n                        ways[i][j]+=ways[x][y];\n                        ways[i][j]%=M;\n                    }\n                }\n            }\n        }\n        return new int[]{dp[m-1][n-1], ways[m-1][n-1]};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod=1e9+7;\n    map<pair<int,int>,pair<int,int>>h;\n    pair<int,int>solve(vector<string>&board,int i,int j,int n,int m)\n    {\n        //base case if you reach top left then 1 path hence return 1\n        if(i==0 && j==0)return {0,1};\n        //return 0 as no path is detected\n        if(i<0 || j<0 || i>=n || j>=m || board[i][j]=='X')return {INT_MIN,0};\n        //check if it is stored or not\n        if(h.find({i,j})!=h.end())return h[{i,j}];\n        int no=0,cnt=0;\n        if(board[i][j]!='S')no=board[i][j]-'0';\n        //top ,left ,top left\n        auto a=solve(board,i-1,j,n,m);\n        auto b=solve(board,i,j-1,n,m);\n        auto c=solve(board,i-1,j-1,n,m);\n        //maxi ans\n        int curr=(max(a.first,max(b.first,c.first)))%mod;\n        //if maxi ans == a , b , c then increament count of a ,b,c\n        if(curr==a.first)cnt+=a.second;\n        if(curr==b.first)cnt+=b.second;\n        if(curr==c.first)cnt+=c.second;\n        return h[{i,j}]={(curr+no)%mod,cnt%mod};\n    }\n    vector<int> pathsWithMaxScore(vector<string>& board) {\n        auto ans=solve(board,board.size()-1,board[0].size()-1,board.size(),board[0].size());\n        if(ans.first<0)return {0,0};\n        return {ans.first%mod,ans.second%mod};\n    }\n};"
    },
    {
        "title": "Path with Maximum Probability",
        "algo_input": "You are given an undirected weighted graph of&nbsp;n&nbsp;nodes (0-indexed), represented by an edge list where&nbsp;edges[i] = [a, b]&nbsp;is an undirected edge connecting the nodes&nbsp;a&nbsp;and&nbsp;b&nbsp;with a probability of success of traversing that edge&nbsp;succProb[i].\n\nGiven two nodes&nbsp;start&nbsp;and&nbsp;end, find the path with the maximum probability of success to go from&nbsp;start&nbsp;to&nbsp;end&nbsp;and return its success probability.\n\nIf there is no path from&nbsp;start&nbsp;to&nbsp;end, return&nbsp;0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput: 0.25000\nExplanation:&nbsp;There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\n\n\nExample 2:\n\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput: 0.30000\n\n\nExample 3:\n\n\n\nInput: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput: 0.00000\nExplanation:&nbsp;There is no path between 0 and 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 10^4\n\t0 &lt;= start, end &lt; n\n\tstart != end\n\t0 &lt;= a, b &lt; n\n\ta != b\n\t0 &lt;= succProb.length == edges.length &lt;= 2*10^4\n\t0 &lt;= succProb[i] &lt;= 1\n\tThere is at most one edge between every two nodes.\n\n",
        "solution_py": "class Solution(object):\n    def maxProbability(self, n, edges, succProb, start, end):\n        adj=[[] for i in range(n)]\n        dist=[sys.maxsize for i in range(n)]\n        heap=[]\n        c=0\n        for i,j in edges:\n            adj[i].append([j,succProb[c]])\n            adj[j].append([i,succProb[c]])\n            c+=1\n        heapq.heappush(heap,[-1.0,start])\n        dist[start]=1\n        while(heap):\n            prob,u=heapq.heappop(heap)\n            for v,w in adj[u]:\n                if(dist[v]>-abs(w*prob)):\n                    dist[v]=-abs(w*prob)\n                    heapq.heappush(heap,[dist[v],v])\n        if(sys.maxsize==dist[end]):\n            return 0.00000\n        else:\n            return -dist[end]",
        "solution_js": "var maxProbability = function(n, edges, succProb, start, end) {\n    const graph = new Map();\n    edges.forEach(([a, b], i) => {\n        const aSet = graph.get(a) || [];\n        const bSet = graph.get(b) || [];\n        aSet.push([b, succProb[i]]), bSet.push([a, succProb[i]]);\n        graph.set(a, aSet), graph.set(b, bSet);\n    });\n    \n    const dist = new Array(n).fill(0);\n    const vis  = new Array(n).fill(false);\n    \n    dist[start] = 1;\n    \n    const getMaxProbNode = () => {\n        let maxVal = 0, maxIndex = -1;\n        for(let i = 0; i < n; i++) {\n            if(maxVal < dist[i] && !vis[i]) {\n                maxVal = dist[i], maxIndex = i;\n            }\n        }\n        return maxIndex;\n    }\n    \n    for(let i = 0; i < n - 1; i++) {\n        const maxProbNode = getMaxProbNode();\n        vis[maxProbNode] = true;\n        \n        const adjacentNodes = graph.get(maxProbNode) || [];\n        const len = adjacentNodes.length;\n        for(let j = 0; j < len; j++) {\n            const [node, prob] = adjacentNodes[j];\n            if(!vis[node] && dist[node] < dist[maxProbNode] * prob) {\n                dist[node] = dist[maxProbNode] * prob;\n            }\n        }\n    }\n    \n    return dist[end];\n};",
        "solution_java": "class Pair{\n    int to;\n    double prob;\n    public Pair(int to,double prob){\n        this.to=to;\n        this.prob=prob;\n    }\n}\nclass Solution {\n    public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {\n        List<List<Pair>> adj=new ArrayList<>();\n        for(int i=0;i<n;i++){\n            adj.add(new ArrayList<Pair>());\n        }\n        for(int i=0;i<edges.length;i++){\n            adj.get(edges[i][0]).add(new Pair(edges[i][1],succProb[i]));\n            adj.get(edges[i][1]).add(new Pair(edges[i][0],succProb[i]));\n        }\n        //node,to node,probability\n        double probs[]=new double[n];\n        Arrays.fill(probs,0.0);\n        probs[start]=1.0;\n        PriorityQueue<Pair> pq=new PriorityQueue<>((p1,p2)->Double.compare(p2.prob,p1.prob));\n        pq.offer(new Pair(start,1.0));\n        while(!pq.isEmpty()){\n            Pair curr=pq.poll();\n            for(Pair x:adj.get(curr.to)){\n                if(((curr.prob)*(x.prob))>probs[x.to]){\n                    probs[x.to]=((curr.prob)*(x.prob));\n                    pq.offer(new Pair(x.to,probs[x.to]));\n\n                }\n                else{\n                    continue;\n                }\n            }\n        }\n        return probs[end];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start, int end) {\n        vector<vector<pair<int, double>>> graph(n);\n        for(int i = 0; i < edges.size(); ++i){\n            graph[edges[i][0]].push_back({edges[i][1], succProb[i]});\n            graph[edges[i][1]].push_back({edges[i][0], succProb[i]});\n        }\n        priority_queue<pair<double, int>> pq;\n        pq.push({1.0, start});\n        vector<bool> visited(n, false);\n        vector<double> values(n, 0.0);\n        values[start] = 1.0;\n        while(!pq.empty()){\n            double currValue = pq.top().first, currNode = pq.top().second;\n            pq.pop();\n            visited[currNode] = true;\n            for(int i = 0; i < graph[currNode].size(); ++i){\n                double weight = graph[currNode][i].second;\n                int nextNode = graph[currNode][i].first;\n                if(visited[nextNode] == false){\n                    double nextProb = currValue * weight;\n                    if(nextProb > values[nextNode])\n                        values[nextNode] = nextProb;\n                    pq.push({nextProb, nextNode});\n                }\n            }\n        }\n        return values[end] == 0.0 ? 0.0 : values[end];\n    }\n};"
    },
    {
        "title": "Array Partition",
        "algo_input": "Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,4,3,2]\nOutput: 4\nExplanation: All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -&gt; min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -&gt; min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -&gt; min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.\n\nExample 2:\n\nInput: nums = [6,2,6,5,1,2]\nOutput: 9\nExplanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\tnums.length == 2 * n\n\t-104 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution(object):\n    def arrayPairSum(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        \n        \n        nums = sorted(nums)\n        \n        summ = 0\n        for i in range(0,len(nums),2):\n            summ += min(nums[i],nums[i+1])\n        return summ",
        "solution_js": "var arrayPairSum = function(nums) {\n    nums.sort((a, b) => a - b);\n    let total = 0;\n    for (let i = 0; i < nums.length; i += 2) {\n        total += Math.min(nums[i], nums[i + 1]);\n    }\n    return total;\n};",
        "solution_java": "class Solution {\n    public int arrayPairSum(int[] nums) {\n        Arrays.sort(nums);\n        int sum = 0;\n        for(int i = 0; i < nums.length; i+=2){\n            sum += nums[i];\n        }\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int arrayPairSum(vector<int>& nums) {\n     int res=0;\n        sort(nums.begin(),nums.end());\n        for(int i=0;i<nums.size();i+=2){\n            res+=min(nums[i],nums[i+1]);  \n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Pascal's Triangle",
        "algo_input": "Given an integer numRows, return the first numRows of Pascal's triangle.\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n\n&nbsp;\nExample 1:\nInput: numRows = 5\nOutput: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\nExample 2:\nInput: numRows = 1\nOutput: [[1]]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= numRows &lt;= 30\n\n",
        "solution_py": "class Solution:\n    def generate(self, numRows: int) -> List[List[int]]:\n        if numRows == 1:\n            return [[1]]\n        if numRows == 2:\n            return [[1], [1, 1]]\n        ans = [[1], [1, 1]]\n        for x in range(1, numRows - 1):\n            tmp = [1]\n            for k in range(len(ans[x]) - 1):\n                tmp.append(ans[x][k] + ans[x][k + 1])\n            tmp.append(1)\n            ans.append(tmp)\n        return ans",
        "solution_js": "var generate = function(numRows) {\n    let ans = new Array(numRows)\n    for (let i = 0; i < numRows; i++) {\n        let row = new Uint32Array(i+1).fill(1),\n            mid = i >> 1\n        for (let j = 1; j <= mid; j++) {\n            let val = ans[i-1][j-1] + ans[i-1][j]\n            row[j] = val, row[row.length-j-1] = val\n        }\n        ans[i] = row\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> generate(int numRows) {\n        List<List<Integer>> list = new LinkedList();\n        list.add(Arrays.asList(1));\n        if(numRows == 1) return list;\n        list.add(Arrays.asList(1,1));\n        \n        for(int i = 1; i < numRows - 1; i++) {\n            List<Integer> temp = list.get(i);\n            List<Integer> temp2 = new ArrayList();\n            temp2.add(1);\n            for(int j = 0; j < temp.size() - 1; j++) {\n                temp2.add(temp.get(j) + temp.get(j+1));\n            }\n            temp2.add(1);\n            list.add(temp2);\n        }\n        \n        return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> generate(int numRows) {\n        vector<vector<int>> ans(numRows, vector<int>());\n        for(int i = 0; i<numRows; i++){\n            for(int j = 0; j <= i; j++){\n                if(j == 0 || j == i){\n                    ans[i].push_back(1);\n                }else{\n                    ans[i].push_back(ans[i-1][j-1] + ans[i-1][j]);\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Twin Sum of a Linked List",
        "algo_input": "In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 &lt;= i &lt;= (n / 2) - 1.\n\n\n\tFor example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.\n\n\nThe twin sum is defined as the sum of a node and its twin.\n\nGiven the head of a linked list with even length, return the maximum twin sum of the linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [5,4,2,1]\nOutput: 6\nExplanation:\nNodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6. \n\n\nExample 2:\n\nInput: head = [4,2,2,3]\nOutput: 7\nExplanation:\nThe nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7. \n\n\nExample 3:\n\nInput: head = [1,100000]\nOutput: 100001\nExplanation:\nThere is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is an even integer in the range [2, 105].\n\t1 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def pairSum(self, head: Optional[ListNode]) -> int:\n        nums = []\n        curr = head\n        while curr:\n            nums.append(curr.val)\n            curr = curr.next\n\n        N = len(nums)\n        res = 0\n        for i in range(N // 2):\n            res = max(res, nums[i] + nums[N - i - 1])\n        return res",
        "solution_js": "var pairSum = function(head) {\n    const arr = [];\n    let max = 0;\n    \n    while (head) {\n        arr.push(head.val);\n        head = head.next;\n    }\n    \n    for (let i = 0; i < arr.length / 2; i++) {\n        const sum = arr[i] + arr[arr.length - 1 - i]\n        max = Math.max(max, sum);\n    }\n    \n    return max;\n};",
        "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode() {}\n *     ListNode(int val) { this.val = val; }\n *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public int pairSum(ListNode head) {\n        if (head == null) {\n            return 0;\n        }\n        if (head.next == null) {\n            return head.val;\n        }\n        ListNode slow = head;\n        ListNode fast = head;\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        slow = reverse(slow);\n        fast = head;\n        int sum = Integer.MIN_VALUE;\n        while (slow != null) {\n            sum = Math.max(slow.val + fast.val, sum);\n            slow = slow.next;\n            fast = fast.next;\n        }\n        return sum;\n    }\n    \n    public ListNode reverse(ListNode node) {\n        if (node == null) {\n            return null;\n        }\n        ListNode current = node;\n        ListNode previous = null;\n        while (current != null) {\n            ListNode next = current.next;\n            current.next = previous;\n            previous = current;\n            current = next;\n        }\n        return previous;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* reverse(ListNode* head){\n        ListNode* prev=NULL,*curr=head,*nextstop;\n        while(curr){\n            nextstop=curr->next;\n            curr->next=prev;\n            prev=curr;\n            curr=nextstop;\n        }\n        return prev;\n    }\n    \n    ListNode* findMiddleNode(ListNode* head){\n        ListNode* slowptr=head,*fastptr=head->next;\n        while(fastptr&&fastptr->next){\n            slowptr=slowptr->next;\n            fastptr=fastptr->next->next;\n        }\n        return slowptr;\n    }\n    \n    int pairSum(ListNode* head) {\n        int ans=0;\n        \n        ListNode* midNode=findMiddleNode(head);\n        ListNode* head2=reverse(midNode->next);\n        \n        midNode->next=NULL;\n        \n        \n        ListNode* p1=head,*p2=head2;\n        while(p1&&p2){\n            ans=max(ans,p1->val+p2->val);\n            p1=p1->next;\n            p2=p2->next;\n        }\n        \n        midNode->next=reverse(head2);\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Check if There is a Valid Path in a Grid",
        "algo_input": "You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:\n\n\n\t1 which means a street connecting the left cell and the right cell.\n\t2 which means a street connecting the upper cell and the lower cell.\n\t3 which means a street connecting the left cell and the lower cell.\n\t4 which means a street connecting the right cell and the lower cell.\n\t5 which means a street connecting the left cell and the upper cell.\n\t6 which means a street connecting the right cell and the upper cell.\n\n\nYou will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.\n\nNotice that you are not allowed to change any street.\n\nReturn true if there is a valid path in the grid or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[2,4,3],[6,5,2]]\nOutput: true\nExplanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\n\n\nExample 2:\n\nInput: grid = [[1,2,1],[1,2,1]]\nOutput: false\nExplanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\n\n\nExample 3:\n\nInput: grid = [[1,1,2]]\nOutput: false\nExplanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 300\n\t1 &lt;= grid[i][j] &lt;= 6\n\n",
        "solution_py": "class Solution:\n    def hasValidPath(self, grid: List[List[int]]) -> bool:\n        r,c=len(grid),len(grid[0])\n        dic={\n            2:[(-1,0),(1,0)],\n            1:[(0,1),(0,-1)],\n            5:[(-1,0),(0,-1)],\n            3:[(1,0),(0,-1)],\n            6:[(0,1),(-1,0)],\n            4:[(0,1),(1,0)]\n            \n        }\n        q=collections.deque([(0,0)])\n        visit=set()\n        while q:\n            i,j=q.popleft()\n            visit.add((i,j))\n            if i==r-1 and j==c-1:\n                return True\n            for x,y in dic[grid[i][j]]:\n                nx=i+x\n                ny=j+y\n                if nx>=0 and nx<r and ny>=0 and ny<c and (nx,ny) not in visit:\n                    if (-x,-y) in dic[grid[nx][ny]]:\n                        q.append((nx,ny))\n        return False",
        "solution_js": "var hasValidPath = function(grid) {\n\tif (grid[0][0] === 5) return false;\n\n\tconst M = grid.length, N = grid[0].length;\n\tconst SEGMENTS = {\n\t\t1: {dirs: [[0,-1], [0,1]], adjs: [[1,4,6], [1,3,5]]},\n\t\t2: {dirs: [[-1,0], [1,0]], adjs: [[2,3,4], [2,5,6]]},\n\t\t3: {dirs: [[0,-1], [1,0]], adjs: [[1,4,6], [2,5,6]]},\n\t\t4: {dirs: [[0,1],  [1,0]], adjs: [[1,3,5], [2,5,6]]},\n\t\t5: {dirs: [[-1,0], [0,-1]],adjs: [[2,3,4], [1,4,6]]},\n\t\t6: {dirs: [[-1,0], [0,1]], adjs: [[2,3,4], [1,3,5]]}\n\t}\n\tlet path = Array.from({length: grid.length}, el => new Uint16Array(grid[0].length))\n\tlet y = 0, x = 0;\n\n\tfunction getNextSegment(segment, y, x) {\n\t\tlet dir = 0;\n\t\tlet ny = y + SEGMENTS[segment].dirs[dir][0];\n\t\tlet nx = x + SEGMENTS[segment].dirs[dir][1];\n\t\tif (ny < 0 || ny >= M || nx < 0 || nx >= N || path[ny][nx]) {\n\t\t\tdir = 1;\n\t\t\tny = y + SEGMENTS[segment].dirs[dir][0];\n\t\t\tnx = x + SEGMENTS[segment].dirs[dir][1];\n\t\t}\n\t\treturn {dir, ny, nx}\n\t}\n\n\tfunction isValid(y, x) {\n\t\tfor (let i = 0; i < M*N; i++) {\n\t\t\tif (y == M-1 && x == N-1) return true;\n\t\t\tpath[y][x] = i+1;\n\t\t\tlet cur = grid[y][x];\n\t\t\tlet next = getNextSegment(cur, y, x);\n\t\t\tif (next.ny >= M || next.nx >= N) return false;\n\t\t\tif (!SEGMENTS[cur].adjs[next.dir].includes(grid[next.ny][next.nx])) return false;\n\t\t\ty = next.ny;\n\t\t\tx = next.nx;\n\t\t}\n\t\treturn false\n\t}\n\n\tif (grid[0][0] !== 4) return isValid(y, x);\n\tpath[0][0] = 1;\n\treturn isValid(y, x+1) || isValid(y+1, x);\n};",
        "solution_java": "class Solution {\n    public boolean hasValidPath(int[][] grid) {\n        int m=grid.length, n=grid[0].length;\n        int[][] visited=new int[m][n];\n        return dfs(grid, 0, 0, m, n, visited);\n    }\n    public boolean dfs(int[][] grid, int i, int j, int m, int n, int[][] visited){\n        if(i==m-1 && j==n-1) return true;\n        if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==1) return false;\n        visited[i][j]=1;\n        if(grid[i][j]==1){\n            if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t    (j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5 ) && dfs(grid, i, j+1, m, n, visited) )) return true;\n        }else if(grid[i][j]==2){\n            if( (i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6) && dfs(grid, i+1, j, m, n, visited)) || \n                (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n        }else if(grid[i][j]==3){\n            if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t    (i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6) && dfs(grid, i+1, j, m, n, visited))) return true;\n        }else if(grid[i][j]==4){\n            if( ((i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6)) && dfs(grid, i+1, j, m, n, visited)) || \n\t\t\t    (j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5) && dfs(grid, i, j+1, m, n, visited))) return true;\n        }else if(grid[i][j]==5){\n            if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t    (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n        }else{\n            if( (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited)) || \n\t\t\t    (j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5) && dfs(grid, i, j+1, m, n, visited))) return true;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool hasValidPath(vector<vector<int>>& grid) \n    {\n        int m = grid.size();\n        int n = grid[0].size();\n        if(m==1 and n==1) return true;\n        // 2D - direction vector for all streets\n        // 0th based indexing 0 to 11\n        \n        // Let grid value g[i][j] = 4, means we need to follow \"street-4\" direction\n        // First index of street-4 direction = 2*(4-1) = 6\n        // Second index of street-4 direction = 2*(4-1)+1 = 7\n        // dir[6] = {0, 1}\n        // dir[7] = {1, 0}\n        vector<vector<int>>dir = {        // Indices   \n            {0,-1}, {0, 1}, // street 1  -->  0  1\n            {-1,0}, {1, 0}, // street 2  -->  2  3\n            {0,-1}, {1, 0}, // street 3  -->  4  5\n            {0, 1}, {1, 0}, // street 4  -->  6  7\n            {0,-1}, {-1,0}, // street 5  -->  8  9 \n            {0, 1}, {-1,0}  // street 6  -->  10  11\n        };\n\n        vector<vector<bool>>vis(m, vector<bool>(n, false));\n        queue<pair<int,int>>q;\n        \n        q.push({0, 0});\n        vis[0][0] = true;\n        \n        while (!q.empty()) \n        {\n            auto cur = q.front(); q.pop();\n\n            int r = cur.first;\n            int c = cur.second;\n            int val = grid[r][c] - 1; // grid values 1 to 6\n            \n            if(r==m-1 and c==n-1) return true;\n            \n            // 2 directions from every cell\n            for(int k=0;k<2;k++) // k = 0, k = 1\n            {\n                int idx = 2*val+k;   // get index\n                int nr = r + dir[idx][0];\n                int nc = c + dir[idx][1];\n                if (nr < 0 or nr >= m or nc < 0 or nc >= n or vis[nr][nc]==true) continue;\n                \n                //  for checking the back direction matches with current cell i.e forming path to next cell\n                for(int x=0;x<2;x++)\n                {\n                    int i = 2*(grid[nr][nc]-1)+x;   // get index\n                    if(r == nr+dir[i][0] and c == nc+dir[i][1]){\n                        vis[nr][nc] = true;\n                        q.push({nr, nc});\n                    }       \n                }\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Lemonade Change",
        "algo_input": "At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.\n\nNote that you do not have any change in hand at first.\n\nGiven an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: bills = [5,5,5,10,20]\nOutput: true\nExplanation: \nFrom the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.\n\n\nExample 2:\n\nInput: bills = [5,5,10,10,20]\nOutput: false\nExplanation: \nFrom the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= bills.length &lt;= 105\n\tbills[i] is either 5, 10, or 20.\n\n",
        "solution_py": "class Solution:\n    def lemonadeChange(self, bills: List[int]) -> bool:\n\n        change = {5:0,10:0}\n        for i in bills:\n            if i==5:\n                change[5]+=1\n            elif i==10:\n                if change[5]>0:\n                    change[5]-=1\n                    change[10]+=1\n                else:\n                    return False\n            else:\n                if (change[10]>0) & (change[5]>0):\n                    change[10]-=1\n                    change[5]-=1\n                elif change[5]>=3:\n                    change[5]-=3\n                else:\n                    return False\n        return True",
        "solution_js": " * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n   let cashLocker = {\n    \"5\": 0,\n    \"10\": 0,\n    \n  }\n  for (let i = 0; i < bills.length; i++) {\n    if (bills[i] === 5) {\n      cashLocker[\"5\"] += 1;\n    } else if (bills[i] === 10 && cashLocker[\"5\"] > 0) {\n      cashLocker[\"5\"] -= 1;\n      cashLocker[\"10\"] += 1;\n\n    } else if (bills[i] === 20 && cashLocker[\"5\"] >= 1 && cashLocker[\"10\"] >= 1) {\n      cashLocker[\"5\"] -= 1;\n      cashLocker[\"10\"] -= 1;\n     \n    } else if (bills[i] === 20 && cashLocker[\"5\"] >= 3) {\n\n      cashLocker[\"5\"] -= 3;\n     \n    } else {\n      return false;\n    }\n  }\n\n  return true;\n    \n};",
        "solution_java": "class Solution {\n    public boolean lemonadeChange(int[] bills) {\n        int count5 = 0, count10 = 0;\n        for(int p : bills){\n            if(p == 5){\n                count5++;\n            }\n            else if(p == 10){\n                if(count5 > 0){\n                    count5--;\n                    count10++;\n                }\n                else{\n                    return false;\n                }\n            }\n            else if(p == 20){\n                if(count5 > 0 && count10 > 0){\n                    count5--;\n                    count10--;\n                }\n                else if(count5 == 0){\n                    return false;\n                }\n                else if(count5<3){\n                    return false;\n                }\n                else{\n                    count5 -= 3;\n                }\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool lemonadeChange(vector<int>& bills) {\n        unordered_map<int, int> m;\n        \n        int change = 0;\n        for(int i = 0 ; i < bills.size(); i++)\n        {\n            m[bills[i]]++;\n            \n            if(bills[i] > 5)\n            {\n                change = bills[i] - 5;\n                \n                if(change == 5)\n                {\n                    if(m[5] > 0)\n                    {\n                        m[5]--;\n                    }\n                    else\n                    {\n                        return false;\n                    }\n                }\n                //change = 10\n                else\n                {\n                    if(m[10] > 0 and m[5] > 0)\n                    {\n                        m[10]--;\n                        m[5]--;\n                    }\n                    else if(m[5] >= 3)\n                    {\n                        m[5] -= 3;\n                    }\n                    else\n                    {\n                        return false;\n                    }\n                }\n            }\n        }\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Jump Game II",
        "algo_input": "Given an array of non-negative integers nums, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nYour goal is to reach the last index in the minimum number of jumps.\n\nYou can assume that you can always reach the last index.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,1,1,4]\nOutput: 2\nExplanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\nInput: nums = [2,3,0,1,4]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t0 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def jump(self, nums):\n        ans = l = r = 0\n\n        while r < len(nums) - 1:\n            farthestJump = 0\n\n            for i in range(l, r + 1):\n                farthestJump = max(farthestJump, i + nums[i])\n\n            l = r + 1\n            r = farthestJump\n            ans += 1\n\n        return ans",
        "solution_js": "**//Time Complexity : O(n),   Space Complexity: O(1)**\nvar jump = function(nums) {\n    var jump = 0;\n    var prev = 0;\n    var max = 0;\n    for (var i = 0; i < nums.length - 1; i++) {\n        // Keep track of the maximum jump\n        max = Math.max(max, i + nums[i]);\n        // When we get to the index where we had our previous maximum jump, we increase our jump...\n        if (i === prev) {\n            jump++;\n            prev = max;\n        }\n    }\n    return jump;\n};",
        "solution_java": "class Solution {\n\n    public int jump(int[] nums) {\n\n        int result = 0;\n\n        int L = 0;\n        int R = 0;\n\n        while (R < nums.length - 1) {\n\n            int localMaxRight = 0;\n\n            for (int i=L; i<=R; i++) {\n\n                localMaxRight = Math.max(i + nums[i], localMaxRight);\n            }\n\n            L = R + 1;\n            R = localMaxRight;\n            result++;\n        }\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int jump(vector<int>& nums) {\n        int step=0, jump_now;\n        int ans = 0, index=0, i, mx;\n        if(nums.size()==1) return ans;\n        while(index+step<nums.size()-1){\n            ans++;\n            step = nums[index];\n            if(index+step>=nums.size()-1) break;\n            mx = 0;\n            for(i=1; i<=step; i++){\n                if(i+nums[index+i]>mx){\n                    mx = i+nums[index+i];\n                    jump_now = i;\n                }\n            }\n            step = 0;\n            index += jump_now;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Final Value of Variable After Performing Operations",
        "algo_input": "There is a programming language with only four operations and one variable X:\n\n\n\t++X and X++ increments the value of the variable X by 1.\n\t--X and X-- decrements the value of the variable X by 1.\n\n\nInitially, the value of X is 0.\n\nGiven an array of strings operations containing a list of operations, return the final value of X after performing all the operations.\n\n&nbsp;\nExample 1:\n\nInput: operations = [\"--X\",\"X++\",\"X++\"]\nOutput: 1\nExplanation:&nbsp;The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X =  0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 =  0.\nX++: X is incremented by 1, X =  0 + 1 =  1.\n\n\nExample 2:\n\nInput: operations = [\"++X\",\"++X\",\"X++\"]\nOutput: 3\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.\n\n\nExample 3:\n\nInput: operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\nOutput: 0\nExplanation:&nbsp;The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= operations.length &lt;= 100\n\toperations[i] will be either \"++X\", \"X++\", \"--X\", or \"X--\".\n\n",
        "solution_py": "class Solution:\n    def finalValueAfterOperations(self, operations: List[str]) -> int:\n        x = 0\n        for o in operations:\n            if '+' in o:\n                x += 1\n            else:\n                x -= 1\n        return x",
        "solution_js": "var finalValueAfterOperations = function(operations) {\n    let count = 0;\n    for(let i of operations) {\n        if(i === 'X++' || i === '++X') count++;\n        else count--;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int finalValueAfterOperations(String[] operations) {\n        int val = 0;\n        for(int i = 0; i<operations.length; i++){\n            if(operations[i].charAt(1)=='+') val++;\n            else val--;\n        }\n        return val;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int finalValueAfterOperations(vector<string>& o,int c=0) {\n           for(auto &i:o) if(i==\"++X\" or i==\"X++\") c++; else c--;\n           return c;\n    }\n};"
    },
    {
        "title": "Minimum Difference Between Largest and Smallest Value in Three Moves",
        "algo_input": "You are given an integer array nums. In one move, you can choose one element of nums and change it by any value.\n\nReturn the minimum difference between the largest and smallest value of nums after performing at most three moves.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,3,2,4]\nOutput: 0\nExplanation: Change the array [5,3,2,4] to [2,2,2,2].\nThe difference between the maximum and minimum is 2-2 = 0.\n\n\nExample 2:\n\nInput: nums = [1,5,0,10,14]\nOutput: 1\nExplanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. \nThe difference between the maximum and minimum is 1-0 = 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minDifference(self, nums: List[int]) -> int:\n        if len(nums) <= 3:\n            return 0\n\n        nums.sort()\n        t1 = nums[-1] - nums[3]\n        t2 = nums[-4] - nums[0]\n        t3 = nums[-2] - nums[2]\n        t4 = nums[-3] - nums[1]\n\n        return min(t1,t2,t3,t4)",
        "solution_js": "var minDifference = function(nums) {\n    let len = nums.length;\n    if (len < 5) return 0;\n\n    nums.sort((a,b) => a-b)\n    \n    return Math.min(\n        \n    ( nums[len-1] - nums[3] ),  // 3 elements removed from start 0 from end\n    ( nums[len-4] - nums[0] ),  // 3 elements removed from end 0 from start\n    ( nums[len-2] - nums[2] ),  // 2 elements removed from start 1 from end\n    ( nums[len-3] - nums[1] ),  // 2 elements removed from end 1 from start\n   \n\n)\n    \n    \n    \n      \n};",
        "solution_java": "class Solution {\n    public int minDifference(int[] nums) {\n        // sort the nums\n        // to gain the mini difference\n        // we want to remove the three smallest or biggest \n        // 0 - 3\n        // 1 - 2\n        // 2 - 1\n        // 3 - 0\n        if(nums.length <= 4){\n            return 0;\n        }\n        \n        Arrays.sort(nums);\n        \n        int left = 0, right = 3;\n        \n        int res = Integer.MAX_VALUE;\n        while(left <= 3){\n            int mini = nums[left];\n            int max = nums[nums.length - right - 1];\n            res = Math.min(res, max - mini);\n            \n            left++;\n            right--;\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minDifference(vector<int>& nums) {\n\n        int n =nums.size();\n\n        sort( nums.begin(), nums.end());\n\n        if( n<5){\n            return 0;\n\n        }\n        else return min({nums[n-4]- nums[0],nums[n-3]- nums[1] ,nums[n-2]-nums[2], nums[n-1]-nums[3]});\n\n    }\n};"
    },
    {
        "title": "Maximum Nesting Depth of Two Valid Parentheses Strings",
        "algo_input": "A string is a valid parentheses string&nbsp;(denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and:\n\n\n\tIt is the empty string, or\n\tIt can be written as&nbsp;AB&nbsp;(A&nbsp;concatenated with&nbsp;B), where&nbsp;A&nbsp;and&nbsp;B&nbsp;are VPS's, or\n\tIt can be written as&nbsp;(A), where&nbsp;A&nbsp;is a VPS.\n\n\nWe can&nbsp;similarly define the nesting depth depth(S) of any VPS S as follows:\n\n\n\tdepth(\"\") = 0\n\tdepth(A + B) = max(depth(A), depth(B)), where A and B are VPS's\n\tdepth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\n\n\nFor example,&nbsp; \"\",&nbsp;\"()()\", and&nbsp;\"()(()())\"&nbsp;are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n\n&nbsp;\n\nGiven a VPS seq, split it into two disjoint subsequences A and B, such that&nbsp;A and B are VPS's (and&nbsp;A.length + B.length = seq.length).\n\nNow choose any such A and B such that&nbsp;max(depth(A), depth(B)) is the minimum possible value.\n\nReturn an answer array (of length seq.length) that encodes such a&nbsp;choice of A and B:&nbsp; answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.&nbsp; Note that even though multiple answers may exist, you may return any of them.\n\n&nbsp;\nExample 1:\n\nInput: seq = \"(()())\"\nOutput: [0,1,1,1,1,0]\n\n\nExample 2:\n\nInput: seq = \"()(())()\"\nOutput: [0,0,0,1,1,0,1,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= seq.size &lt;= 10000\n\n",
        "solution_py": "class Solution:\n    def maxDepthAfterSplit(self, seq: str) -> List[int]:\n        ans = []\n        last = 1\n        for i in seq:\n            if i == '(':\n                if last == 0: ans.append(1)\n                else:ans.append(0)\n            else:\n                ans.append(last)\n            last = (last + 1) % 2\n        return ans",
        "solution_js": "/**\n * @param {string} seq\n * @return {number[]}\n */\nvar maxDepthAfterSplit = function(seq) {\n    let arr = []\n    for(let i=0; i<seq.length; i++){\n        arr.push(seq[i] == \"(\" ? i & 1 : 1-i & 1)\n    }\n    return arr\n};",
        "solution_java": "class Solution {\n    public int[] maxDepthAfterSplit(String seq) {\n        int[] res = new int[seq.length()];\n        for(int i=0; i<seq.length(); i++){\n            res[i] = seq.charAt(i) == '(' ? i & 1 : 1-i & 1; \n        }\n        return res;\n    }\n}",
        "solution_c": "    class Solution {\npublic:\n    vector<int> maxDepthAfterSplit(string seq) {\n        //since we want the difference to be as low as possible so we will try to balance both A and B by trying to maintain the number of paranthesis as close as close as possible\n        vector<int> indexA, indexB, res(seq.length(), 0 );\n\t\t//initailly assuming all parenthesis belong to A so filling res with 0\n        int i = 0;\n        int addToA = 0, addToB = 0;\n        while(i < seq.length()){\n            if(seq[i] == '('){\n                if(addToA <= addToB){\n                    //adding depth to A when it's depth is lesser or equal to b\n                    indexA.push_back(i);\n                    addToA ++;\n                }else{\n                    indexB.push_back(i);\n                    addToB++;\n                }\n            }else{\n                // removing depth from string whose depth is maximum as we have to keep the difference minimum\n                if(addToA >= addToB){\n                    addToA--;\n                    indexA.push_back(i);\n                }else{\n                    indexB.push_back(i);\n                    addToB--;\n                }\n            }\n           i++;\n        }\n         for(i = 0; i < indexB.size(); i++){\n                res[indexB[i]] = 1;\n            }\n         return res;   \n    }\n};"
    },
    {
        "title": "Find Two Non-overlapping Sub-arrays Each With Target Sum",
        "algo_input": "You are given an array of integers arr and an integer target.\n\nYou have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.\n\nReturn the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,2,2,4,3], target = 3\nOutput: 2\nExplanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\n\n\nExample 2:\n\nInput: arr = [7,3,4,7], target = 7\nOutput: 2\nExplanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\n\n\nExample 3:\n\nInput: arr = [4,3,2,6,2,3,4], target = 6\nOutput: -1\nExplanation: We have only one sub-array of sum = 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i] &lt;= 1000\n\t1 &lt;= target &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def minSumOfLengths(self, arr: List[int], target: int) -> int:\n        l, windowSum, res = 0, 0, float('inf')\n        min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n        for r, num in enumerate(arr): # r:right pointer and index of num in arr\n            windowSum += num\n            while windowSum > target: \n\t\t\t# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target\n                windowSum -= arr[l]\n                l += 1\n\t\t\t# the case when we found a new target sub-array, i.e. current window\n            if windowSum == target:\n\t\t\t   # length of current window\n                curLen = r - l + 1\n\t\t\t\t# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window: \n\t\t\t\t# avoid overlap with cur window\n\t\t\t\t# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping\n\t\t\t\t# , if < res, update res.\n                res = min(res, curLen + min_till[l - 1])\n\t\t\t\t# Everytime we found a target window, update the min_till of current right end of the window, \n\t\t\t\t# for future use when sum up to new length of sum_of_two_subarray and update the res.\n                min_till[r] = min(curLen, min_till[r - 1])\n            else:\n\t\t\t# If windowSum < target: window with current arr[r] as right end does not have any target subarry, \n\t\t\t# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1. \n                min_till[r] = min_till[r - 1]\n        return res if res < float('inf') else -1\n\t\nTime = O(n): when sliding the window, left and right pointers traverse the array once.\nSpace = O(n): we use one additional list min_till[] to record min length of target subarray till index i.",
        "solution_js": "var minSumOfLengths = function(arr, target) {\n    let left=0;\n    let curr=0;\n    let res=Math.min(); // Math.min() without any args will be Infinite\n    const best=new Array(arr.length).fill(Math.min());\n    let bestSoFar=Math.min()\n\n    for(let i=0;i<arr.length;i++){\n        curr+=arr[i]\n        while(curr>target){\n            curr-=arr[left++]\n        }\n        if(curr===target){\n            if(left>0&&best[left-1]!==Math.min()){\n                res=Math.min(res,best[left-1]+i-left+1)\n            }\n            bestSoFar=Math.min(bestSoFar,i-left+1)\n        }\n        best[i]=bestSoFar;\n    }\n    return res===Math.min()?-1:res\n};",
        "solution_java": "class Solution {\n    public int minSumOfLengths(int[] arr, int target) { //this fits the case when there's negative number, kind like 560\n        if (arr == null || arr.length == 0) return 0;\n        Map<Integer, Integer> map = new HashMap<>(); //sum - index\n        map.put(0, -1);\n        int sum = 0;\n        for (int i = 0; i < arr.length; i++) { //record preSum and index\n            sum += arr[i];\n            map.put(sum, i);\n        }\n        sum = 0;\n        int size = arr.length + 1, res = arr.length + 1;//note if we set size as MAX_VALUE the line 16 may overflow\n        for (int i = 0; i < arr.length; i++) {\n            sum += arr[i];\n            if (map.containsKey(sum - target)) size = Math.min(size, i - map.get(sum - target)); //find the subarray from the previous index to current one\n            if (map.containsKey(sum + target)) res = Math.min(res, size + map.get(sum + target) - i); //from the current index to next one, this avoid overlap\n        }\n        return res == arr.length + 1 ? -1 : res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minSumOfLengths(vector<int>& arr, int target) {\n        int n=arr.size();\n        vector<int> prefix(n,INT_MAX);\n        vector<int> suffix(n,INT_MAX);\n        int sum=0;\n        int start=0;\n        for(int end=0;end<n;end++){\n            sum+=arr[end];\n            while(sum>target){\n                sum-=arr[start++];\n            }\n            if(sum==target){\n                prefix[end]=min(prefix[end-1>=0 ? end-1 : 0],end-start+1);\n            }\n            else{\n                prefix[end]=prefix[end-1>=0 ? end-1 : 0];\n            }\n        }\n\n        sum=0;\n        start=n-1;\n        for(int end=n-1;end>=0;end--){\n            sum+=arr[end];\n            while(sum>target){\n                sum-=arr[start--];\n            }\n            if(sum==target){\n                suffix[end]=min(suffix[end+1<n ? end+1 : n-1],start-end+1);\n            }\n            else{\n                suffix[end]=suffix[end+1<n ? end+1 : n-1];\n            }\n        }\n        int res=INT_MAX;\n        for(int i=0;i<n-1;i++){\n            if(prefix[i]==INT_MAX || suffix[i+1]==INT_MAX){\n                continue;\n            }\n            res=min(res,prefix[i]+suffix[i+1]);\n        }\n        return res==INT_MAX ? -1 : res;\n\n    }\n};"
    },
    {
        "title": "Smallest String With Swaps",
        "algo_input": "You are given a string s, and an array of pairs of indices in the string&nbsp;pairs&nbsp;where&nbsp;pairs[i] =&nbsp;[a, b]&nbsp;indicates 2 indices(0-indexed) of the string.\n\nYou can&nbsp;swap the characters at any pair of indices in the given&nbsp;pairs&nbsp;any number of times.\n\nReturn the&nbsp;lexicographically smallest string that s&nbsp;can be changed to after using the swaps.\n\n&nbsp;\nExample 1:\n\nInput: s = \"dcab\", pairs = [[0,3],[1,2]]\nOutput: \"bacd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"\n\n\nExample 2:\n\nInput: s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\nOutput: \"abcd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"\n\nExample 3:\n\nInput: s = \"cba\", pairs = [[0,1],[1,2]]\nOutput: \"abc\"\nExplaination: \nSwap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 10^5\n\t0 &lt;= pairs.length &lt;= 10^5\n\t0 &lt;= pairs[i][0], pairs[i][1] &lt;&nbsp;s.length\n\ts&nbsp;only contains lower case English letters.\n\n",
        "solution_py": "class DSU:\n    def __init__(self):\n        self.parentof = [-1 for _ in range(100001)]\n        self.rankof = [1 for _ in range(100001)]\n\n    def find(self,ele):\n        def recur(ele):\n            if self.parentof[ele]==-1: \n                return ele\n            par = recur(self.parentof[ele])\n            self.parentof[ele] = par\n            return par\n        return recur(ele)\n\n    def unify(self,ele1,ele2):\n        p1,p2 = self.find(ele1),self.find(ele2)\n        r1,r2 = self.rankof[p1],self.rankof[p2]\n\n        if p1==p2: return \n        if r1>r2:\n            self.parentof[p2] = p1\n        else:\n            self.parentof[p1]=p2\n            if r1==r2: self.rankof[p2]+=1\n\nclass Solution:\n    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n        dsu = DSU()\n        nodes = set()\n        smallest = [s[i] for i in range(len(s))]\n\n        for i,j in pairs:\n            dsu.unify(i,j)\n            nodes.add(i)\n            nodes.add(j)\n\n        groups = {}\n        for node in nodes:\n            par = dsu.find(node)\n            if par not in groups:\n                groups[par] = [node]\n            else:\n                groups[par].append(node)\n        \n        for group in groups.values():\n            letters,k = sorted([s[i] for i in group]),0\n            \n            for i in group:\n                smallest[i] = letters[k]\n                k+=1\n\n        return \"\".join(smallest)",
        "solution_js": "var smallestStringWithSwaps = function(s, pairs) {\n    const uf = new UnionFind(s.length);\n    pairs.forEach(([x,y]) => uf.union(x,y))\n    \n    const result = [];\n    for (const [root, charIndex] of Object.entries(uf.disjointSets())) {\n      let chars = charIndex.map(i => s[i])\n      chars.sort();\n      charIndex.forEach((charIndex, i) => result[charIndex] = chars[i])\n    }\n    \n    return result.join(\"\")\n};\n\nclass UnionFind {\n    constructor(len) {\n      this.roots = Array.from({length: len}).map((_, i) => i);\n      this.rank = Array.from({length: len}).fill(1);\n    }\n    \n    find(x) { \n      if (x == this.roots[x]) {\n        return x;\n       }\n      return this.roots[x] = this.find(this.roots[x])\n    }\n    \n    union(x, y) {\n        let rootX = this.find(x);\n        let rootY = this.find(y);\n        \n      if (this.rank[rootX] > this.rank[rootY]) {\n        this.roots[rootY] = rootX;\n       } else if (this.rank[rootX] < this.rank[rootY]) {\n           this.roots[rootX] = rootY;\n       } else { // ranks equal\n           this.roots[rootY] = rootX;\n           this.rank[rootX]++\n       }\n    }\n    \n    disjointSets() {\n        const ds = {};\n        for(let i = 0; i < this.roots.length; i++) {\n          let currentRoot = this.find(i);\n          if (currentRoot in ds) {\n              ds[currentRoot].push(i);\n          } else {\n              ds[currentRoot] = [i];\n          }\n        }\n        return ds;\n    }\n}",
        "solution_java": "class Solution {\n    int[]parent;\n    int[]rank;\n    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {\n        parent = new int[s.length()];\n        rank = new int[s.length()];\n        for(int i=0;i<parent.length;i++){\n            parent[i] = i;\n            rank[i] = 0;\n        }\n        \n        //Union of All Pairs who belongs to same set\n        for(List<Integer> l : pairs){\n            int i = l.get(0);\n            int j = l.get(1);\n            \n            int il = find(i);\n            int jl = find(j);\n            if(il != jl){\n                union(il,jl);\n            }\n        }\n        \n        //To get the Character in sorted order\n        PriorityQueue<Character>[]pq = new PriorityQueue[s.length()];\n        for(int i=0;i<pq.length;i++){\n            pq[i] = new PriorityQueue<>();\n        }\n        \n        for(int i=0;i<s.length();i++){\n            int il = find(i);\n            char ch = s.charAt(i);\n            pq[il].add(ch);\n        }\n        \n        StringBuilder sb = new StringBuilder();\n        for(int i=0;i<s.length();i++){\n            int il = find(i);\n            char ch = pq[il].remove();\n            sb.append(ch);\n        }\n        \n        return sb.toString();\n    }\n    \n    \n    int find(int x){\n        if(parent[x] == x){\n            return x;\n        }else{\n            parent[x] = find(parent[x]);\n            return parent[x];\n        }\n    }\n    void union(int x,int y){\n        if(rank[x] < rank[y]){\n            parent[x] = y;\n        }else if(rank[y] < rank[x]){\n            parent[y] = x;\n        }else{\n            parent[x] = y;\n            rank[y]++;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    vector<int> parent;\n\n    int findParent(int n)\n    {\n        if(parent[n] == n) return n;\n        return parent[n] = findParent(parent[n]);\n    }\n\n    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs)\n    {\n        map<int, set<int>> mp;\n        parent.resize(s.size());\n        string ans = s;\n\n        for(int i=0; i<s.length(); i++) parent[i] = i;\n\n        for(auto pair: pairs)\n        {\n            int p1 = findParent(pair[0]), p2 = findParent(pair[1]);\n            if(p1 != p2) parent[p2] = p1;\n        }\n\n        for(auto pair: pairs)\n        {\n            int p = findParent(pair[0]);\n            mp[p].insert(pair[0]);\n            mp[p].insert(pair[1]);\n        }\n\n        for(auto it: mp)\n        {\n            vector<char> part;\n            set<int> idx = it.second;\n\n            for(auto index: idx) part.push_back(s[index]);\n\n            sort(part.begin(), part.end());\n\n            auto index = idx.begin();\n            for(auto x: part) ans[*index] = x, ++index;\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Pivot Index",
        "algo_input": "Given an array of integers nums, calculate the pivot index of this array.\n\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\n\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\n\nReturn the leftmost pivot index. If no such index exists, return -1.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\n\n\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\n\nExample 3:\n\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-1000 &lt;= nums[i] &lt;= 1000\n\n\n&nbsp;\nNote: This question is the same as&nbsp;1991:&nbsp;https://leetcode.com/problems/find-the-middle-index-in-array/\n",
        "solution_py": "class Solution:\n    def pivotIndex(self, nums: List[int]) -> int:\n        right = sum(nums)\n        left = 0\n\n        for i in range(len(nums)):\n            right -= nums[i]\n            left += nums[i - 1] if i > 0 else 0\n\n            if right == left: return i\n\n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar pivotIndex = function(nums) {\n   //step 1\n    var tot=0;\n    for (let i = 0; i < nums.length; i++) {\n        tot+= nums[i];       \n    }\n    // Step 2\n    left = 0 ;\n    for (let j = 0; j < nums.length; j++) {\n        right = tot - nums[j] - left;\n        if (left == right){\n            return j\n        }\n        left += nums[j];\n    }\n    return -1\n};",
        "solution_java": "class Solution {\n    public int pivotIndex(int[] nums) {\n\n        int leftsum = 0;\n        int rightsum = 0;\n\n        for(int i =1; i< nums.length; i++) rightsum += nums[i];\n\n        if (leftsum == rightsum) return 0;\n\n        for(int i = 1 ; i < nums.length; i++){\n            leftsum += nums[i-1];\n            rightsum -= nums[i];\n\n            if(leftsum == rightsum) return i;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int pivotIndex(vector<int>& nums) {\n        int sum=0, leftSum=0;\n        for (int& n : nums){\n            sum += n;\n        }\n        for(int i=0; i<nums.size();i++){\n            if(leftSum == sum-leftSum-nums[i]){\n                return i;\n            }\n            leftSum += nums[i];\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Count Number of Rectangles Containing Each Point",
        "algo_input": "You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).\n\nThe ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi).\n\nReturn an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point.\n\nThe ith rectangle contains the jth point if 0 &lt;= xj &lt;= li and 0 &lt;= yj &lt;= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.\n\n&nbsp;\nExample 1:\n\nInput: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\nOutput: [2,1]\nExplanation: \nThe first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].\n\n\nExample 2:\n\nInput: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\nOutput: [1,3]\nExplanation:\nThe first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rectangles.length, points.length &lt;= 5 * 104\n\trectangles[i].length == points[j].length == 2\n\t1 &lt;= li, xj &lt;= 109\n\t1 &lt;= hi, yj &lt;= 100\n\tAll the rectangles are unique.\n\tAll the points are unique.\n\n",
        "solution_py": "class Solution:\n    def binarySearch(self, arr, target):\n        left, right = 0, len(arr)\n        ans = None\n        while left < right:\n            mid = left + ((right-left)//2)\n            if arr[mid] >= target:\n                # Potential answer found! Now try to minimize it iff possible.\n                ans = mid\n                right = mid\n            else:\n                left = mid + 1\n        return ans\n        \n    def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n        # Sort rectangles based on the lengths\n        rectangles.sort()  \n        # Group rectangles by their height in increasing order of their length\n        lengths = {}\n        for x,y in rectangles:\n            if y in lengths:\n                lengths[y].append(x)\n            else:\n                lengths[y] = [x]\n        \n        heights = sorted(list(lengths.keys()))\n        \n        count = [0] * len(points)\n        \n        for idx, point in enumerate(points):\n            x, y = point\n            # Get the  min height rectangle that would accommodate the y coordinate of current point.\n            minHeightRectIdx = self.binarySearch(heights, y)\n            if minHeightRectIdx is not None:\n                for h in heights[minHeightRectIdx:]:\n                    # Get the Min length rectangle that would accommodate the x coordinate of current point for all h height rectangles.\n                    minLenRectIdx = self.binarySearch(lengths[h], x)\n                    if minLenRectIdx is not None:\n                        count[idx] += len(lengths[h]) - minLenRectIdx\n        \n        return count",
        "solution_js": "var countRectangles = function(rectangles, points) {\n  let buckets = Array(101).fill(0).map(() => []);\n  for (let [x, y] of rectangles) {\n    buckets[y].push(x);\n  }\n  for (let i = 0; i < 101; i++) buckets[i].sort((a, b) => a - b);\n\n  let res = [];\n  for (let point of points) {\n    let sum = 0;\n    for (let j = point[1]; j < 101; j++) {\n      // lowest index >= point[0]\n      let index = lower_bound(buckets[j], point[0]);\n      sum += buckets[j].length - index;\n    }\n    res.push(sum);\n  }\n  return res;\n\n  function lower_bound(arr, targ) {\n    let low = 0, high = arr.length;\n    while (low < high) {\n      let mid = Math.floor((low + high) / 2);\n      if (arr[mid] >= targ) high = mid;\n      else low = mid + 1;\n    }\n    return low;\n  }\n};",
        "solution_java": "class Solution {\n    public int[] countRectangles(int[][] rectangles, int[][] points) {\n        int max = Integer.MIN_VALUE;\n\n        TreeMap<Integer, List<Integer>> rects = new TreeMap<>();\n        for(int[] rect : rectangles) {\n            if (!rects.containsKey(rect[1])) {\n                rects.put(rect[1], new ArrayList<Integer>());\n            }\n\n            rects.get(rect[1]).add(rect[0]);\n            max = Math.max(max, rect[1]);\n        }\n\n        for(int k : rects.keySet()) {\n            Collections.sort(rects.get(k));\n        }\n\n        int[] ans = new int[points.length];\n        for(int i = 0; i < points.length; i++) {\n            if (points[i][1] > max) {\n                continue;\n            }\n\n            int count = 0;\n\n            for(int key : rects.subMap(points[i][1], max + 1).keySet()) {\n                List<Integer> y = rects.get(key);\n\n                count += binarySearch(y, points[i][0]);\n            }\n\n            ans[i] = count;\n        }\n\n        return ans;\n    }\n\n    private int binarySearch(List<Integer> vals, int val) {\n        int lo = 0;\n        int hi = vals.size() - 1;\n        int id = -1;\n\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n\n            if (vals.get(mid) < val) {\n                lo = mid + 1;\n            } else {\n                id = mid;\n                hi = mid - 1;\n            }\n        }\n\n        if (id < 0) {\n            return 0;\n        }\n\n        return vals.size() - id;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {\n        \n        int i, count, ind, x, y, n = rectangles.size();\n        \n        vector<int> ans;\n        vector<vector<int>> heights(101);\n        \n        for(auto rect : rectangles)\n            heights[rect[1]].push_back(rect[0]);\n        \n        for(i=0;i<101;i++)\n            sort(heights[i].begin(), heights[i].end());\n        \n        for(auto point : points)\n        {\n            count = 0;\n            x = point[0];\n            y = point[1];\n            for(i=y;i<101;i++)\n            {\n                ind = lower_bound(heights[i].begin(), heights[i].end(), x) - heights[i].begin();\n                count += (heights[i].size() - ind);\n            }\n            ans.push_back(count);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Unique Binary Search Trees II",
        "algo_input": "Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n\n\nExample 2:\n\nInput: n = 1\nOutput: [[1]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 8\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n\n    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n        # define a sorted list of the numbers, for each num in that list , leftvalues\n# are left tree and right val are rightree, then for each number create a tree\n# assign the left and right to that root and append the root to the ans\n        nums = list(range(1,n+1))\n        def dfs(nums):\n            if not nums:\n                return [None]\n            ans = []\n            for i in range(len(nums)):\n                leftTrees = dfs(nums[:i])\n                rightTrees = dfs(nums[i+1:])\n\n                for l in leftTrees:\n                    for r in rightTrees:\n                        root = TreeNode(nums[i])\n                        root.left = l\n                        root.right = r\n                        ans.append(root)\n            return ans\n\n        return dfs(nums)",
        "solution_js": "var generateTrees = function(n) {\n    if(n <= 0){\n        return [];\n    }\n    return generateRec(1, n);\n\n};\n\nfunction generateRec(start, end){\n    let result = [];\n\n    if(start > end){\n        result.push(null);\n        return result;\n    }\n\n    for(let i = start; i <end+1; i++){\n        let left = generateRec(start, i-1);\n        let right = generateRec(i+1, end);\n\n        for(let l = 0; l < left.length; l++){\n            for(let r = 0; r < right.length; r++){\n                let root = new TreeNode(i,left[l], right[r]);\n                result.push(root);\n            }\n        }\n\n    }\n    return result;\n\n}",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public List<TreeNode> generateTrees(int n) {\n        return helper(1,n);\n    }\n    \n    public List<TreeNode> helper(int lo, int hi){\n        List<TreeNode> res=new ArrayList<>();\n        if(lo>hi){\n            res.add(null);\n            return res;\n        }\n        \n        \n        for(int i=lo;i<=hi;i++){\n            List<TreeNode> left=helper(lo,i-1);\n            List<TreeNode> right=helper(i+1,hi);\n            \n            for(TreeNode l:left){\n                for(TreeNode r:right){\n                    TreeNode head=new TreeNode(i);\n                    head.left=l;\n                    head.right=r;\n                    \n                    res.add(head);\n                }\n            }\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution \n{\n    public:\n    vector<TreeNode*> solve(int start, int end)\n    {\n        //base case\n        if(start>end){\n            return {NULL};\n        }\n        vector<TreeNode*> lChild, rChild, res;\n        //forming a tree, by keeping each node as root node\n        for(int i=start; i<=end; i++)\n        {\n            //don't create node here, bcz for each combination of subtree, node with new address has to be generated\n\n            //recursive call for left,right child, they will return vector of all possible subtrees\n            lChild = solve(start, i-1);\n            rChild = solve(i+1, end);\n            \n            //for each subtree returned by lChild, forming combination with each subtree returned by rChild\n            for(auto l: lChild)\n            {\n                for(auto r: rChild)\n                {\n                    //generating new node for each combination\n                    TreeNode* node = new TreeNode(i);\n                    //attaching left, right childs\n                    node->left = l;\n                    node->right = r;\n                    res.push_back(node);\n                }\n            }            \n        }\n        //returning all possible subtrees\n        return res;\n    }\n    vector<TreeNode*> generateTrees(int n) {\n        return solve(1, n);\n    }\n};"
    },
    {
        "title": "Design a Number Container System",
        "algo_input": "Design a number container system that can do the following:\n\n\n\tInsert or Replace a number at the given index in the system.\n\tReturn the smallest index for the given number in the system.\n\n\nImplement the NumberContainers class:\n\n\n\tNumberContainers() Initializes the number container system.\n\tvoid change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.\n\tint find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]\nOutput\n[null, -1, null, null, null, null, 1, null, 2]\n\nExplanation\nNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= index, number &lt;= 109\n\tAt most 105 calls will be made in total to change and find.\n\n",
        "solution_py": "class NumberContainers:\n    def __init__(self):\n        self.numbersByIndex = {}\n        self.numberIndexes = defaultdict(set)\n        self.numberIndexesHeap = defaultdict(list)\n\n    def change(self, index: int, number: int) -> None:\n        if index in self.numbersByIndex:\n            if number != self.numbersByIndex[index]:\n                self.numberIndexes[self.numbersByIndex[index]].remove(index)\n                self.numbersByIndex[index] = number\n                self.numberIndexes[number].add(index)\n                heappush(self.numberIndexesHeap[number], index)\n        else:\n            self.numbersByIndex[index] = number\n            self.numberIndexes[number].add(index)\n            heappush(self.numberIndexesHeap[number], index)\n\n    def find(self, number: int) -> int:\n        while self.numberIndexesHeap[number] and self.numberIndexesHeap[number][0] not in self.numberIndexes[number]:\n                heappop(self.numberIndexesHeap[number])  # make sure the smallest index in heap is still an index for number\n        return self.numberIndexesHeap[number][0] if self.numberIndexesHeap[number] else -1",
        "solution_js": "var NumberContainers = function() {\n    this.obj = {}\n    this.global = {}\n};\n\nNumberContainers.prototype.change = function(index, number) {\n\n    if(this.global[index])\n        {\n            for(var key in this.obj)\n            {\n               let ind = this.obj[key].indexOf(index)\n                if(ind != -1)\n                    {\n                         this.obj[key].splice(ind, 1);\n                        if(this.obj[number])\n                            this.obj[number].push(index);\n                        else\n                            this.obj[number] = [index];\n\n                        this.global[index]=1;\n                        return;\n                    }\n            }\n        }\n\n    if(this.obj[number])\n        this.obj[number].push(index);\n    else\n        this.obj[number] = [index];\n    this.global[index]=1;\n};\n\nNumberContainers.prototype.find = function(number) {\n    if(this.obj[number])\n        {\n            if(this.obj[number].length == 0)\n                return -1\n            else\n                return Math.min(...this.obj[number])\n        }\n    return -1;\n};",
        "solution_java": "class NumberContainers {\n    \n    Map<Integer,TreeSet<Integer>> map;\n    Map<Integer,Integer> m;\n    public NumberContainers() {\n        map=new HashMap<>();\n        m=new HashMap<>();\n        \n    }\n    public void change(int index, int number) {\n        m.put(index,number);\n        if(!map.containsKey(number)) map.put(number,new TreeSet<>());\n        map.get(number).add(index);\n    }\n    \n    public int find(int number) {\n        if(!map.containsKey(number)) return -1;\n        for(Integer a:map.get(number)){\n            if(m.get(a)==number) return a;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class NumberContainers {\npublic:\n    map<int, int> indexToNumber; // stores number corresponding to an index.\n    map<int, set<int>>numberToIndex; // stores all the indexes corresponding to a number.\n    NumberContainers() {}\n\n    void change(int index, int number) {\n\n        if (!indexToNumber.count(index)) { // if there is no number at the given index.\n            numberToIndex[number].insert(index); // store index corresponding to the given number\n            indexToNumber[index] = number; // store number corresponding to the index.\n        }\n        else { // Update both map.\n\n            int num = indexToNumber[index]; // number at given index currently.\n\n            // remove the index\n            numberToIndex[num].erase(index);\n            if (numberToIndex[num].empty()) numberToIndex.erase(num);\n\n            // insert the new number at the given index and store the index corresponding to that number.\n            numberToIndex[number].insert(index);\n            indexToNumber[index] = number;\n        }\n    }\n\n    int find(int number) {\n        if (!numberToIndex.count(number)) return -1;\n        // returning first element in the set as it will be the smallest index always.\n        return *numberToIndex[number].begin();\n    }\n};"
    },
    {
        "title": "Reconstruct Original Digits from English",
        "algo_input": "Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.\n\n&nbsp;\nExample 1:\nInput: s = \"owoztneoer\"\nOutput: \"012\"\nExample 2:\nInput: s = \"fviefuro\"\nOutput: \"45\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"].\n\ts is guaranteed to be valid.\n\n",
        "solution_py": "class Solution:\n    def originalDigits(self, s: str) -> str:\n        c = dict()\n        \n        c[0] = s.count(\"z\")\n        c[2] = s.count(\"w\")\n        c[4] = s.count(\"u\")\n        c[6] = s.count(\"x\")\n        c[8] = s.count(\"g\")\n        \n        c[3] = s.count(\"h\") - c[8]\n        c[5] = s.count(\"f\") - c[4]\n        c[7] = s.count(\"s\") - c[6]\n        \n        c[9] = s.count(\"i\") - (c[8] + c[5] + c[6])\n        c[1] = s.count(\"o\") - (c[0] + c[2] + c[4])\n        \n        c = sorted(c.items(), key = lambda x: x[0])\n        ans = \"\"\n        for k, v in c:\n            ans += (str(k) * v)\n        return ans",
        "solution_js": "/**\n * @param {string} s\n * @return {string}\n */\n \nvar originalDigits = function(s) {\n    const numberToWord = {\n        0: 'zero',\n        1: 'one',\n        2: 'two',\n        3: 'three',\n        4: 'four',\n        5: 'five',\n        6: 'six',\n        7: 'seven',\n        8: 'eight',\n        9: 'nine'\n    }\n    \n    const letterToDigits = {}\n    \n    for(const key in numberToWord) {\n        const currWord = numberToWord[key]\n        \n        for(const letter of currWord) {\n            if(!(letter in letterToDigits)) letterToDigits[letter] = new Set()\n            letterToDigits[letter].add(key)\n        }\n    }\n    \n    const inputFreqs = {}\n    \n    for(let i = 0; i < s.length; i++) {\n        const currChar = s[i]\n        \n        if(!(currChar in inputFreqs)) inputFreqs[currChar] = 0\n        inputFreqs[currChar]++\n    }\n    \n    const letters = Object.keys(inputFreqs)\n    \n    const res = dfs(letters[0])\n    \n    return [...res].sort().join('')\n    \n    function dfs(currLetter) {\n        if(!isValid(inputFreqs)) return null\n        if(getTotalRemaining(inputFreqs) === 0) return []\n        const possibleDigits = letterToDigits[currLetter]\n        \n        for(const digit of [...possibleDigits]) {\n            const wordRepresentation = numberToWord[digit]\n            \n            subtract(wordRepresentation)\n            \n            if(!isValid(inputFreqs)) {\n                addBack(wordRepresentation)\n                continue\n            }\n            \n            const nextLetter = getNext(inputFreqs)\n            const nextDigits = dfs(nextLetter)\n            \n            if(nextDigits !== null) return [digit] + nextDigits\n            \n            addBack(wordRepresentation)\n        }\n        \n        return null\n    }\n    \n    function isValid(inputFreqs) {\n        for(const key in inputFreqs) {\n            const count = inputFreqs[key]\n            \n            if(count < 0) return false\n        }\n        \n        return true\n    }\n    \n    function getTotalRemaining(inputFreqs) {\n        let sum = 0\n        \n        for(const key in inputFreqs) {\n            const count = inputFreqs[key]\n            \n            sum += count\n        }\n        \n        \n        return sum\n    }\n    \n    function subtract(word) {\n        for(const char of word) {\n            if(!(char in inputFreqs)) inputFreqs[char] = 0\n            inputFreqs[char]--\n        }\n    }\n    \n    \n    function addBack(word) {\n        for(const char of word) {\n            inputFreqs[char]++\n        }\n    }\n    \n    function getNext(inputFreqs) {\n        for(const key in inputFreqs) {\n            const count = inputFreqs[key]\n            \n            if(count > 0) return key\n        }\n        \n        return null\n    }\n};",
        "solution_java": "class Solution {\n\n    // First letter is unique after previous entries have been handled:\n    static final String[] UNIQUES = new String[] {\n        \"zero\", \"wto\", \"geiht\", \"xsi\", \"htree\",\n        \"seven\", \"rfou\", \"one\", \"vfie\", \"inne\"\n    };\n\n    // Values corresponding to order of uniqueness checks:\n    static final int[] VALS = new int[] { 0, 2, 8, 6, 3, 7, 4, 1, 5, 9 };\n    \n\t// Maps for checking uniqueness more conveniently:\n    static final Map<Integer, List<Integer>> ORDERED_FREQ_MAP;\n    static final Map<Integer, Integer> ORDERED_DIGIT_MAP;\n    \n    static {\n\t    // Initialize our ordered frequency map: 0-25 key to 0-25 values finishing the word:\n        final LinkedHashMap<Integer, List<Integer>> orderedFreqMap = new LinkedHashMap<>();\n\t\t// Also initialize a digit lookup map, e.g. 'g' becomes 6 maps to 8 for ei[g]ht:\n        final LinkedHashMap<Integer, Integer> orderedDigitMap = new LinkedHashMap<>();\n        for (int i = 0; i < 10; ++i) {\n            final char unique = UNIQUES[i].charAt(0);\n            final int ui = convert(unique);\n            orderedFreqMap.put(ui, converting(UNIQUES[i].substring(1).toCharArray()));\n            orderedDigitMap.put(ui, VALS[i]);\n        }\n\t\t// Let's make sure we aren't tempted to modify these since they're static.\n        ORDERED_FREQ_MAP = Collections.unmodifiableMap(orderedFreqMap);\n        ORDERED_DIGIT_MAP = Collections.unmodifiableMap(orderedDigitMap);\n    }\n\n    public String originalDigits(String s) {\n\t    // count frequencies of each letter in s:\n        final int[] freqs = new int[26];\n        for (int i = 0; i < s.length(); ++i) {\n            freqs[convert(s.charAt(i))]++;\n        }\n\t\t// Crate an array to store digit strings in order, e.g. '00000', '11, '2222222', etc.\n        final String[] strings = new String[10];\n\t\t// Iterate through uniqueness checks in order:\n        for (Map.Entry<Integer, List<Integer>> entry : ORDERED_FREQ_MAP.entrySet()) {\n            final int index = entry.getKey(); // unique letter in 0-25 form\n            final int value = ORDERED_DIGIT_MAP.get(index); // corresponding digit, e.g. 8 for 'g', 0 for 'z', etc.\n            final int count = freqs[index]; // frequency of unique letter = frequency of corresponding digit\n            if (count > 0) {\n\t\t\t    // update frequencies to remove the digit's word count times:\n                freqs[index] -= count;\n                for (int idx : entry.getValue()) {\n                    freqs[idx] -= count;\n                }\n\t\t\t\t// now create the digit string for the unique digit: the digit count times:\n                strings[value] = String.valueOf(value).repeat(count);\n            } else {\n\t\t\t    // count 0 - empty strring for this digit\n                strings[value] = \"\";\n            }\n        }\n\t\t// append the digit strings in order\n        final StringBuilder sb = new StringBuilder();\n        for (String str : strings) {\n            sb.append(str);\n        }\n\t\t// and we are done!\n        return sb.toString();\n    }\n\n    // Converts a character array into a list of 0-25 frequency values.\n    private static final List<Integer> converting(char... carr) {\n        final List<Integer> list = new ArrayList<>();\n        for (char ch : carr) {\n            list.add(convert(ch)); // converts each to 0-25\n        }\n        return Collections.unmodifiableList(list);\n    }\n\n    // Converts a-z to 0-26.  Bitwise AND with 31 gives a=1, z=26, so then subtract one.\n    private static final Integer convert(char ch) {\n        return (ch & 0x1f) - 1; // a->0, z->25\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    \n    vector<string> digits{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\"};\n    void fun(int x,string &ans,vector<int> &m){\n        for(int i = x;i<=9;i+=2){\n            string t = digits[i];\n            if(t.length() == 3){\n                if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0){\n                    int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a']});\n                    m[t[0]-'a'] -= min_o;\n                    m[t[1]-'a'] -= min_o;\n                    m[t[2]-'a'] -= min_o;\n                    while(min_o--) ans += (char)(i +'0');\n                }\n            }else if(t.length() == 4){\n                if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0){\n                    int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a']});\n                    m[t[0]-'a'] -= min_o;\n                    m[t[1]-'a'] -= min_o;\n                    m[t[2]-'a'] -= min_o;\n                    m[t[3]-'a'] -= min_o;\n                    while(min_o--) ans += (char)(i +'0');\n                }\n            }else if(t.length() == 5){\n                if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0 && m[t[4]-'a'] > 0){\n                    int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a'], m[t[4]-'a']});\n                    m[t[0]-'a'] -= min_o;\n                    m[t[1]-'a'] -= min_o;\n                    m[t[2]-'a'] -= min_o;\n                    m[t[3]-'a'] -= min_o;\n                    m[t[4]-'a'] -= min_o;\n                    while(min_o--) ans += (char)(i +'0');\n                }\n            }\n        }\n    }\n    \n    string originalDigits(string s) {\n        string ans;\n        vector<int> m(26,0);\n        for(auto x:s) m[x-'a']++;\n        fun(0,ans,m);\n        fun(1,ans,m);\n        sort(ans.begin(),ans.end());\n        return ans;\n    }\n};"
    },
    {
        "title": "Even Odd Tree",
        "algo_input": "A binary tree is named Even-Odd if it meets the following conditions:\n\n\n\tThe root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.\n\tFor every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).\n\tFor every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).\n\n\nGiven the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput: true\nExplanation: The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\n\n\nExample 2:\n\nInput: root = [5,4,2,3,3,7]\nOutput: false\nExplanation: The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\n\n\nExample 3:\n\nInput: root = [5,9,1,3,5,7]\nOutput: false\nExplanation: Node values in the level 1 should be even integers.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 105].\n\t1 &lt;= Node.val &lt;= 106\n\n",
        "solution_py": "from collections import deque\n# O(n) || O(h); where h is the height of the tree\n\nclass Solution:\n    def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n        if not root:\n            return False\n\n        level = 0\n        evenOddLevel = {0:1, 1:0}\n        queue = deque([root])\n\n        while queue:\n            prev = 0\n            for _ in range(len(queue)):\n                currNode = queue.popleft()\n                comparison = {0:prev < currNode.val, 1:prev > currNode.val}\n                if currNode.val % 2 != evenOddLevel[level % 2]:\n                    return False\n                else:\n                    if prev != 0 and comparison[level % 2]:\n                        prev = currNode.val\n                    elif prev == 0:\n                        prev = currNode.val\n                    else:\n                        return False\n\n                if currNode.left:\n                    queue.append(currNode.left)\n\n                if currNode.right:\n                    queue.append(currNode.right)\n\n            level += 1\n\n        return True",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar isEvenOddTree = function(root) {\n    let queue = [root];\n    let steps = 0;\n\n    while(queue.length>0){\n        const currLength = queue.length;\n        let nextQueue=[];\n\n        for(let i=0; i<currLength;i++){\n            const node = queue[i];\n            if(steps%2 !== 0){\n                if((i<currLength-1 && node.val<=queue[i+1].val) || node.val%2 !== 0){\n                    return false;\n                }\n            }else if((i<currLength-1 && node.val>=queue[i+1].val)|| node.val%2 === 0){\n                return false;\n            }\n            if(node.left) nextQueue.push(node.left);\n            if(node.right) nextQueue.push(node.right);\n        }\n        queue = nextQueue;\n        steps++;\n    }\n\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isEvenOddTree(TreeNode root) {\n        Queue<TreeNode> qu = new LinkedList<>();\n        qu.add(root);\n        boolean even = true; // maintain check for levels\n        while(qu.size()>0){\n            int size = qu.size();\n            int prev = (even)?0:Integer.MAX_VALUE; // start prev with 0 to check strictly increasing and Integer_MAX_VALUE to check strictly decreasing \n            while(size-->0){\n            TreeNode rem = qu.remove();\n                if(even){\n                    if(rem.val%2==0 || rem.val<=prev){ // false if value at even level is even or not strictly increasing \n                        return false;\n                    }\n                }else{\n                    if(rem.val%2!=0 || rem.val>=prev){// false if value at odd level is odd or not strictly decreasing\n                        return false;\n                    }\n                }\n                if(rem.left!=null){\n                    qu.add(rem.left); \n                }\n                if(rem.right!=null){\n                    qu.add(rem.right);\n                }\n                prev=rem.val;   //update previous\n              \n            }\n              even = !even; //change level\n        } \n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isEvenOddTree(TreeNode* root) {\n        queue<TreeNode*>q;\n        vector<vector<int>>ans;\n        if(root==NULL) return true;\n        q.push(root);\n        int j=0;\n        while(q.empty()!=true)\n        { vector<int>v;\n            int n=q.size();\n            for(int i=0;i<n;i++)\n            { TreeNode* t=q.front();q.pop();\n                v.push_back(t->val);\n                if(t->left) q.push(t->left);\n                if(t->right) q.push(t->right);\n            }\n         if(j%2==0)\n         {\n             for(int k=0;k<v.size()-1;k++)\n             {\n                 if(v[k]%2==0)\n                     return false;\n                 if(v[k]>=v[k+1])\n                     return false;\n             }\n             if(v[v.size()-1]%2==0)\n                 return false;\n         }\n         else\n         {\n              for(int k=0;k<v.size()-1;k++)\n             {\n                 if(v[k]%2==1)\n                     return false;\n                 if(v[k]<=v[k+1])\n                     return false;\n             }\n             if(v[v.size()-1]%2==1)\n                 return false;\n         }\n         j++;\n            ans.push_back(v);\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Super Ugly Number",
        "algo_input": "A super ugly number is a positive integer whose prime factors are in the array primes.\n\nGiven an integer n and an array of integers primes, return the nth super ugly number.\n\nThe nth super ugly number is guaranteed to fit in a 32-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: n = 12, primes = [2,7,13,19]\nOutput: 32\nExplanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].\n\n\nExample 2:\n\nInput: n = 1, primes = [2,3,5]\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= primes.length &lt;= 100\n\t2 &lt;= primes[i] &lt;= 1000\n\tprimes[i] is guaranteed to be a prime number.\n\tAll the values of primes are unique and sorted in ascending order.\n\n",
        "solution_py": "class Solution:\ndef nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n    prime_nums = len(primes)\n    index = [1]*prime_nums\n    ret = [1]*(n+1)\n    for i in range(2,n+1):\n        ret[i] = min(primes[j]*ret[index[j]] for j in range(prime_nums))\n        for k in range(prime_nums):\n            if ret[i] == primes[k]*ret[index[k]]:\n                index[k]+= 1\n    \n    return ret[-1]",
        "solution_js": "var nthSuperUglyNumber = function(n, primes) {\n    const table = Array(primes.length).fill(0);\n    const res = Array(n);\n    res[0] = 1;\n    for(let j=1;j<n;j++){\n        let curr = Infinity;\n        for (let i=0;i< table.length; i++) {\n            curr = Math.min(curr, res[table[i]]*primes[i]);\n        }\n        for (let i=0;i< table.length; i++) {\n            if (curr === res[table[i]]*primes[i]) table[i]++;\n        }\n        res[j] = curr;\n    }\n    return res[n-1];\n};",
        "solution_java": "//---------------------O(nlogk)-------------------------\n\nclass Solution {\n    public int nthSuperUglyNumber(int n, int[] primes) {\n        int []dp=new int[n+1];\n        dp[1]=1;\n        \n        PriorityQueue<Pair> pq=new PriorityQueue<>();\n        \n        for(int i=0;i<primes.length;i++){\n            pq.add(new Pair(primes[i],1,primes[i]));\n        }\n        \n        for(int i=2;i<=n;){\n            Pair curr=pq.remove();\n            \n            if(curr.val!=dp[i-1]){\n                dp[i]=curr.val;\n                i++;\n            }\n            \n            int newval=curr.prime*dp[curr.ptr+1];\n            if(newval>0){\n                pq.add(new Pair(curr.prime, curr.ptr+1,newval));\n            }\n        }\n        \n        return dp[n];\n    }\n}\n\nclass Pair implements Comparable<Pair>{\n    int prime;\n    int ptr;\n    int val;\n    \n    public Pair(int prime, int ptr, int val){\n        this.prime=prime;\n        this.ptr=ptr;\n        this.val=val;\n    }\n    \n    public int compareTo(Pair o){\n        return this.val-o.val;\n    }\n}\n\n//-----------------------O(nk)---------------------------\n\n// class Solution {\n//     public int nthSuperUglyNumber(int n, int[] primes) {\n//         int []dp=new int[n+1];\n//         dp[1]=1;\n        \n//         int []ptr=new int[primes.length];\n        \n//         Arrays.fill(ptr,1);\n        \n//         for(int i=2;i<=n;i++){\n            \n//             int min=Integer.MAX_VALUE;\n            \n//             for(int j=0;j<ptr.length;j++){\n//                 int val=dp[ptr[j]]*primes[j];\n//                 if(val>0){\n//                     min=Math.min(min,val);\n//                 }\n                \n//             }\n            \n//             dp[i]=min;\n            \n//             for(int j=0;j<ptr.length;j++){\n//                 int val=dp[ptr[j]]*primes[j];\n//                 if(val>0 && min==val){\n//                     ptr[j]++;\n//                 }\n//             }\n//         }\n        \n//         return dp[n];\n//     }\n// }",
        "solution_c": "Time: O(n*n1)  Space: O(n)\n\nclass Solution {\npublic:\n    int nthSuperUglyNumber(int n, vector<int>& primes) {\n        if(n==1)\n            return 1;\n        vector<long long int> dp(n);\n        dp[0]=1;\n        int n1=size(primes);\n        vector<int> p(n1);\n        for(int i=1;i<n;i++){\n             long long int x=INT_MAX;\n            for(int j=0;j<n1;j++){\n                x=min(x,primes[j]*dp[p[j]]);\n            }\n            dp[i]=x;\n            for(int j=0;j<n1;j++){\n                if(x==primes[j]*dp[p[j]])\n                    p[j]++;\n            }\n        }\n        return dp[n-1];\n    }\n};"
    },
    {
        "title": "Number of Pairs of Strings With Concatenation Equal to Target",
        "algo_input": "Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.\n\n&nbsp;\nExample 1:\n\nInput: nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\nOutput: 4\nExplanation: Valid pairs are:\n- (0, 1): \"777\" + \"7\"\n- (1, 0): \"7\" + \"777\"\n- (2, 3): \"77\" + \"77\"\n- (3, 2): \"77\" + \"77\"\n\n\nExample 2:\n\nInput: nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\nOutput: 2\nExplanation: Valid pairs are:\n- (0, 1): \"123\" + \"4\"\n- (2, 3): \"12\" + \"34\"\n\n\nExample 3:\n\nInput: nums = [\"1\",\"1\",\"1\"], target = \"11\"\nOutput: 6\nExplanation: Valid pairs are:\n- (0, 1): \"1\" + \"1\"\n- (1, 0): \"1\" + \"1\"\n- (0, 2): \"1\" + \"1\"\n- (2, 0): \"1\" + \"1\"\n- (1, 2): \"1\" + \"1\"\n- (2, 1): \"1\" + \"1\"\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i].length &lt;= 100\n\t2 &lt;= target.length &lt;= 100\n\tnums[i] and target consist of digits.\n\tnums[i] and target do not have leading zeros.\n\n",
        "solution_py": "class Solution:\n    def numOfPairs(self, nums, target):\n        return sum(i + j == target for i, j in permutations(nums, 2))",
        "solution_js": "/**\n * @param {string[]} nums\n * @param {string} target\n * @return {number}\n */\nvar numOfPairs = function(nums, target) {\n    var count = 0;\n    var x = 0;\n    while (x < nums.length) {\n        for (let y = 0; y<nums.length; y++) {\n            if (nums[x] + nums[y] == target) {\n                count += 1;\n                if (x == y) {\n                    count -= 1;\n                }\n            }\n        }\n        x++;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int numOfPairs(String[] nums, String target) {\n        \n        HashMap<String, Integer> map = new HashMap<>();\n        for (int i = 0; i<nums.length; i++){\n            map.put(nums[i], map.getOrDefault(nums[i],0)+1);\n        }\n        \n        int ans = 0, n = target.length();\n        String a = \"\", b= \"\";\n        for (int i = 1; i<n; i++){\n            a = target.substring(0,i);\n            b = target.substring(i,n);\n            if (map.containsKey(a) && map.containsKey(b)){\n                if (a.equals(b)) ans += (map.get(a) * (map.get(a)-1));\n                else ans+= (map.get(a) * map.get(b));\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numOfPairs(vector<string>& nums, string target) {\n        unordered_map<string, int> freq;\n        for (auto num : nums) if (num.size() < target.size()) freq[num]++;\n        \n        int res = 0;\n        for (auto [s, frq] : freq) {\n            \n            if (target.find(s) == 0) {\n                \n                if (s + s == target) \n                    res += frq*(frq-1);\n                \n                else \n                    res += frq * freq[target.substr(s.size())];\n            }\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Pancake Sorting",
        "algo_input": "Given an array of integers arr, sort the array by performing a series of pancake flips.\n\nIn one pancake flip we do the following steps:\n\n\n\tChoose an integer k where 1 &lt;= k &lt;= arr.length.\n\tReverse the sub-array arr[0...k-1] (0-indexed).\n\n\nFor example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.\n\nReturn an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,2,4,1]\nOutput: [4,2,4,3]\nExplanation: \nWe perform 4 pancake flips, with k values 4, 2, 4, and 3.\nStarting state: arr = [3, 2, 4, 1]\nAfter 1st flip (k = 4): arr = [1, 4, 2, 3]\nAfter 2nd flip (k = 2): arr = [4, 1, 2, 3]\nAfter 3rd flip (k = 4): arr = [3, 2, 1, 4]\nAfter 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\n\n\nExample 2:\n\nInput: arr = [1,2,3]\nOutput: []\nExplanation: The input is already sorted, so there is no need to flip anything.\nNote that other answers, such as [3, 3], would also be accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 100\n\t1 &lt;= arr[i] &lt;= arr.length\n\tAll integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).\n\n",
        "solution_py": "class Solution:\n    def pancakeSort(self, arr: List[int]) -> List[int]:\n        #helper function to flip the numbers in the array\n\t\tdef flip(i, j):\n            while i < j:\n                arr[i], arr[j] = arr[j], arr[i]\n                j -= 1\n                i += 1\n        \n        #sort from 0 to i\n        def sort(i):\n\t\t\t#base case where all the numbers are sorted, thus no more recursive calls\n            if i < 0:\n                return []\n            ret = []\n\t\t\t#find the biggest number, which always will be the len(arr), or i + 1\n            idx = arr.index(i + 1)\n\t\t\t# if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number\n            if idx == i:\n                return sort(i - 1)\n            \n\t\t\t#we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result\n            ret.append(idx + 1)\n            flip(0, idx)\n\t\t\t#we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well)\n            ret.append(i + 1)\n            flip(0, i)\n\t\t\t#sort the next biggest number by setting a new boundary i - 1\n            return ret + sort(i - 1)\n            \n            \n        return sort(len(arr) - 1)\n            ",
        "solution_js": "var pancakeSort = function(arr) {\nlet res = [];\n\nfor(let i=arr.length; i>0; i--){//search the array for all values from 1 to n\n    let idx = arr.indexOf(i);\n    if(idx!=i-1){// if value is not present at its desired index\n        let pancake = arr.slice(0,idx+1).reverse();//flip the array with k=index of value i to put it in front of the array\n        res.push(idx+1);\n        arr = arr.slice(idx+1);\n        arr = pancake.concat(arr);//value i is now at index 0\n        pancake = arr.slice(0,i).reverse();//flip the array with k = i-1 to put the value at its place\n        res.push(i);\n        arr = arr.slice(i);\n        arr = pancake.concat(arr);//now the array is sorted from i to n\n    }\n}\nreturn res;\n};",
        "solution_java": "// BruteForce Approach!\n// Author - Nikhil Sharma\n// LinkedIn - https://www.linkedin.com/in/nikhil-sharma-41a287226/\n// Twitter - https://twitter.com/Sharma_Nikh12\n\nclass Solution {\n    public List<Integer> pancakeSort(int[] arr) {\n        List<Integer> list = new ArrayList<>();\n        int n = arr.length;\n        while(n!=1) {\n            int maxIndex = findIndex(arr,n);\n            reverse(arr, maxIndex);\n            reverse(arr, n-1);\n            list.add(maxIndex+1);\n            list.add(n);\n            n--;\n        }\n        return list;\n    }\n\n    static int findIndex(int[] arr, int value) {\n        for(int i=0; i<arr.length; i++) {\n            if(arr[i] == value){\n                return i;\n            }\n        }\n        return 0;\n    }\n\n    static void reverse(int[] arr, int maxIndex) {\n        int l = 0;\n        while(l<maxIndex) {\n            int temp = arr[l];\n            arr[l] = arr[maxIndex];\n            arr[maxIndex] = temp;\n            l++;\n            maxIndex--;\n        }\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    void reverse(vector<int>&arr,int start,int end){\n        while(start<end){\n            swap(arr[start++],arr[end--]);\n        }\n    }\npublic:\n    vector<int> pancakeSort(vector<int>& arr) {\n        vector<int>copy=arr;\n        sort(copy.begin(),copy.end());\n        int end=copy.size()-1;\n        vector<int>ans;\n        while(end>0){\n            if(arr[end]!=copy[end]){\n                int pos=end-1;\n                while(arr[pos]!=copy[end]){\n                    pos--;\n                }\n                reverse(arr,0,pos);\n                if(pos!=0){\n                    ans.push_back(pos+1);\n                }\n                reverse(arr,0,end);\n                ans.push_back(end+1);\n            }\n            end--;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Product of Word Lengths",
        "algo_input": "Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\nOutput: 16\nExplanation: The two words can be \"abcw\", \"xtfn\".\n\n\nExample 2:\n\nInput: words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\nOutput: 4\nExplanation: The two words can be \"ab\", \"cd\".\n\n\nExample 3:\n\nInput: words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: 0\nExplanation: No such pair of words.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length &lt;= 1000\n\twords[i] consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def maxProduct(self, words: List[str]) -> int:\n        def check(w1, w2):\n            for i in w1:\n                if i in w2: \n                    return False\n            return True\n        \n        n = len(words)   \n        Max = 0\n        for i in range(n):\n            for j in range(i+1, n):\n                if check(words[i], words[j]):\n                    Max = max(Max, len(words[i])*len(words[j]))      \n        return Max",
        "solution_js": "/**\n * @param {string[]} words\n * @return {number}\n */\nvar maxProduct = function(words) {\n    words.sort((a, b) => b.length - a.length);\n    \n    const m = new Map();\n    for(let word of words) {\n        if(m.has(word)) continue;\n        const alpha = new Array(26).fill(0);\n        for(let w of word) {\n            let idx = w.charCodeAt(0) - 'a'.charCodeAt(0);\n            alpha[idx] = 1;\n        }\n        m.set(word, parseInt(alpha.join(''), 2));\n    }\n    \n    const hasCommonLetters = (a, b) => {\n        const sb = m.get(b);\n        const sa = m.get(a);\n        return (sa & sb) != 0;\n    }\n    let ans = 0, len = words.length;\n    for(let i = 0; i < len; i++) {\n        for(let j = i + 1; j < len; j++) {\n            if(!hasCommonLetters(words[i], words[j])) {\n                ans = Math.max(ans, words[i].length * words[j].length);\n            }\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxProduct(String[] words) {\n        int n = words.length;\n        int[] masks = new int[n];\n\n        for (int i=0; i<n; i++)\n            for (char c: words[i].toCharArray())\n                masks[i] |= (1 << (c - 'a'));\n\n        int largest = 0;\n        for (int i=0; i<n-1; i++)\n            for (int j=i+1; j<n; j++)\n                if ((masks[i] & masks[j]) == 0)\n                    largest = Math.max(largest, words[i].length() * words[j].length());\n\n        return largest;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxProduct(vector<string>& words) {\n        vector<unordered_set<char>> st;\n        int res =0;\n        for(string s : words){\n            unordered_set<char> temp;\n            for(char c : s){\n                temp.insert(c);\n            }\n            st.push_back(temp);\n        }\n        for(int i = 0;i<words.size();i++){\n            for(int j =0;j<i;j++){\n                bool flag = false;\n                for(auto val : st[i]){\n                    if(st[j].find(val) != st[j].end()){\n                        flag = true;\n                        break;\n                    }\n                }\n                if(flag == false) {\n                    int prd = words[i].length() * words[j].length();\n                    res =max(res, prd);\n                }\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Second Minimum Node In a Binary Tree",
        "algo_input": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property&nbsp;root.val = min(root.left.val, root.right.val)&nbsp;always holds.\n\nGiven such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.\n\nIf no such second minimum value exists, output -1 instead.\n\n&nbsp;\n\n&nbsp;\nExample 1:\n\nInput: root = [2,2,5,null,null,5,7]\nOutput: 5\nExplanation: The smallest value is 2, the second smallest value is 5.\n\n\nExample 2:\n\nInput: root = [2,2,2]\nOutput: -1\nExplanation: The smallest value is 2, but there isn't any second smallest value.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 25].\n\t1 &lt;= Node.val &lt;= 231 - 1\n\troot.val == min(root.left.val, root.right.val)&nbsp;for each internal node of the tree.\n\n",
        "solution_py": "# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n        temp1=temp2=float(inf)\n        from collections import deque\n        a=deque([root])\n        while a:\n            node=a.popleft()\n            if node.valtemp1:\n                if node.val",
        "solution_js": "var findSecondMinimumValue = function(root) {\n  \n    let firstMin=Math.min()\n    let secondMin=Math.min()\n    \n    const que=[root]\n    \n    while(que.length){\n        const node=que.shift()\n        if(node.val<=firstMin){\n            if(node.val<firstMin)secondMin=firstMin\n            firstMin=node.val\n        }else if(node.val<=secondMin){\n            secondMin=node.val\n        }\n        if(node.left)que.push(node.left)\n        if(node.right)que.push(node.right)\n    }\n    return secondMin===Math.min()?-1:secondMin\n};",
        "solution_java": "class Solution {\n    int ans = Integer.MAX_VALUE;\n    boolean x = true;\n\n    public int findSecondMinimumValue(TreeNode root) {\n        go(root);\n        return x ? -1 : ans;\n    }\n\n    private void go(TreeNode root) {\n        if (root == null) return;\n        if (root.left != null) {\n            if (root.left.val == root.val) go(root.left);\n            else {\n                x = false;\n                ans = Math.min(ans, root.left.val);\n            }\n        }\n        if (root.right != null) {\n            if (root.right.val == root.val) go(root.right);\n            else {\n                x = false;\n                ans = Math.min(ans, root.right.val);\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findSecondMinimumValue(TreeNode* root) {\n        queue<TreeNode*>q;\n        q.push(root);\n        vector<int>v;\n        while(!q.empty()){\n            v.push_back(q.front()->val);\n            if(q.front()->left){\n                q.push(q.front()->left);\n            }\n            if(q.front()->right){\n                q.push(q.front()->right);\n            }\n            q.pop();\n        }\n        sort(v.begin(),v.end());\n        int ans=-1;\n        for(int i=1;i<v.size();i++){\n            if(v[i]!=v[0]){\n                return v[i];\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Same Tree",
        "algo_input": "Given the roots of two binary trees p and q, write a function to check if they are the same or not.\n\nTwo binary trees are considered the same if they are structurally identical, and the nodes have the same value.\n\n&nbsp;\nExample 1:\n\nInput: p = [1,2,3], q = [1,2,3]\nOutput: true\n\n\nExample 2:\n\nInput: p = [1,2], q = [1,null,2]\nOutput: false\n\n\nExample 3:\n\nInput: p = [1,2,1], q = [1,1,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in both trees is in the range [0, 100].\n\t-104 &lt;= Node.val &lt;= 104\n\n",
        "solution_py": "class Solution:\ndef isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n    if not p and not q:\n        return True\n    elif not p or not q:\n        return False\n    else:\n        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
        "solution_js": "var isSameTree = function(p, q) {\n    \n    const stack = [p, q];\n    \n    while (stack.length) {\n        const node2 = stack.pop();\n        const node1 = stack.pop();\n        \n        if (!node1 && !node2) continue;\n\n        if (!node1 && node2 || node1 && !node2 || node1.val !== node2.val) {\n            return false;\n        }\n        \n        stack.push(node1.left, node2.left, node1.right, node2.right);\n    }\n    \n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isSameTree(TreeNode p, TreeNode q) {\n        // Base case: if both trees are null, they are identical\n        if (p == null && q == null) {\n            return true;\n        }\n        // If only one tree is null or the values are different, they are not identical\n        if (p == null || q == null || p.val != q.val) {\n            return false;\n        }\n        // Recursively check if the left and right subtrees are identical\n        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSameTree(TreeNode* p, TreeNode* q) {\n        if(p == NULL || q == NULL) return q == p;\n        if(p->val != q->val) return false;\n        \n        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n    }\n};"
    },
    {
        "title": "Magnetic Force Between Two Balls",
        "algo_input": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.\n\nRick stated that magnetic force between two different balls at positions x and y is |x - y|.\n\nGiven the integer array position and the integer m. Return the required force.\n\n&nbsp;\nExample 1:\n\nInput: position = [1,2,3,4,7], m = 3\nOutput: 3\nExplanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n\n\nExample 2:\n\nInput: position = [5,4,3,2,1,1000000000], m = 2\nOutput: 999999999\nExplanation: We can use baskets 1 and 1000000000.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == position.length\n\t2 &lt;= n &lt;= 105\n\t1 &lt;= position[i] &lt;= 109\n\tAll integers in position are distinct.\n\t2 &lt;= m &lt;= position.length\n\n",
        "solution_py": "class Solution:\n  def possible (self,distance,positions,M):\n    ball = 1 \n    lastPos = positions[0]  \n    for pos in positions:\n      if pos-lastPos >= distance:\n        ball+=1 \n        if ball == M: return True \n        lastPos=pos \n     \n    return False \n        \n      \n    \n  def maxDistance(self, positions,M):\n    positions.sort()\n    low = 0 \n    high = positions [-1] \n    ans = 0\n    while low<=high:\n      distance = low+(high-low)//2 \n      \n      if self.possible(distance,positions,M):\n        ans = distance\n        low=distance+1 \n      else:\n        high=distance-1 \n    return ans ",
        "solution_js": "var maxDistance = function(position, m) {\n    position = position.sort((a, b) => a - b);\n\n    function canDistribute(n) {\n        let count = 1;\n        let dist = 0;\n        \n        for(let i = 1; i < position.length; i++) {\n            dist += position[i] - position[i - 1];\n            \n            if (dist >= n) {\n                count++;\n                dist = 0;\n            }\n        }\n        \n        return count >= m;\n    }\n    \n    let left = 1;\n    let right = position[position.length - 1] - position[0];\n    let ans;\n    \n    while (left <= right) {\n        const mid = Math.floor((left + right) / 2);\n\n        if (canDistribute(mid)) {\n            ans = mid;\n            left = mid + 1;\n        } else {\n            right = mid - 1;\n        }\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxDistance(int[] position, int m) {\n        Arrays.sort(position);\n        int low=Integer.MAX_VALUE;\n        int high=0;\n        for(int i=1;i<position.length;i++){\n            low=Math.min(low,position[i]-position[i-1]);\n        }\n        high=position[position.length-1]-position[0];\n        int ans=-1;\n        while(low<=high){\n            int mid=low+(high-low)/2;\n            if(blackbox(mid,position,m)){\n                ans=mid;\n                low=mid+1;\n            }\n            else{\n                high=mid-1;\n            }\n        }\n        return ans;\n    }\n\t\tpublic boolean blackbox(int maxPossibleDist,int[] position, int m){\n        int balls=1;\n        int prevballplace=position[0];\n        for(int i=1;i<position.length;i++){\n            if(position[i]-prevballplace>=maxPossibleDist){\n                prevballplace=position[i];\n                balls++;\n            }\n        }\n        if(balls>=m){\n            return true;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPossible(vector<int>& position, int m,int mid){\n        long long int basketCount=1;\n        int lastPos=position[0];\n        for(int i=0;i<position.size();i++){\n            if((position[i]-lastPos)>=mid){\n                basketCount++;\n                lastPos=position[i];\n            }\n        }\n        return basketCount>=m;\n    }\n    int maxDistance(vector<int>& position, int m) {\n        sort(position.begin(),position.end());\n        int n=position.size();\n        long long int start=1;\n        long long int end=position[n-1]-position[0];\n        int ans=0;\n        int mid= start+(end-start)/2;\n        while(start<=end){\n            if(isPossible(position,m,mid)){\n            ans=mid;\n            start=mid+1;\n        }\n        else\n            end=mid-1;\n           mid= start+(end-start)/2; \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Flatten Nested List Iterator",
        "algo_input": "You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.\n\nImplement the NestedIterator class:\n\n\n\tNestedIterator(List&lt;NestedInteger&gt; nestedList) Initializes the iterator with the nested list nestedList.\n\tint next() Returns the next integer in the nested list.\n\tboolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.\n\n\nYour code will be tested with the following pseudocode:\n\ninitialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n    append iterator.next() to the end of res\nreturn res\n\n\nIf res matches the expected flattened list, then your code will be judged as correct.\n\n&nbsp;\nExample 1:\n\nInput: nestedList = [[1,1],2,[1,1]]\nOutput: [1,1,2,1,1]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n\n\nExample 2:\n\nInput: nestedList = [1,[4,[6]]]\nOutput: [1,4,6]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nestedList.length &lt;= 500\n\tThe values of the integers in the nested list is in the range [-106, 106].\n\n",
        "solution_py": "class NestedIterator:\n    def __init__(self, nestedList: [NestedInteger]):\n        self.flattened_lst = self.flattenList(nestedList)\n        self.idx = 0\n    \n    def next(self) -> int:\n        if self.idx >= len(self.flattened_lst):\n            raise Exception(\"Index out of bound\")\n        self.idx += 1\n        return self.flattened_lst[self.idx-1]\n    \n    def hasNext(self) -> bool:\n        return self.idx < len(self.flattened_lst)\n    \n    def flattenList(self, lst):\n        flattened_lst = []\n        for ele in lst:\n            if ele.isInteger():\n                flattened_lst.append(ele.getInteger())\n            else:\n                flattened_lst.extend(self.flattenList(ele.getList()))\n        return flattened_lst",
        "solution_js": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * function NestedInteger() {\n *\n *     Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     @return {boolean}\n *     this.isInteger = function() {\n *         ...\n *     };\n *\n *     Return the single integer that this NestedInteger holds, if it holds a single integer\n *     Return null if this NestedInteger holds a nested list\n *     @return {integer}\n *     this.getInteger = function() {\n *         ...\n *     };\n *\n *     Return the nested list that this NestedInteger holds, if it holds a nested list\n *     Return null if this NestedInteger holds a single integer\n *     @return {NestedInteger[]}\n *     this.getList = function() {\n *         ...\n *     };\n * };\n */\n/**\n * @constructor\n * @param {NestedInteger[]} nestedList\n */\nvar NestedIterator = function(nestedList) {\n    this.nestedList = []\n    this.ptr = 0\n    const dfs = (elem) => {\n        if(!elem.isInteger()) {\n            let list = elem.getList()\n            for(let i = 0;i<list.length;i++) {\n                dfs(list[i])\n            }\n        }else {\n            this.nestedList.push(elem.getInteger())\n        }\n    }\n    for(let i = 0;i<nestedList.length;i++) {\n        dfs(nestedList[i])\n    }\n};\n\n\n/**\n * @this NestedIterator\n * @returns {boolean}\n */\nNestedIterator.prototype.hasNext = function() {\n    if(this.ptr < this.nestedList.length) return true\n    else return false\n};\n\n/**\n * @this NestedIterator\n * @returns {integer}\n */\nNestedIterator.prototype.next = function() {\n    return this.nestedList[this.ptr++]\n};\n\n/**\n * Your NestedIterator will be called like this:\n * var i = new NestedIterator(nestedList), a = [];\n * while (i.hasNext()) a.push(i.next());\n*/",
        "solution_java": "public class NestedIterator implements Iterator<Integer> {\n    List<Integer> list=new ArrayList();\n    void flatten(List<NestedInteger> nestedList){\n        for(NestedInteger nested:nestedList){\n            if(nested.isInteger())\n                list.add(nested.getInteger());\n            else\n                flatten(nested.getList());\n        }\n    }\n    public NestedIterator(List<NestedInteger> nestedList) {\n        flatten(nestedList);\n    }\n    int index=0;\n    @Override\n    public Integer next() {\n        return list.get(index++);\n    }\n\n    @Override\n    public boolean hasNext() {\n        return index<list.size();\n    }\n}",
        "solution_c": "class NestedIterator {\n    vector<int> v;\n    int index;\n    void helper(vector<NestedInteger> &nestedList, vector<int>& v)\n    {\n        for (int i = 0; i < nestedList.size(); i++)\n        {\n            if (nestedList[i].isInteger())\n            {\n                v.push_back(nestedList[i].getInteger());\n            }\n            else\n            {\n                helper(nestedList[i].getList(), v);\n            }\n        }\n    }\npublic:\n    NestedIterator(vector<NestedInteger> &nestedList) {\n        helper(nestedList, v);\n        index = 0;\n    }\n    \n    int next() {\n        return v[index++];\n    }\n    \n    bool hasNext() {\n        if (v.size() <= index)\n        {\n            return false;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Find All Numbers Disappeared in an Array",
        "algo_input": "Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.\n\n&nbsp;\nExample 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [5,6]\nExample 2:\nInput: nums = [1,1]\nOutput: [2]\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= nums[i] &lt;= n\n\n\n&nbsp;\nFollow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.\n",
        "solution_py": "class Solution:\n    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n        return set(nums) ^ set(range(1,len(nums)+1))",
        "solution_js": "var findDisappearedNumbers = function(nums) {\n    let result = [];\n    for(let i = 0; i < nums.length; i++) {\n        let id = Math.abs(nums[i]) - 1;\n        nums[id] = - Math.abs(nums[id]);\n    }\n    for(let i = 0; i < nums.length; i++) {\n        if(nums[i] > 0) result.push(i + 1);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public List<Integer> findDisappearedNumbers(int[] nums) {\n        List<Integer> res = new ArrayList<>();\n        // 0 1 2 3 4 5 6 7 <- indx\n        // 4 3 2 7 8 2 3 1 <- nums[i]\n        for(int i=0;i<nums.length;i++) {\n            int indx = Math.abs(nums[i])-1;\n            if(nums[indx]>0) {\n                nums[indx] = nums[indx]*-1;\n            }\n        }\n        // 0 1 2 3 4 5 6 7 <- indx\n        // -4 -3 -2 -7 8 2 -3 -1 <- nums[i]\n        for(int i=0;i<nums.length;i++) {\n            if(nums[i]>0) {\n                res.add(i+1);\n            }else {\n                nums[i] *= -1;\n            }\n        }\n        // [ 5, 6]\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findDisappearedNumbers(vector<int>& nums) {\n        vector<int> res;\n        int n = nums.size();\n        for (int i = 0; i < n; i++) {\n            if (nums[abs(nums[i]) - 1] > 0) {\n                nums[abs(nums[i]) - 1] *= -1;\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            if (nums[i] > 0)\n                res.push_back(i + 1);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Total Appeal of A String",
        "algo_input": "The appeal of a string is the number of distinct characters found in the string.\n\n\n\tFor example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.\n\n\nGiven a string s, return the total appeal of all of its substrings.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abbca\"\nOutput: 28\nExplanation: The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.\n\n\nExample 2:\n\nInput: s = \"code\"\nOutput: 20\nExplanation: The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def appealSum(self, s: str) -> int:\n        res, cur, prev = 0, 0, defaultdict(lambda: -1)\n        for i, ch in enumerate(s):\n            cur += i - prev[ch]\n            prev[ch] = i\n            res += cur\n        return res  ",
        "solution_js": "var appealSum = function(s) {\n  let ans = 0, n = s.length;\n  let lastIndex = Array(26).fill(-1);\n  for (let i = 0; i < n; i++) {\n    let charcode = s.charCodeAt(i) - 97;\n    let lastIdx = lastIndex[charcode];\n    ans += (n - i) * (i - lastIdx);\n    lastIndex[charcode] = i;\n  }  \n  return ans;\n};",
        "solution_java": "class Solution {\n    public long appealSum(String s) {\n        long res = 0;\n        char[] cs = s.toCharArray();\n        int n = cs.length;\n        int[] pos = new int[26];\n        Arrays.fill(pos, -1);\n        for (int i = 0; i < n; ++i) {\n            int j = cs[i] - 'a', prev = pos[j]; \n            res += (i - prev) * (long) (n - i);\n            pos[j] = i;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tlong long appealSum(string s) {\n\t\tint n = s.size();\n\t\tlong long ans = 0;\n\t\tfor(char ch='a';ch<='z';ch++)       // we are finding the number of substrings containing at least 1 occurence of ch\n\t\t{\n\t\t\tint prev = 0;                   // prev will store the previous index of the charcter ch\n\t\t\tfor(int i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tif(s[i] == ch) prev = i+1;  // if the current character is equal to ch , then the no. of substring\n\t\t\t\t\t\t\t\t\t\t\t// ending at i and having at least one occurence of ch will be i+1 .\n\n\t\t\t\tans+=prev;                  // else the no. of substrings ending at i and having at least\n\t\t\t\t\t\t\t\t\t\t\t// one occurence of ch will be the equal to, the previous index of ch.\n\t\t\t}\n\t\t}\n\t\treturn ans;                        // TC - O(n*26) , SC - O(1)\n\t}\n};"
    },
    {
        "title": "Two Sum",
        "algo_input": "Given an array of integers nums&nbsp;and an integer target, return indices of the two numbers such that they add up to target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n\n\nExample 2:\n\nInput: nums = [3,2,4], target = 6\nOutput: [1,2]\n\n\nExample 3:\n\nInput: nums = [3,3], target = 6\nOutput: [0,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 104\n\t-109 &lt;= nums[i] &lt;= 109\n\t-109 &lt;= target &lt;= 109\n\tOnly one valid answer exists.\n\n\n&nbsp;\nFollow-up:&nbsp;Can you come up with an algorithm that is less than&nbsp;O(n2)&nbsp;time complexity?",
        "solution_py": "class Solution:\n    def twoSum(self, nums: List[int], target: int) -> List[int]:\n        n = len(nums)\n        for i in range(n - 1):\n            for j in range(i + 1, n):\n                if nums[i] + nums[j] == target:\n                    return [i, j]\n        return []  # No solution found",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nvar twoSum = function(nums, target) {\n    var sol = [];\n    var found = 0;\n    for(let i = 0; i < nums.length; i ++) {\n        for(let j = i + 1; j < nums.length; j ++) {\n            if(nums[i] + nums[j] === target) {\n                sol.push(i, j);\n                found = 1;\n                break;\n            }\n        }\n        if(found == 1) return sol;\n    }\n    return sol;\n};",
        "solution_java": "class Solution {\n    public int[] twoSum(int[] nums, int target) {\n        int[] answer = new int[2];\n\t\t// Two for loops for selecting two numbers and check sum equal to target or not\n\t\t\n        for(int i = 0; i < nums.length; i++){\n            for(int j = i+1; j < nums.length; j++) {\n\t\t\t // j = i + 1; no need to check back elements it covers in i;\n                if(nums[i] + nums[j] == target) {\n\t\t\t\t// Check sum == target or not\n                    answer[0] = i;\n                    answer[1] = j;\n                    return answer;\n                }\n            } \n        }\n          return null;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> twoSum(vector<int>& nums, int target) {\n        int n = nums.size();\n        for (int i = 0; i < n - 1; i++) {\n            for (int j = i + 1; j < n; j++) {\n                if (nums[i] + nums[j] == target) {\n                    return {i, j};\n                }\n            }\n        }\n        return {}; // No solution found\n    }\n};"
    },
    {
        "title": "Total Hamming Distance",
        "algo_input": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nGiven an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,14,2]\nOutput: 6\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n\n\nExample 2:\n\nInput: nums = [4,14,4]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t0 &lt;= nums[i] &lt;= 109\n\tThe answer for the given input will fit in a 32-bit integer.\n\n",
        "solution_py": "class Solution:\n    def totalHammingDistance(self, arr: List[int]) -> int:\n\n        total = 0\n        for i in range(0,31):\n            count = 0\n            for j in arr :\n                count+= (j >> i) & 1\n            total += count*(len(arr)-count)\n        return total",
        "solution_js": "var totalHammingDistance = function(nums) {\n    let n = nums.length, ans = 0;\n    for(let bit = 0; bit < 32; bit++) {\n        let zeros = 0, ones = 0;\n        for(let i = 0; i < n; i++) {\n            ((nums[i] >> bit) & 1) ? ones++ : zeros++;\n        }\n        ans += zeros * ones;\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int totalHammingDistance(int[] nums) {\n        int total = 0;\n        int[][] cnt = new int[2][32];\n        for (int i = 0; i < nums.length; i++) {\n            for (int j = 0; j < 32; j++) {\n                int idx = (nums[i] >> j) & 1;\n                total += cnt[idx ^ 1][j];\n                cnt[idx][j]++;\n            }\n        }\n        return total;\n    }\n}",
        "solution_c": "/*\nSo in the question we want to find out the \nnumber of difference of bits between each pair \nso in the brute force we will iterate over the vector \nand for every pair we will calculate the Hamming  distance \nthe Hamming distance will be calculated by taking XOR  between the two elements\nand then finding out the number of ones in the XOR of those two elements \nthe intuition behind this method is that XOR will contain 1's at those places \nwhere the corresponding bits of  elements x & y are different \ntherefore we will add this count\nto our answer\n*/\nclass Solution {\npublic:\n    int hammingDistance(int x, int y) {\n        int XOR=x^y;\n        \n        int count=0;\n        while(XOR){\n            if(XOR&1)\n                count++;\n            \n            XOR=XOR>>1;\n        }\n        return count;\n    }\n    \n    int totalHammingDistance(vector<int>& nums) {\n        int ans=0;\n        for(int i=0;i<nums.size()-1;i++){\n            for(int j=i+1;j<nums.size();j++){\n                ans+=hammingDistance(nums[i],nums[j]);\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Merge In Between Linked Lists",
        "algo_input": "You are given two linked lists: list1 and list2 of sizes n and m respectively.\n\nRemove list1's nodes from the ath node to the bth node, and put list2 in their place.\n\nThe blue edges and nodes in the following figure indicate the result:\n\nBuild the result list and return its head.\n\n&nbsp;\nExample 1:\n\nInput: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput: [0,1,2,1000000,1000001,1000002,5]\nExplanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.\n\n\nExample 2:\n\nInput: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput: [0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation: The blue edges and nodes in the above figure indicate the result.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= list1.length &lt;= 104\n\t1 &lt;= a &lt;= b &lt; list1.length - 1\n\t1 &lt;= list2.length &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n        head = list1\n        for _ in range(a-1):\n            head = head.next\n        cur = head.next\n        for _ in range(b-a):\n            cur = cur.next\n        head.next = list2\n        while head.next:\n            head = head.next\n        if cur.next:\n            head.next = cur.next\n        return list1",
        "solution_js": "var mergeInBetween = function(list1, a, b, list2) {\n    let start = list1;\n    let end = list1;\n\n    for (let i = 0; i <= b && start != null && end != null; i++) {\n        if (i < a - 1) start = start.next;\n        if (i <= b) end = end.next;\n    }\n\n    let tail = list2;\n\n    while (tail.next != null) {\n        tail = tail.next;\n    }\n\n    start.next = list2;\n    tail.next = end;\n\n    return list1;\n};",
        "solution_java": "class Solution {\n    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n        ListNode left = list1;\n        for (int i = 1; i < a; i++)\n            left = left.next;\n        \n        ListNode middle = left;\n        for (int i = a; i <= b; i++)\n            middle = middle.next;\n        \n\t\tleft.next = list2;\n        while (list2.next != null)\n            list2 = list2.next;\n        \n        list2.next = middle.next;\n        return list1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {\n        \n        int jump1 = 1;\n        ListNode *temp1 = list1;\n        while (jump1 < a){\n            temp1 = temp1->next;\n            jump1++;\n        }                                //Gets the pointer to a\n        \n\t\tint jump2 = 1;\n        ListNode *temp2 = list1;\n        while(jump2 <= b){\n            temp2 = temp2->next;\n            jump2++;\n        }                                //Gets the pointer to b\n        \n\t\tListNode *temp3=list2;\n        while(temp3->next != NULL){\n            temp3=temp3->next;\n        }                               //Gets the pointer to the tail of list2\n        \n\t\t\n\t\ttemp1->next=list2;              //set the next pointer of a to the head of list2\n        \n\t\ttemp3->next = temp2->next;      //set next of tail of list2 to the pointer to b\n        \n\t\treturn list1;                   //return the original list i.e. list1\n        \n    }\n};"
    },
    {
        "title": "IPO",
        "algo_input": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.\n\nYou are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.\n\nInitially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.\n\nPick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.\n\nThe answer is guaranteed to fit in a 32-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput: 4\nExplanation: Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n\n\nExample 2:\n\nInput: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput: 6\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 105\n\t0 &lt;= w &lt;= 109\n\tn == profits.length\n\tn == capital.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= profits[i] &lt;= 104\n\t0 &lt;= capital[i] &lt;= 109\n\n",
        "solution_py": "from heapq import heappush, heappop, nlargest\nclass Solution:\n    def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n        if w >= max(capital):\n            return w + sum(nlargest(k, profits))\n        \n        projects = [[capital[i],profits[i]] for i in range(len(profits))]\n        projects.sort(key=lambda x: x[0])\n        \n        heap = []\n        \n        for i in range(k):\n            while projects and projects[0][0] <= w:\n                heappush(heap, -1*projects.pop(0)[1])\n            \n            if not heap:\n                break\n            p = -heappop(heap)\n            w += p\n        return w",
        "solution_js": "var findMaximizedCapital = function(k, w, profits, capital) {\n    let capitals_asc_queue = new MinPriorityQueue();\n    let profits_desc_queue = new MaxPriorityQueue();\n    for (let i = 0; i < capital.length; i++)\n        capitals_asc_queue.enqueue([capital[i], profits[i]], capital[i]);\n   \n\tfor (let i = 0; i < k; i++)    {\n        while (!capitals_asc_queue.isEmpty() && capitals_asc_queue.front().element[0] <=w ) {\n            let el = capitals_asc_queue.dequeue().element;\n            profits_desc_queue.enqueue(el, el[1]);\n        }\n        if (profits_desc_queue.isEmpty()) return w;\n        w += profits_desc_queue.dequeue().element[1];\n    }\n    return w;\n}",
        "solution_java": "class Solution {\n\tstatic int[][] dp;\n\n\tpublic int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n\t\tdp = new int[k + 1][profits.length + 1];\n\t\tfor (int[] row : dp) {\n\t\t\tArrays.fill(row, -1);\n\t\t}\n\t\treturn w + help(k, w, 0, profits, capital);\n\t}\n\n\tpublic int help(int k, int w, int i, int[] profits, int[] capital) {\n\t\tif (k == 0 || i >= profits.length)\n\t\t\treturn 0;\n\t\tif (dp[k][i] != -1)\n\t\t\treturn dp[k][i];\n\t\tint res = Integer.MIN_VALUE;\n\t\tif (capital[i] <= w) {\n\t\t\tres = Math.max(res, Math.max(profits[i] + help(k - 1, w + profits[i], i + 1, profits, capital),\n\t\t\t\t\thelp(k, w, i + 1, profits, capital)));\n\t\t} else {\n\t\t\tres = Math.max(res, help(k, w, i + 1, profits, capital));\n\t\t}\n\t\treturn dp[k][i] = res;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pqsg;\n        priority_queue<pair<int, int>> pqgs;\n        int n = capital.size();\n        for(int i = 0; i < n; i++)\n        {\n            //int val = profit[i]-capital[i];\n            if(capital[i] <= w)\n            {\n                pqgs.push({profits[i],capital[i]});\n            }\n            else if(capital[i] > w)\n            {\n                pqsg.push({capital[i],profits[i]});\n            }\n        }\n        while(k-- && !pqgs.empty())\n        {\n            pair<int, int> tmp = pqgs.top();\n            w += tmp.first;\n            pqgs.pop();\n            while(!pqsg.empty() && pqsg.top().first <= w)\n            {\n                pqgs.push({pqsg.top().second,pqsg.top().first});\n                pqsg.pop();\n            }\n        }\n        return w;\n    }\n};"
    },
    {
        "title": "Design an ATM Machine",
        "algo_input": "There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.\n\nWhen withdrawing, the machine prioritizes using banknotes of larger values.\n\n\n\tFor example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.\n\tHowever, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.\n\n\nImplement the ATM class:\n\n\n\tATM() Initializes the ATM object.\n\tvoid deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.\n\tint[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]\nOutput\n[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]\n\nExplanation\nATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n                          // and 1 $500 banknote.\natm.withdraw(600);        // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n                          // and 1 $500 banknote. The banknotes left over in the\n                          // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n                          // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600);        // Returns [-1]. The machine will try to use a $500 banknote\n                          // and then be unable to complete the remaining $100,\n                          // so the withdraw request will be rejected.\n                          // Since the request is rejected, the number of banknotes\n                          // in the machine is not modified.\natm.withdraw(550);        // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n                          // and 1 $500 banknote.\n\n&nbsp;\nConstraints:\n\n\n\tbanknotesCount.length == 5\n\t0 &lt;= banknotesCount[i] &lt;= 109\n\t1 &lt;= amount &lt;= 109\n\tAt most 5000 calls in total will be made to withdraw and deposit.\n\tAt least one call will be made to each function withdraw and deposit.\n\n",
        "solution_py": "class ATM:\n    def __init__(self):\n        self.cash = [0] * 5\n        self.values = [20, 50, 100, 200, 500]\n\n    def deposit(self, banknotes_count: List[int]) -> None:\n        for i, n in enumerate(banknotes_count):\n            self.cash[i] += n\n\n    def withdraw(self, amount: int) -> List[int]:\n        res = []\n        for val, n in zip(self.values[::-1], self.cash[::-1]):\n            need = min(n, amount // val)\n            res = [need] + res\n            amount -= (need * val)\n        if amount == 0:\n            self.deposit([-x for x in res])\n            return res\n        else:\n            return [-1]",
        "solution_js": "var ATM = function() {\n    this.bankNotes = new Array(5).fill(0)\n    this.banksNotesValue = [20, 50, 100, 200, 500]\n};\n\n/**\n * @param {number[]} banknotesCount\n * @return {void}\n */\nATM.prototype.deposit = function(banknotesCount) {\n    for (let i = 0; i < 5; i++) {\n       this.bankNotes[i] += banknotesCount[i]\n    }\n    return this.bankNotes\n};\n\n/**\n * @param {number} amount\n * @return {number[]}\n */\nATM.prototype.withdraw = function(amount) {\n    let remain = amount\n    let usedBankNotes = new Array(5).fill(0)\n    let temp = [...this.bankNotes]\n    for (let i = 4; i >= 0; i--) {\n        if (temp[i] > 0 && remain >= this.banksNotesValue[i]) {\n            const bankNote = Math.floor(remain / this.banksNotesValue[i])\n            const maxCanUse = Math.min(temp[i], bankNote)\n            usedBankNotes[i] = maxCanUse\n            temp[i] -= maxCanUse\n\n            remain -= maxCanUse * this.banksNotesValue[i]\n        }\n    }\n\n    if (remain > 0) {\n        return [-1]\n    } else {\n        this.bankNotes = temp\n        return usedBankNotes\n    }\n};\n\n/**\n * Your ATM object will be instantiated and called as such:\n * var obj = new ATM()\n * obj.deposit(banknotesCount)\n * var param_2 = obj.withdraw(amount)\n */",
        "solution_java": "class ATM {\n\tlong[] notes = new long[5];                                                // Note: use long[] instead of int[] to avoid getting error in large testcases\n\tint[] denoms;\n\tpublic ATM() {\n\t\tdenoms = new int[]{ 20,50,100,200,500 };                               // create an array to represent money value.\n\t}\n\n\tpublic void deposit(int[] banknotesCount) {\n\t\tfor(int i = 0; i < banknotesCount.length; i++){\n\t\t\tnotes[i] += banknotesCount[i];                                       // add new deposit money to existing\n\t\t}\n\t}\n\n\tpublic int[] withdraw(int amount) {                 \n\t\tint[] result = new int[5];                                              // create result array to store quantity of each notes we will be using to withdraw \"amount\"\n\t\tfor(int i = 4; i >= 0; i--){\n\t\t\tif(amount >= denoms[i] ){                                              \n\t\t\t\tint quantity = (int) Math.min(notes[i], amount / denoms[i]);     // pick the minimum quanity. because if say, amount/denoms[i] gives 3 but you only have 1 note. so you have to use 1 only instead of 3 \n\t\t\t\tamount -= denoms[i] * quantity;                                 // amount left = 100\n\t\t\t\tresult[i] = quantity;\n\t\t\t}\n\t\t}\n\t\tif(amount != 0){ return new int[]{-1}; }\n\t\tfor(int i = 0; i < 5; i++){  notes[i] -= result[i];  }                   // deduct the quantity we have used.\n\t\treturn result;\n\t}\n}",
        "solution_c": "class ATM {\npublic:\n    long long bank[5] = {}, val[5] = {20, 50, 100, 200, 500};\n    void deposit(vector<int> banknotesCount) {\n        for (int i = 0; i < 5; ++i)\n            bank[i] += banknotesCount[i];\n    }\n    vector<int> withdraw(int amount) {\n        vector<int> take(5);\n        for (int i = 4; i >= 0; --i) {\n            take[i] = min(bank[i], amount / val[i]);\n            amount -= take[i] * val[i];\n        }\n        if (amount)\n            return { -1 };\n        for (int i = 0; i < 5; ++i)\n            bank[i] -= take[i];            \n        return take;\n    }\n};"
    },
    {
        "title": "Number of Enclaves",
        "algo_input": "You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.\n\nA move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.\n\nReturn the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput: 3\nExplanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.\n\n\nExample 2:\n\nInput: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput: 0\nExplanation: All 1s are either on the boundary or can reach the boundary.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 500\n\tgrid[i][j] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def recursion(self, grid, row, col, m, n):\n        if 0<=row<m and 0<=col<n and grid[row][col] == 1:\n            grid[row][col] = 't'\n            self.recursion(grid, row+1, col, m, n)\n            self.recursion(grid, row-1, col, m, n)\n            self.recursion(grid, row, col+1, m, n)\n            self.recursion(grid, row, col-1, m, n)\n    \n    def numEnclaves(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        if not m or not n:\n            return 0\n        # mark all boundary lands and neighbors with 0\n        for row in range(m):\n            self.recursion(grid, row, 0, m, n)\n            self.recursion(grid, row, n-1, m, n)\n            \n        for col in range(n):\n            self.recursion(grid, 0, col, m, m)\n            self.recursion(grid, m-1, col, m, n)\n        \n        result = 0\n        for i in range(m):\n            for j in range(n):\n                if grid[i][j] == 1:\n                    result += 1\n        \n        \n        return result",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar numEnclaves = function(grid) {\n\n    let count = 0, rowLength = grid.length, colLength = grid[0].length\n\n    const updateBoundaryLand = (row,col) => {\n        if(grid?.[row]?.[col]){\n            grid[row][col] = 0\n            updateBoundaryLand(row + 1,col)\n            updateBoundaryLand(row - 1,col)\n            updateBoundaryLand(row,col + 1)\n            updateBoundaryLand(row,col - 1)\n\n        }\n    }\n\n    for(let i=0;i<rowLength;i++){\n        if(grid[i][0] || grid[i][colLength-1]){\n            updateBoundaryLand(i,0)\n            updateBoundaryLand(i,colLength-1)\n        }\n    }\n\n    for(let j=0;j<colLength;j++){\n        if(grid[0][j] || grid[rowLength-1][j]){\n            updateBoundaryLand(0,j)\n            updateBoundaryLand(rowLength-1,j)\n        }\n    }\n\n    for(let i=0;i<rowLength;i++){\n        for(let j=0;j<colLength;j++){\n            if(grid[i][j]) count++\n        }\n    }\n\n    return count\n\n};",
        "solution_java": "    class Solution {\n    public int numEnclaves(int[][] grid) {\n        int maxcount = 0;\n        // if(grid.length==10)\n        // {\n        // return 3;\n        // }\n        for(int i = 0;i<grid.length;i++)\n          {\n              for(int j = 0;j<grid[0].length;j++)\n              {\n                  if(grid[i][j] ==0)\n                  {\n                      continue;\n                  }\n                  if(i==0||i==grid.length-1||j==grid[0].length-1||j==0)\n                  {\n                        dfs(grid,i,j);\n                  }\n\n              }\n        }\n        int count = 0;\n      for(int i = 0;i<grid.length;i++)\n          {\n\n              for(int j = 0;j<grid[0].length;j++)\n              {\n\n                  if(grid[i][j]==1)\n                  {\n                      count++;\n                  }\n\n              }\n        }\n\n        return count;\n    }\n    int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};\n\n      public void dfs(int[][] grid,int row,int col) {\n\n           grid[row][col] = 0;\n             for(int k = 0;k<4;k++)\n         {\n             int rowdash = row+dirs[k][0];\n             int coldash = col+dirs[k][1];\n\n             if(rowdash<0||coldash<0||rowdash>=grid.length||coldash>=grid[0].length||\n              grid[rowdash][coldash]==0)\n             {\n                 continue;\n             }\n\n             if(grid[rowdash][coldash]==1)\n             {\n               dfs(grid,rowdash,coldash);\n             }\n\n         }\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numEnclaves(vector<vector<int>>& grid) {\n        for(int i=0;i<grid.size();i++)\n        {\n            for(int j=0;j<grid[0].size();j++)\n            {\n                if(grid[i][j]==0)\n                    continue;\n                int c=0;\n                if(grid[i][j]==1 && (i*j==0 || i==grid.size()-1 || j==grid[0].size()-1))\n                {\n                    queue<vector<int>> q;\n                    q.push({i,j});\n                    while(!q.empty())\n                    {\n                        vector<int> a;\n                        a=q.front();\n                        q.pop();\n                        grid[a[0]][a[1]]=0;\n                        if(a[0]+1<grid.size() && grid[a[0]+1][a[1]]==1)\n                        {\n                            q.push({a[0]+1,a[1]});\n                            grid[a[0]+1][a[1]]=0;\n                        }\n                        if(a[1]+1<grid[0].size() && grid[a[0]][a[1]+1]==1)\n                        {\n                            q.push({a[0],a[1]+1});\n                            grid[a[0]][a[1]+1]=0;\n                        }\n                        if(a[0]-1>=0 && grid[a[0]-1][a[1]]==1)\n                        {\n                            q.push({a[0]-1,a[1]});\n                            grid[a[0]-1][a[1]]=0;\n                        }\n                        if(a[1]-1>=0 && grid[a[0]][a[1]-1]==1)\n                        {\n                            q.push({a[0],a[1]-1});\n                            grid[a[0]][a[1]-1]=0;\n                        }\n                    }\n                }\n            }\n        }\n        int m=0;\n        for(int i=0;i<grid.size();i++)\n        {\n            for(int j=0;j<grid[0].size();j++)\n            {\n                m+=grid[i][j];\n            }\n        }\n        return m;\n    }\n};"
    },
    {
        "title": "Check if Move is Legal",
        "algo_input": "You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.\n\nEach move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).\n\nA good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:\n\nGiven two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\nOutput: true\nExplanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.\n\n\nExample 2:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\nOutput: false\nExplanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == board[r].length == 8\n\t0 &lt;= rMove, cMove &lt; 8\n\tboard[rMove][cMove] == '.'\n\tcolor is either 'B' or 'W'.\n\n",
        "solution_py": "class Solution:\n    def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n        directions = [False] * 8\n        moves = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),\n                 (-1, -1), (0, -1), (1, -1)]\n        opposite_color = \"W\" if color == \"B\" else \"B\"\n\n        for d in range(8):\n            r, c = rMove + moves[d][0], cMove + moves[d][1]\n            if 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite_color:\n                directions[d] = True\n\n        for step in range(2, 8):\n            if not any(d for d in directions):\n                return False\n            for d in range(8):\n                if directions[d]:\n                    r, c = rMove + step * moves[d][0], cMove + step * moves[d][1]\n                    if 0 <= r < 8 and 0 <= c < 8:\n                        if board[r][c] == color:\n                            return True\n                        elif board[r][c] == \".\":\n                            directions[d] = False\n                    else:\n                        directions[d] = False\n        return False",
        "solution_js": "var checkMove = function(board, rMove, cMove, color) {\n    const moves = [-1, 0, 1];\n    \n    let count = 0;\n    \n    for (let i = 0; i < 3; ++i) {\n        for (let j = 0; j < 3; ++j) {\n            if (i === 1 && j === 1) continue;\n            \n            const rowDir = moves[i];\n            const colDir = moves[j];\n            \n            if (isLegal(rMove, cMove, rowDir, colDir, color, 1)) return true;\n        }\n    }\n    \n    return false;\n      \n    function withinBound(row, col) {\n        return row >= 0 && col >= 0 && row < 8 && col < 8;\n    }\n   \n    function isLegal(currRow, currCol, rowDir, colDir, startColor, length) {\n        if (!withinBound(currRow, currCol)) return false; // we went passed the boundaries\n        if (board[currRow][currCol] === startColor) return length >= 3; // we seen another start color\n        if (board[currRow][currCol] === \".\" && length > 1) return false;\n\n        return isLegal(currRow + rowDir, currCol + colDir, rowDir, colDir, startColor, length + 1);\n    }\n};",
        "solution_java": "class Solution {\n    public boolean checkMove(char[][] board, int rMove, int cMove, char color) {\n\n        int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};\n\n        for(int[] d : direction)\n        {\n            if(dfs(board,rMove,cMove,color,d,1))\n                return true;\n        }\n        return false;\n    }\n\n    public boolean dfs(char[][] board, int r, int c, char color,int[] direcn,int len)\n    {\n\n        int nr = r + direcn[0];\n        int nc = c + direcn[1];\n\n        if( nr<0 || nc<0 || nr>7 || nc>7) return false;\n\n        if(board[nr][nc] == color)\n        {\n            if(len>=2) return true;\n            else\n                return false;\n        }\n        else\n        {\n            if(board[nr][nc] == '.')\n            {  \n                return false;\n            }\n            return dfs(board,nr,nc,color,direcn,len+1);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool inBoard(vector<vector<char>>& board, int x, int y) {\n        return x >= 0 && x < board.size() && y >= 0 && y < board[0].size();\n    }\n    \n    bool isLegal(vector<vector<char>>& board, int x, int y, char color) {\n        if (color == 'B') return board[x][y] == 'W';\n        if (color == 'W') return board[x][y] == 'B';\n        return false;\n    }\n    \n    bool checkMove(vector<vector<char>>& board, int rMove, int cMove, char color) {\n        vector<int> dir_x = {0, 0, 1, 1, 1, -1, -1, -1}, dir_y = {1, -1, 1, -1, 0, 1, -1, 0};\n        for (int i = 0; i < 8; i++) {\n            int x = rMove + dir_x[i], y = cMove + dir_y[i], count = 0;\n            while (inBoard(board, x, y) && isLegal(board, x, y, color)) {\n                x += dir_x[i], y += dir_y[i];\n                count++;\n            }\n            if (inBoard(board, x, y) && board[x][y] == color && count > 0) return true;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Russian Doll Envelopes",
        "algo_input": "You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.\n\nOne envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.\n\nReturn the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\n\nNote: You cannot rotate an envelope.\n\n&nbsp;\nExample 1:\n\nInput: envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput: 3\nExplanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] =&gt; [5,4] =&gt; [6,7]).\n\n\nExample 2:\n\nInput: envelopes = [[1,1],[1,1],[1,1]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= envelopes.length &lt;= 105\n\tenvelopes[i].length == 2\n\t1 &lt;= wi, hi &lt;= 105\n\n",
        "solution_py": "from bisect import bisect_left\nclass Solution:\n    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n        envelopes = sorted(envelopes, key= lambda x:(x[0],-x[1]))\n        rst = []\n        for _,h in envelopes:\n            i = bisect_left(rst,h)\n            if i == len(rst):\n                rst.append(h)\n            else:\n                rst[i] = h\n        return len(rst)",
        "solution_js": "const binarySearch = (arr, target) => {\n    let left = 0;\n    let right = arr.length - 1;\n    \n    while (left <= right) {\n        const mid = Math.floor((left + right) / 2);\n        if (arr[mid] === target) {\n            return mid;\n        }\n        if (arr[mid] < target) {\n            left = mid + 1;\n        } else {\n            right = mid - 1;\n        }\n    }\n    \n    return left;\n}\n\nvar maxEnvelopes = function(envelopes) {\n    envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);\n    const sub = [envelopes[0][1]];\n    \n    for (let envelope of envelopes) {\n        if (envelope[1] > sub[sub.length - 1]) {\n            sub.push(envelope[1]);\n        } else {\n            const replaceIndex = binarySearch(sub, envelope[1]);\n            sub[replaceIndex] = envelope[1];\n        }\n    }\n    \n    return sub.length;\n};",
        "solution_java": "class Solution {\n    public int maxEnvelopes(int[][] envelopes) {\n\t\t//sort the envelopes considering only width\n        Arrays.sort(envelopes, new sortEnvelopes());\n\t\t\n\t\t//Now this is a Longest Increasing Subsequence problem on heights\n\t\t//tempList to store the temporary elements, size of this list will be the length of LIS \n        ArrayList<Integer> tempList = new ArrayList<>();\n        tempList.add(envelopes[0][1]);\n\t\t\n        for(int i=1; i<envelopes.length; i++){\n            if(envelopes[i][1]>tempList.get(tempList.size()-1)){\n                tempList.add(envelopes[i][1]);\n            } else{\n\t\t\t//if the element is smaller than the largest(last because it is sorted) element of tempList, replace the largest smaller element of tempList with it..\n\t\t\t//ex->(assume if envelopes[i][1] is 4), then >>[1,7,8] will become [1,4,8]<<\n                int index = lowerBound(tempList, envelopes[i][1]);\n                tempList.set(index, envelopes[i][1]);\n            }\n        }\n        return tempList.size();\n    }\n    \n\t//finding the index of greatest smaller element \n    public int lowerBound(ArrayList<Integer> list, int search){\n        int start = 0;\n        int end = list.size()-1;\n        while(start<end){\n            int mid = start + (end-start)/2;\n            if(list.get(mid) < search){\n                start = mid+1;\n            } else{\n                end = mid;\n            }\n        }\n        return start;\n    }\n}\n\nclass sortEnvelopes implements Comparator<int[]> {\n    public int compare(int[] a, int[] b){\n        if(a[0] == b[0]){\n\t\t//to ignore the duplicates, we are sorting such that, for same width-> element with \n\t\t//largest height would be considered first, in this way all the other smaller heights would\n\t\t//be ignored\n            return b[1] - a[1];\n        } else{\n            return a[0] - b[0];\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxEnvelopes(vector<vector<int>>& envelopes) {\n        int n = envelopes.size();\n        sort(envelopes.begin(), envelopes.end(), [](auto &l, auto &r)\n             {\n                return l[0] == r[0] ? l[1] > r[1] : l[0] < r[0];\n             });\n        int len = 0;\n        for(auto& cur: envelopes)\n        {\n            if(len==0 || envelopes[len-1][1] < cur[1])\n                envelopes[len++] = cur;\n            else\n                *lower_bound(envelopes.begin(), envelopes.begin()+ len, cur, [](auto &l, auto &r)\n                             {\n                                 return l[1] < r[1];\n                             }) = cur;\n        }\n        return len;\n    }\n};"
    },
    {
        "title": "Maximum Binary String After Change",
        "algo_input": "You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:\n\n\n\tOperation 1: If the number contains the substring \"00\", you can replace it with \"10\".\n\n\t\n\t\tFor example, \"00010\" -&gt; \"10010\"\n\t\n\t\n\tOperation 2: If the number contains the substring \"10\", you can replace it with \"01\".\n\t\n\t\tFor example, \"00010\" -&gt; \"00001\"\n\t\n\t\n\n\nReturn the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.\n\n&nbsp;\nExample 1:\n\nInput: binary = \"000110\"\nOutput: \"111011\"\nExplanation: A valid transformation sequence can be:\n\"000110\" -&gt; \"000101\" \n\"000101\" -&gt; \"100101\" \n\"100101\" -&gt; \"110101\" \n\"110101\" -&gt; \"110011\" \n\"110011\" -&gt; \"111011\"\n\n\nExample 2:\n\nInput: binary = \"01\"\nOutput: \"01\"\nExplanation:&nbsp;\"01\" cannot be transformed any further.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= binary.length &lt;= 105\n\tbinary consist of '0' and '1'.\n\n",
        "solution_py": "class Solution:\n    def maximumBinaryString(self, binary: str) -> str:\n        zero = binary.count('0') # count number of '0'\n        zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists\n        one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's)\n        return f\"{binary[:zero_idx]}{'1'*(zero-1)}{'0'*min(zero, 1)}{'1'*one}\"",
        "solution_js": "/**\n * @param {string} binary\n * @return {string}\n */\nvar maximumBinaryString = function(binary) {\n    /*\n    10 -> 01 allows us to move any zero to left by one position\n    00 -> 10 allows us to convert any consicutive 00 to 10\n    So we can collect all the zeros together then convert them in 1 except for the rightmost 0\n    We will club all the zeros togegher on the rightmost possition, to achieve the biggest value, then covert them into 1 except for the rightmost 0\n    So we need to choose indexOfFirstZero as the starting possition of the group of zeros\n    If there is no 0 then given string is the maximum possible string\n    If there are 1 or more zeros\n        Then there will be only 1 zero in the answer\n        Position of this will be indexOfFirstZero in given string + countOfZeros - 1\n    */\n    let firstZeroIndex=-1,zeroCount=0,ans=\"\";\n    for(let i=0;i<binary.length;i++){\n        if(binary[i]==='0'){\n            zeroCount++;\n            if(firstZeroIndex===-1){\n                firstZeroIndex=i;\n            }\n        }\n    }\n    if(firstZeroIndex==-1){\n        return binary;\n    }\n    let onlyZeroInAns = firstZeroIndex + (zeroCount-1);\n    for(let i=0;i<binary.length;i++){\n        if(i==onlyZeroInAns){\n            ans+=\"0\";\n        }\n        else{\n            ans+=\"1\";\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public String maximumBinaryString(String binary) {\n        int n = binary.length();\n        StringBuffer ans = new StringBuffer(\"\");\n        StringBuffer buffer = new StringBuffer(\"\");\n        int onesAfter1stZero = 0;\n        boolean found1stZero = false;\n        for(int i=0;i<n;i++){\n            if(found1stZero){\n                if(binary.charAt(i)=='0')\n                    ans.append('1');\n                else\n                    buffer.append('1');\n            }\n            else{\n                if(binary.charAt(i)=='0'){\n                    found1stZero = true;\n                    buffer.append('0');\n                }\n                else\n                    ans.append('1');\n            }\n        }\n        \n        ans.append(buffer);\n        return ans.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string maximumBinaryString(string binary) {\n        int n = binary.size();\n        int z_count=0;  //count the number of zeros\n        int z_index=-1; //index of the leftmost zero that is why we start iterating from the right\n        for(int i=n-1;i>=0;i--) {\n         if(binary[i]=='0') {\n             z_count++;\n             z_index = i;\n             binary[i] = '1'; //changing all occurances to 1\n         }\n        }\n        if(z_index!=-1)  //to check if there is atleast 1 zero\n        {\n            binary[z_index+z_count-1] = '0'; //this is the only zero present\n            // -1 because the only zero is also included in zero count \n        }\n        return binary;\n    }\n};"
    },
    {
        "title": "Jump Game III",
        "algo_input": "Given an array of non-negative integers arr, you are initially positioned at start&nbsp;index of the array. When you are at index i, you can jump&nbsp;to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.\n\nNotice that you can not jump outside of the array at any time.\n\n&nbsp;\nExample 1:\n\nInput: arr = [4,2,3,0,3,1,2], start = 5\nOutput: true\nExplanation: \nAll possible ways to reach at index 3 with value 0 are: \nindex 5 -&gt; index 4 -&gt; index 1 -&gt; index 3 \nindex 5 -&gt; index 6 -&gt; index 4 -&gt; index 1 -&gt; index 3 \n\n\nExample 2:\n\nInput: arr = [4,2,3,0,3,1,2], start = 0\nOutput: true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -&gt; index 4 -&gt; index 1 -&gt; index 3\n\n\nExample 3:\n\nInput: arr = [3,0,2,1,2], start = 2\nOutput: false\nExplanation: There is no way to reach at index 1 with value 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 5 * 104\n\t0 &lt;= arr[i] &lt;&nbsp;arr.length\n\t0 &lt;= start &lt; arr.length\n\n",
        "solution_py": "class Solution:\n    def canReach(self, arr: List[int], start: int) -> bool:\n        vis = [0]*len(arr)\n        q = deque() \n        q.append(start) \n        while q:\n            cur = q.popleft() \n            print(cur)\n            vis[cur] = 1\n            if arr[cur] == 0:\n                return True\n            if cur+arr[cur]<len(arr) and vis[cur+arr[cur]] == 0:\n                q.append(cur+arr[cur]) \n            if cur-arr[cur]>=0 and vis[cur-arr[cur]] == 0: \n                q.append(cur-arr[cur])  \n        return False\n\n            ",
        "solution_js": "/**\n * @param {number[]} arr\n * @param {number} start\n * @return {boolean}\n */\nvar canReach = function(arr, start) {\n        let queue = [start];\n        while(queue.length) {\n            let index = queue.shift();\n            if(index >= 0 && index < arr.length && arr[index] >=0 ){\n                if(arr[index] === 0)return true;\n                let move = arr[index]\n                arr[index] = -1   \n                queue.push(index +move , index-move)\n            }\n        }\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean canReach(int[] arr, int start) {\n        int n = arr.length;\n        boolean[] vis = new boolean[n];\n        Queue<Integer> q = new LinkedList<>();\n        q.add(start);\n        while(!q.isEmpty()){\n            int size = q.size();\n            while(size-- > 0){\n                int curr = q.poll();\n                if(vis[curr])\n                    continue;\n                if(arr[curr] == 0)\n                    return true;\n                if(curr+arr[curr] < n)\n                    q.add(curr+arr[curr]);\n                if(curr-arr[curr] >= 0)\n                    q.add(curr-arr[curr]);\n                vis[curr] = true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool dfs(int curr, vector<int>& arr, vector<bool>& visited, int size) {\n\t\t// edge cases - we can't go outside the array size and if the curr index is alredy visited it will repeat same recursion all over again so we can return false in that case too.\n        if(curr < 0 || curr >= size || visited[curr])\n            return false;\n\t\t// If we reach zero we can return true\n        if(arr[curr] == 0)\n            return true;\n        visited[curr] = true;\n\t\t// do dfs in left and right and return two if any of the two paths end up reaching to zero\n        return dfs(curr - arr[curr], arr, visited, size) || \n            dfs(curr + arr[curr], arr, visited, size);\n    }\n    \n    bool canReach(vector<int>& arr, int start) {\n        int size = arr.size();\n        vector<bool> visited(size, false);\n        return dfs(start, arr, visited, size);\n    }\n};"
    },
    {
        "title": "Delete Nodes And Return Forest",
        "algo_input": "Given the root of a binary tree, each node in the tree has a distinct value.\n\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\n\nReturn the roots of the trees in the remaining forest. You may return the result in any order.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\n\nExample 2:\n\nInput: root = [1,2,4,null,3], to_delete = [3]\nOutput: [[1,2,4]]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the given tree is at most 1000.\n\tEach node has a distinct value between 1 and 1000.\n\tto_delete.length &lt;= 1000\n\tto_delete contains distinct values between 1 and 1000.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def traverse(self,node,par):\n        if node:\n            self.parent[node.val] = par\n            self.traverse(node.left,node)\n            self.traverse(node.right,node)\n            \n    def deleteNode(self,toDelete):\n                node = None\n                par = self.parent[toDelete]\n                if par.val == toDelete:\n                    node = par\n                elif par.left and par.left.val == toDelete:\n                    node = par.left\n                elif par.right and par.right.val == toDelete:\n                    node = par.right\n                if node.left:  \n                    self.unique[node.left] = True\n                if node.right: \n                    self.unique[node.right] = True\n                    \n                if node in self.unique: self.unique.pop(node)\n                if node != self.parent[toDelete]:\n                    if par.left == node: par.left = None\n                    else: par.right = None\n\n    \n    def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n        self.parent = {}\n        self.traverse(root,root)\n        self.unique = {root:True}\n        for node in to_delete:\n                self.deleteNode(node)\n        return self.unique",
        "solution_js": "var delNodes = function(root, to_delete) {\n    if(!root) return [];\n\n    to_delete = new Set(to_delete);\n    // know how to delete\n    // while deleting add new nodes to same algo\n    const ans = [];\n    const traverse = (r = root, p = null, d = 0) => {\n        if(!r) return null;\n        if(to_delete.has(r.val)) {\n            if(p != null) {\n                p[d == -1 ? 'left' : 'right'] = null;\n            }\n            traverse(r.left, null, 0);\n            traverse(r.right, null, 0);\n        } else {\n            if(p == null) ans.push(r);\n            traverse(r.left, r, -1);\n            traverse(r.right, r, 1);\n        }\n    }\n    traverse();\n    return ans;\n};",
        "solution_java": "class Solution {\n\n    HashMap<Integer, List<TreeNode>> parent_val_child_nodes_map;\n    HashMap<Integer, TreeNode> child_val_parent_node_map;\n\n    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {\n\n        // initialize map\n        parent_val_child_nodes_map = new HashMap<> ();\n        child_val_parent_node_map = new HashMap<> ();\n\n        // fill map\n        dfsFillMap(root);\n\n        // traverse to_delete to find those that do not have parent after deleting it\n        List<TreeNode> res = new ArrayList<> ();\n\n        // actually deleting nodes\n        for (int delete_val : to_delete) {\n\n            // if the node has parent\n            if (child_val_parent_node_map.containsKey(delete_val)) {\n                TreeNode parent_node = child_val_parent_node_map.get(delete_val);\n                if (parent_node.left != null && parent_node.left.val == delete_val) {\n                    parent_node.left = null;\n                }\n\n                if (parent_node.right != null && parent_node.right.val == delete_val) {\n                    parent_node.right = null;\n                }\n            }\n        }\n\n        // add root to the list first because root has no parent\n        // only if root.val is not in to_delete\n        if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) {\n            res.add(root);\n        }\n\n        // add other nodes that do not have parent\n        for (int delete_val : to_delete) {\n            if (parent_val_child_nodes_map.containsKey(delete_val)) {\n                for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) {\n\n                    // make sure the add node is not in to_delete\n                    int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val;\n                    if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) {\n                        res.add(parent_val_child_nodes_map.get(delete_val).get(i));\n                    }\n                }\n            }\n        }\n\n        return res;\n    }\n\n    public void dfsFillMap(TreeNode root) {\n\n        if (root == null) {\n            return;\n        }\n\n        if (root.left != null) {\n            parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n            parent_val_child_nodes_map.get(root.val).add(root.left);\n\n            child_val_parent_node_map.putIfAbsent(root.left.val, root);\n            dfsFillMap(root.left);\n        }\n\n        if (root.right != null) {\n            parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n            parent_val_child_nodes_map.get(root.val).add(root.right);\n\n            child_val_parent_node_map.putIfAbsent(root.right.val, root);\n            dfsFillMap(root.right);\n        }\n\n        return;\n    }\n}",
        "solution_c": "class Solution {\n    void solve(TreeNode* root,TreeNode* prev,unordered_map<int,int>& mp,int left,vector<TreeNode*>& ans){\n        if(root==NULL)\n            return;\n\n        int f=0;\n\n        solve(root->left,root,mp,1,ans);\n        solve(root->right,root,mp,0,ans);\n\n         if(mp.find(root->val)!=mp.end()){\n            f=1;\n            if(root->right)\n                ans.push_back(root->right);\n                // cout<<root->left->val<<\" \";}\n            if(root->left)\n                ans.push_back(root->left);\n                // cout<<root->right->val<<\" \";}\n        }\n\n        if(f==1){\n            if(left)\n                prev->left=NULL;\n            else\n                prev->right=NULL;\n        }\n    }\n\npublic:\n    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n        if(root==NULL)\n            return {};\n\n        unordered_map<int,int> mp;\n        for(int i=0;i<to_delete.size();i++)\n            mp[to_delete[i]]++;\n\n       vector<TreeNode*> ans;\n\n        TreeNode* dummy=new TreeNode(-1);\n        dummy->left=root;\n\n        solve(dummy->left,dummy,mp,1,ans);\n        if(dummy->left)\n        ans.push_back(root);\n\n        return ans;\n    }\n};\n        ```"
    },
    {
        "title": "Count Good Numbers",
        "algo_input": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).\n\n\n\tFor example, \"2582\" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even.\n\n\nGiven an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.\n\nA digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\n\n\nExample 2:\n\nInput: n = 4\nOutput: 400\n\n\nExample 3:\n\nInput: n = 50\nOutput: 564908303\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1015\n\n",
        "solution_py": "class Solution:\n    def countGoodNumbers(self, n: int) -> int:\n        ans = 1\n        rem = n % 2\n        n -= rem\n        ans = pow(20, n//2, 10**9 + 7)\n        if rem == 1:\n            ans *= 5\n        return ans % (10**9 + 7)",
        "solution_js": "class Math1 {\n\n    // https://en.wikipedia.org/wiki/Modular_exponentiation\n    static modular_pow(base, exponent, modulus) {\n        if (modulus === 1n)\n            return 0n\n        let result = 1n\n        base = base % modulus\n        while (exponent > 0n) {\n            if (exponent % 2n == 1n)\n                result = (result * base) % modulus\n            exponent = exponent >> 1n\n            base = (base * base) % modulus\n        }\n        return result\n    }\n\n}\n\nvar countGoodNumbers = function(n) {\n    // NOTE: 0n, 1n, 2n, 3n, 4n, 5n are numbers in BigInt\n\n    n = BigInt(n); // convert to BigInt, to avoid no rounding issues\n\n    const odds = n / 2n,\n        evens = n - odds,\n        MOD = BigInt(Math.pow(10, 9) + 7)\n\n    // from wikipedia\n    return (Math1.modular_pow(4n, odds, MOD) * Math1.modular_pow(5n, evens, MOD)) % MOD;\n};",
        "solution_java": "class Solution {\n    int mod=(int)1e9+7;\n    public int countGoodNumbers(long n) {\n        long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd\n        long second=n/2;//second power would be n/2 only irrespective of even or odd\n        long mul1=power(5,first)%mod;//5 power n/2\n        long mul2=power(4,second)%mod;//4 power n/2\n        long ans=1;\n        ans=(ans*mul1)%mod;//computing total product\n        ans=(second!=0)?(ans*mul2)%mod:ans;//computing total product\n        return (int)(ans%mod);\n    }\n    public long power(long x,long y){// this method computes pow(x,y) in O(logn) using divide & conquer\n        long temp;\n        if(y==0) return 1;//base case (x power 0 = 1)\n        temp=power(x,y/2);//computing power for pow(x,y/2) -> divide & conquer step\n        if(y%2==0) return (temp*temp)%mod; //using that result of subproblem (2 power 2 = 2 power 1 * 2 power 1)\n        else return (x*temp*temp)%mod;//using that result of subproblem (2 power 3 = 2 power 1 * 2 power 1 * 2)\n\t\t// if y is odd, x power y = x power y/2 * x power y/2 * x\n\t\t// if y is even, x power y = x power y/2 * x power y/2\n    }\n}",
        "solution_c": "// Approach :-> This is question of combination\n// if n as large no....\n// 0 1 2 3 4 5 6 7 8 9 10 11 . . . . . n\n// 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 . . . . . n/4 times of 4 and n/4 times of 5;\n//so calculate 5*4 = 20 -------> 20 * 20 * 20 * . . . . .. n/2 times\n//so calcultae pow(20,n/2)\n// if n is even return pow(20,n/2)\n// if n is odd return 5*pow(20,n/2) beacause if n is odd then one 5 is left out\n// we can easily calculate pow(x,y) in log(y) times\n// durign calculation take care about mod\nclass Solution {\npublic:\n    int mod = 1000000007;\n    long long solve(long long val,long long pow){ // calculatin pow in log(n) time\n        if(pow==0) return 1;\n\n        if(pow%2==0){\n            return solve((val*val)%mod,pow/2)%mod;\n        }\n        else\n            return (val*solve((val*val)%mod,pow/2))%mod;\n\n    }\n    int countGoodNumbers(long long n) {\n        // even means 5 options\n        // odd means 4 option\n\n        long long pow = n/2; // calculate no of times 5*4 means 20 occurs\n\n        long long ans = solve(20,pow); // calculate power(20,pow)\n\n        if(n%2==0){ // if n is even then 5 and 4 occur same no of time n/2\n            return ans;\n        }\n        return ((5*ans) % mod); // if n is odd then 5 occurs n/2+1 times means one extra times so return ans*5 and don't forgot to mod\n    }\n};"
    },
    {
        "title": "Smallest Sufficient Team",
        "algo_input": "In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.\n\nConsider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n\n\n\tFor example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].\n\n\nReturn any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n\nIt is guaranteed an answer exists.\n\n&nbsp;\nExample 1:\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\nExample 2:\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= req_skills.length &lt;= 16\n\t1 &lt;= req_skills[i].length &lt;= 16\n\treq_skills[i] consists of lowercase English letters.\n\tAll the strings of req_skills are unique.\n\t1 &lt;= people.length &lt;= 60\n\t0 &lt;= people[i].length &lt;= 16\n\t1 &lt;= people[i][j].length &lt;= 16\n\tpeople[i][j] consists of lowercase English letters.\n\tAll the strings of people[i] are unique.\n\tEvery skill in people[i] is a skill in req_skills.\n\tIt is guaranteed a sufficient team exists.\n\n",
        "solution_py": "from collections import defaultdict\nfrom functools import lru_cache\n\nclass Solution:\n    def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n        N = len(req_skills)\n        skills = {skill: i for i, skill in enumerate(req_skills)}\n        people_mask = defaultdict(int)\n        for i, cur_skills in enumerate(people):\n            mask = 0\n            for skill in cur_skills:\n                mask |= 1<<skills[skill]\n            people_mask[i] = mask\n        self.path = []\n        self.res = float('inf')\n        self.respath = None\n        @lru_cache(None)\n        #i: people i\n        #l: length of current self.path\n        #mask: mask for current skills\n        def dfs(i, l, mask):\n            if mask == (1<<N) - 1:\n                if l < self.res:\n                    self.res = l\n                    self.respath = self.path[:]\n                return\n            if i == len(people): return\n            if l >= self.res:\n                return\n            dfs(i+1, l, mask)\n            self.path.append(i)\n            if mask & people_mask[i] != people_mask[i]: dfs(i+1, l+1, mask | people_mask[i])\n            self.path.pop()\n        dfs(0,0,0)\n        return self.respath",
        "solution_js": "/**\n * @param {string[]} req_skills\n * @param {string[][]} people\n * @return {number[]}\n */\nvar smallestSufficientTeam = function(req_skills, people) {\n    \n    const skillIndexMap = new Map();\n    \n    req_skills.forEach((skill, index) => skillIndexMap.set(skill,index) );\n    \n    const skillTeamMap = new Map([[0, []]]);\n    \n    people.forEach( (skills, index) => {\n        \n        let hisSkills = 0;\n                \n        for (const skill of skills) {\n            hisSkills |= 1 << skillIndexMap.get(skill);\n        }\n                \n        for (const [currSkill, team] of skillTeamMap) {\n            \n            const totalSkills = currSkill | hisSkills;\n            \n            if (totalSkills === currSkill) {\n                continue;\n            }\n            \n            if (    \n                !skillTeamMap.has(totalSkills) || \n                team.length + 1 < skillTeamMap.get(totalSkills).length\n            ) {                \n                skillTeamMap.set(totalSkills, [...team, index])\n            }             \n        }\n    });\n        \n    return skillTeamMap.get( (1<<req_skills.length) - 1);\n};",
        "solution_java": "class Solution {\n    public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) {\n        int N = 1 << req_skills.length, INF = (int)1e9;\n        int[] parent = new int[N];\n        int[] who = new int[N];\n        int[] dp = new int[N];\n        Arrays.fill(dp, INF);\n        dp[0] = 0;\n        for (int i = 0; i < N; i++){\n            if (dp[i]!=INF){ // valid state \n                for (int k = 0; k < people.size(); k++){\n                    int cur = i;\n                    for (int j = 0; j < req_skills.length; j++){\n                        for (String skill : people.get(k)){\n                            if (req_skills[j].equals(skill)){\n                                cur |= 1<<j; // set the mask\n                                break;\n                            }\n                        }\n                    }\n                    if (dp[cur]>dp[i]+1){ // replace if better\n                        dp[cur]=dp[i]+1;\n                        parent[cur]=i;\n                        who[cur]=k;\n                    }\n                }\n            }\n        }\n        int[] ans = new int[dp[N-1]];\n        for (int i = 0,cur=N-1; i < ans.length; i++){\n            ans[i]=who[cur];\n            cur=parent[cur];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) {\n        vector<int> mask(people.size(), 0);\n        for(int i=0; i<people.size(); i++){\n            for(int j=0; j<req_skills.size(); j++){\n                for(int z=0; z<people[i].size(); z++){\n                    if(people[i][z] == req_skills[j]){\n                        mask[i] += (1<<j);\n                        break;\n                    }\n                }\n            }\n        }\n        vector<long long> dp(1<<req_skills.size(), INT_MAX);\n        vector<vector<int>> save(1<<req_skills.size());\n        dp[0] = 0;\n        for(int i=0; i<(1<<req_skills.size()); i++){\n            for(int j=0; j<mask.size(); j++){\n                int new_mask = i&(i^mask[j]);\n                if(dp[new_mask]+1<dp[i]){\n                    dp[i] = dp[new_mask]+1;\n                    save[i] = save[new_mask];\n                    save[i].push_back(j);\n                }\n            }\n        }\n        return save[(1<<req_skills.size())-1];\n        \n    }\n};"
    },
    {
        "title": "Longest Harmonious Subsequence",
        "algo_input": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.\n\nGiven an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.\n\nA subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,2,2,5,2,3,7]\nOutput: 5\nExplanation: The longest harmonious subsequence is [3,2,2,2,3].\n\n\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: 2\n\n\nExample 3:\n\nInput: nums = [1,1,1,1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t-109 &lt;= nums[i] &lt;= 109\n",
        "solution_py": "\"\"\nfrom collections import Counter\nclass Solution:\n\tdef findLHS(self, nums: List[int]) -> int:\n\t\tcounter=Counter(nums)\n\t\t# values=set(nums)\n\t\tres=0\n\t\t# if len(values)==1:return 0\n\t\tfor num in nums:\n\t\t\tif num+1 in counter or num-1 in counter:\n\t\t\t\tres=max(res,counter[num]+counter.get(num+1,0))\n\t\t\t\tres=max(res,counter[num]+counter.get(num-1,0))\n\n\t\treturn res\n\"\"",
        "solution_js": "var findLHS = function(nums) {\n    let countNumber = {};\n    let result = [];\n    for (let i=0; i<nums.length; i++) {\n        if (!countNumber[nums[i]]) {\n            countNumber[nums[i]] = 1;\n        } else {\n            countNumber[nums[i]]++;\n        }\n    }\n    for (let value of Object.keys(countNumber)) {\n        let count;\n        let current = parseInt(value);\n        if (countNumber[current + 1]) {\n            count = countNumber[current] + countNumber[current + 1];    \n            result.push(count);\n        }\n    };\n    if (result.length === 0) {\n        return 0;\n    }\n    return Math.max(...result);\n};",
        "solution_java": "class Solution {\n    public static int firstOccurence(int[] arr,int target)\n    {\n        int res=-1;\n        int start=0;\n        int end=arr.length-1;\n        while(start<=end)\n        {\n            int mid=start + (end-start)/2;\n            if(arr[mid]==target)\n            {\n                res=mid;\n                end=mid-1;\n            }\n            else if(arr[mid]<target)\n            {\n                start=mid+1;\n            }\n            else\n            {\n                end=mid-1;\n            }\n        }\n        return res;\n    }\n    public static int lastOccurence(int[] arr,int target)\n    {\n        int res=-1;\n        int start=0;\n        int end=arr.length-1;\n        while(start<=end)\n        {\n            int mid=start + (end-start)/2;\n            if(arr[mid]==target)\n            {\n                res=mid;\n                start=mid+1;\n            }\n            else if(arr[mid]<target)\n            {\n                start=mid+1;\n            }\n            else\n            {\n                end=mid-1;\n            }\n        }\n        return res;\n    }\n    public int findLHS(int[] nums) {\n        Arrays.sort(nums);\n        int maxLen=0;\n        for(int i=0;i<nums.length-1;i++)\n        {\n            if(nums[i+1]==nums[i]+1)\n            {\n            int a=firstOccurence(nums,nums[i]);\n            int b=lastOccurence(nums,nums[i]+1);\n            if(b-a+1>maxLen)\n                maxLen=b-a+1;\n            }\n        }\n        return maxLen;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLHS(vector<int>& nums)\n    {\n        map<int,int> m;\n        for(int i=0;i<nums.size();i++)\n        {\n            m[nums[i]]++;\n        }\n        int ans=0;\n        int x=-1,y=0;\n        for(auto i=m.begin();i!=m.end();i++)\n        {\n            if(i->first-x==1)\n            {\n                ans=max(ans,y+i->second);\n            }\n            x=i->first;\n            y=i->second;\n        }\n        return ans;\n\n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Maximum XOR After Operations",
        "algo_input": "You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).\n\nNote that AND is the bitwise AND operation and XOR is the bitwise XOR operation.\n\nReturn the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,2,4,6]\nOutput: 7\nExplanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.\n\nExample 2:\n\nInput: nums = [1,2,3,9,2]\nOutput: 11\nExplanation: Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def maximumXOR(self, nums: List[int]) -> int:\n        res=0\n        for i in nums:\n            res |= i\n        return res",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumXOR = function(nums) {\n  return nums.reduce((acc, cur) => acc |= cur, 0);\n};",
        "solution_java": "class Solution {\n    public int maximumXOR(int[] nums) {\n        int res = 0;\n        for (int i=0; i<nums.length; i++){\n            res |= nums[i];\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumXOR(vector<int>& nums) {\n        int res = 0;\n        for (int i=0; i<nums.size() ; i++){\n            res |= nums[i];\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Equivalent Domino Pairs",
        "algo_input": "Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino.\n\nReturn the number of pairs (i, j) for which 0 &lt;= i &lt; j &lt; dominoes.length, and dominoes[i] is equivalent to dominoes[j].\n\n&nbsp;\nExample 1:\n\nInput: dominoes = [[1,2],[2,1],[3,4],[5,6]]\nOutput: 1\n\n\nExample 2:\n\nInput: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= dominoes.length &lt;= 4 * 104\n\tdominoes[i].length == 2\n\t1 &lt;= dominoes[i][j] &lt;= 9\n\n",
        "solution_py": "import math\nclass Solution:\n    def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n        d=dict()\n        for i in dominoes:\n            i.sort()            #Just to make everything equal and comparable\n            if(tuple(i) in d.keys()):   #In python, lists are unhashable so converted the list into tuples\n                d[tuple(i)]+=1\n            else:\n                d[tuple(i)]=1\n        count=0\n        for x,y in d.items():\n            if(y>1):\n\t\t\t\tcount+=y*(y-1)//2        #To check the number of pairs, if 2 elements pairs is 1,if 3 pair is 3 and so                                                                     on.....formula is n*n-1/2\n        return count\n                ",
        "solution_js": "var numEquivDominoPairs = function(dominoes) {\n    let map = {};\n    let count = 0;\n    for (let [a, b] of dominoes) {\n        if (b > a) {\n            [a, b] = [b, a];\n        }\n        let key = `${a}-${b}`;\n        if (map.hasOwnProperty(key)) {\n            map[key]++;\n            count += map[key];\n        } else {\n            map[key] = 0;\n        }\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    /** Algorithm\n        1. Brute force cannot be used because of the set size.\n        2. Traverse the dominos and group & count them by min-max value.\n           As pieces can be from 1 to 9, means their groups will be from 11 to 99.\n            eg: [1,2] will be the same as [2,1]. Their value is 10 * (min(1,2)) + max(1,2)\n                => 10 * 1 + 2 = 12.\n            so pieces[12]++;\n        3. After finishing traversing, iterate over the counted pieces and if the count is\n          > 1, calculate the combinations of X by 2.\n        4. The formula is n!/ (k! * (n-k)!)\n           As n! can be very large, use the short version of it; (n * (n-1)) / 2. EG n= 40\n           Eg:  40!         simplify this(divide by 38!) 39 * 40\n              --------                                  ---------   \n               2! * (38!)                                   2\n        5. Return the total result      \n    */\n    public int numEquivDominoPairs(int[][] dominoes) {\n        int[] pieces = new int[100];\n        for (int[] domino : dominoes) {\n            pieces[10 * Math.min(domino[0], domino[1]) + Math.max(domino[0], domino[1])]++;\n        }\n        int pairs = 0;\n        for (int i = 11; i <= 99; i++) {\n            if (pieces[i] > 1) {\n                pairs += getCombinations(pieces[i]);\n            }\n        }\n        \n        return pairs;    \n    }\n    \n    private int getCombinations(int n) {\n        return (n * (n-1)) / 2;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numEquivDominoPairs(vector<vector<int>>& dominoes)\n    {\n        map<pair<int,int>,int> m;\n        int ans=0;\n        for(auto &d:dominoes)\n        {\n            int a=min(d[0],d[1]),b=max(d[0],d[1]);\n            m[{a,b}]++;\n        }\n        for(auto &p:m)\n        {\n            int n=p.second;\n            ans+=((n-1)*n)/2;\n        }\n        return ans;\n\n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Divide Two Integers",
        "algo_input": "Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.\n\nThe integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.\n\nReturn the quotient after dividing dividend by divisor.\n\nNote: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.\n\n&nbsp;\nExample 1:\n\nInput: dividend = 10, divisor = 3\nOutput: 3\nExplanation: 10/3 = 3.33333.. which is truncated to 3.\n\n\nExample 2:\n\nInput: dividend = 7, divisor = -3\nOutput: -2\nExplanation: 7/-3 = -2.33333.. which is truncated to -2.\n\n\n&nbsp;\nConstraints:\n\n\n\t-231 &lt;= dividend, divisor &lt;= 231 - 1\n\tdivisor != 0\n\n",
        "solution_py": "class Solution:\n    def divide(self, dividend: int, divisor: int) -> int:\n        # Solution 1 - bitwise operator <<   \n        \"\"\"\n        positive = (dividend < 0) is (divisor < 0)\n        dividend, divisor = abs(dividend), abs(divisor)\n\t\tif divisor == 1:\n            quotient = dividend\n        else:     \n\t\t\tquotient = 0\n\t\t\twhile dividend >= divisor:\n\t\t\t\ttemp, i = divisor, 1\n\t\t\t\twhile dividend >= temp:\n\t\t\t\t\tdividend -= temp\n\t\t\t\t\tquotient += i\n\t\t\t\t\ti <<= 1\n\t\t\t\t\ttemp <<= 1\n\n\t\tif not positive:\n\t\t\treturn max(-2147483648, -quotient)\n\t\telse:\n\t\t\treturn min(quotient, 2147483647)        \n        \"\"\"\n        # Solution 2 - cumulative sum - faster than bitwise \n        positive = (dividend < 0) == (divisor < 0)\n        dividend, divisor = abs(dividend), abs(divisor)      \n        if divisor == 1:\n            quotient = dividend\n        else:            \n            quotient = 0\n            _sum = divisor\n\n            while _sum <= dividend:\n                current_quotient = 1\n                while (_sum + _sum) <= dividend:\n                    _sum += _sum\n                    current_quotient += current_quotient\n                dividend -= _sum\n                _sum = divisor\n                quotient += current_quotient            \n        if not positive:\n            return max(-2147483648, -quotient)\n        else:\n            return min(quotient, 2147483647)    ",
        "solution_js": "var divide = function(dividend, divisor) {\n    if (dividend == -2147483648 && divisor == -1) return 2147483647;\n    let subdividend = Math.abs(dividend)\n    let subdivisor = Math.abs(divisor)\n    let string_dividend = subdividend.toString()\n    let i = 0\n    let ans=0\n    let remainder = 0\n    while(i<string_dividend.length){\n        remainder =remainder*10+Number(string_dividend[i])\n        let quotient = Math.floor(remainder/subdivisor)\n        ans = ans *10 + quotient\n        remainder = remainder - quotient*subdivisor\n        i++;\n    }\n    if((dividend >0 && divisor <0) || (dividend <0 && divisor >0)) return 0-ans\n    return ans\n};",
        "solution_java": "class Solution {\n    public int divide(int dividend, int divisor) {\n        if(dividend == 1<<31 && divisor == -1){\n            return Integer.MAX_VALUE;\n        }\n        boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false;\n        \n        dividend = Math.abs(dividend);\n        divisor = Math.abs(divisor);\n        \n        int result = 0;\n        while(dividend - divisor >= 0){\n            int count = 0;\n            while(dividend - (divisor << 1 << count) >= 0){\n                count++;\n            }\n            result += 1 <<count;\n            dividend -= divisor << count;\n        }\n        return sign ? result : -result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        if (dividend == INT_MIN && divisor == -1) {\n            return INT_MAX;\n        }\n        long dvd = labs(dividend), dvs = labs(divisor), ans = 0;\n        int sign = dividend > 0 ^ divisor > 0 ? -1 : 1;\n        while (dvd >= dvs) {\n            long temp = dvs, m = 1;\n            while (temp << 1 <= dvd) {\n                temp <<= 1;\n                m <<= 1;\n            }\n            dvd -= temp;\n            ans += m;\n        }\n        return sign * ans;\n    }\n};"
    },
    {
        "title": "Trapping Rain Water",
        "algo_input": "Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n\n&nbsp;\nExample 1:\n\nInput: height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\nExplanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n\n\nExample 2:\n\nInput: height = [4,2,0,3,2,5]\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\tn == height.length\n\t1 &lt;= n &lt;= 2 * 104\n\t0 &lt;= height[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def trap(self, a: List[int]) -> int:\n        l=0\n        r=len(a)-1\n        maxl=0\n        maxr=0\n        res=0\n\n        while (l<=r):\n            if a[l]<=a[r]:\n                if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >=\n                else: res+=maxl-a[l] #adding captured water when maxl>a[l]\n                l+=1\n            else:\n                if a[r]>=maxr: maxr=a[r]\n                else: res+=maxr-a[r]\n                r-=1\n        return res",
        "solution_js": "var trap = function(height) {\n    let left = 0, right = height.length - 1;\n    let hiLevel = 0, water = 0;\n    while(left <= right) {\n        let loLevel = height[height[left] < height[right] ? left++ : right--];\n        hiLevel = Math.max(hiLevel, loLevel);\n        water += hiLevel - loLevel ;\n    }\n    return water;\n};",
        "solution_java": "class Solution {\n    public int trap(int[] height) {\n        int left = 0;\n        int right = height.length - 1;\n        \n        int l_max = height[left];\n        int r_max = height[right];\n        int res = 0;\n        \n        while(left < right) {\n            if(l_max < r_max) {\n                left+=1;\n                l_max = Math.max(l_max, height[left]);\n                res += l_max - height[left];\n            }\n            else{\n                right-=1;\n                r_max = Math.max(r_max, height[right]);\n                res += r_max - height[right];\n            }\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int trap(vector<int>& height) {\n        int left=0,right=height.size()-1;\n        int maxleft=0,maxright=0;\n        int res=0;\n        while(left<=right){\n            if(height[left]<=height[right]){\n                if(height[left]>=maxleft)maxleft=height[left];\n                else res += maxleft-height[left];\n                left++;\n            }else{\n                 if(height[right]>=maxright)maxright=height[right];\n                else res += maxright-height[right];\n                right--;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Calculate Digit Sum of a String",
        "algo_input": "You are given a string s consisting of digits and an integer k.\n\nA round can be completed if the length of s is greater than k. In one round, do the following:\n\n\n\tDivide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.\n\tReplace each group of s with a string representing the sum of all its digits. For example, \"346\" is replaced with \"13\" because 3 + 4 + 6 = 13.\n\tMerge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.\n\n\nReturn s after all rounds have been completed.\n\n&nbsp;\nExample 1:\n\nInput: s = \"11111222223\", k = 3\nOutput: \"135\"\nExplanation: \n- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n  ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n&nbsp; So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n&nbsp; Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n&nbsp; So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length &lt;= k, so we return \"135\" as the answer.\n\n\nExample 2:\n\nInput: s = \"00000000\", k = 3\nOutput: \"000\"\nExplanation: \nWe divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\t2 &lt;= k &lt;= 100\n\ts consists of digits only.\n\n",
        "solution_py": "class Solution:\n    def digitSum(self, s: str, k: int) -> str:\n        while len(s) > k:\n            set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n            s = ''\n            for e in set_3:\n                val = 0\n                for n in e:\n                    val += int(n)\n                s += str(val)\n        return s",
        "solution_js": "var digitSum = function(s, k) {\n    while (s.length > k) {\n        let newString = \"\";\n        for (let i = 0; i < s.length; i += k)\n            newString += s.substring(i, i + k).split(\"\").reduce((acc, val) => acc + (+val), 0);\n\n        s = newString;\n    }\n\n    return s;\n};",
        "solution_java": "class Solution {\n    public String digitSum(String s, int k) {\n        while(s.length() > k) s = gen(s,k);\n        return s;\n    }\n    public String gen(String s,int k){\n        String res = \"\";\n        for(int i=0;i < s.length();){\n            int count = 0,num=0;\n            while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++));\n            res+=num;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string digitSum(string s, int k) {\n        \n        if(s.length()<=k)\n            return s;\n        \n        string ans=\"\";\n        int sum=0,temp=k;\n        int len = s.length();\n        for(int i=0;i<len;i++){\n            sum += (s[i] -'0');\n            temp--;\n            if(temp==0){\n                ans+= to_string(sum);\n                temp=k;\n                sum=0;\n            }\n        }\n        if(temp!=k){\n        ans+= to_string(sum);\n        }\n        if(ans.length()>k)\n            ans = digitSum(ans,k);\n        return ans;\n    }\n};"
    },
    {
        "title": "Best Time to Buy and Sell Stock II",
        "algo_input": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day.\n\nOn each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.\n\nFind and return the maximum profit you can achieve.\n\n&nbsp;\nExample 1:\n\nInput: prices = [7,1,5,3,6,4]\nOutput: 7\nExplanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.\n\n\nExample 2:\n\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.\n\n\nExample 3:\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 3 * 104\n\t0 &lt;= prices[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def maxProfit(self, prices: List[int]) -> int:\n        n=len(prices)\n        ans=0\n        want=\"valley\"\n        for i in range(n-1):\n            if want==\"valley\" and prices[i]<prices[i+1]:\n                ans-=prices[i]\n                want=\"hill\"\n            elif want==\"hill\" and prices[i]>prices[i+1]:\n                ans+=prices[i]\n                want=\"valley\"\n        if want==\"hill\":\n            ans+=prices[-1]\n        return ans",
        "solution_js": "/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n    let lowestNum = prices[0];\n    let highestNum = prices[0];\n    let profit = highestNum - lowestNum;\n\n    for(var indexI=1; indexI<prices.length; indexI++) {\n      if(prices[indexI] < prices[indexI - 1]) {\n          lowestNum = prices[indexI];\n      }\n      if(prices[indexI] > lowestNum) {\n        lowestNum = prices[indexI - 1];\n        profit = profit + prices[indexI] - lowestNum;\n          highestNum = prices[indexI];\n      }\n    }\n\n    return profit;\n};",
        "solution_java": "class Solution {\n    public int maxProfit(int[] prices) {\n        int n = prices.length,profit = 0;\n        for(int i=0;i<n-1;i++){\n            if(prices[i+1]>prices[i]){\n                profit += prices[i+1]-prices[i];\n            }\n        }\n        return profit;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int n=prices.size();\n        int ans=0,currMin=prices[0];\n        for(int i=1;i<n;i++){\n            while(i<n && prices[i]>prices[i-1]){\n                i++;\n            }\n            ans+=(prices[i-1]-currMin);\n            currMin=prices[i];\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Count Common Words With One Occurrence",
        "algo_input": "Given two string arrays words1 and words2, return the number of strings that appear exactly once in each&nbsp;of the two arrays.\n\n&nbsp;\nExample 1:\n\nInput: words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\nOutput: 2\nExplanation:\n- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.\n\n\nExample 2:\n\nInput: words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\nOutput: 0\nExplanation: There are no strings that appear in each of the two arrays.\n\n\nExample 3:\n\nInput: words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\nOutput: 1\nExplanation: The only string that appears exactly once in each of the two arrays is \"ab\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words1.length, words2.length &lt;= 1000\n\t1 &lt;= words1[i].length, words2[j].length &lt;= 30\n\twords1[i] and words2[j] consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n\tdef countWords(self, words1: List[str], words2: List[str]) -> int:\n\t\tcount = Counter(words1 + words2)\n\t\treturn len([word for word in count if count[word] == 2 and word in words1 and word in words2])",
        "solution_js": "var countWords = function(words1, words2) {\n    const map1 = new Map();\n    const map2 = new Map();\n    let count = 0;\n\n    for (const word of words1) {\n        map1.set(word, map1.get(word) + 1 || 1);\n    }\n    for (const word of words2) {\n        map2.set(word, map2.get(word) + 1 || 1);\n    }\n    for (const word of words1) {\n        if (map1.get(word) === 1 && map2.get(word) === 1) count++;\n    }\n\n    return count;\n};",
        "solution_java": "class Solution\n{\n    public int countWords(String[] words1, String[] words2)\n    {\n        HashMap<String, Integer> map1 = new HashMap<>();\n        HashMap<String, Integer> map2 = new HashMap<>();\n\t\t\n        for(String word : words1)\n            map1.put(word,map1.getOrDefault(word,0)+1);\n        for(String word : words2)\n            map2.put(word,map2.getOrDefault(word,0)+1);\n\t\t\t\n        int count = 0;\n        for(String word : words1)\n            if(map1.get(word) == 1 && map2.getOrDefault(word,0) == 1)\n                count++;\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countWords(vector<string>& words1, vector<string>& words2) {\n        unordered_map<string, int> freq1, freq2;\n        for (auto& s : words1) ++freq1[s];\n        for (auto& s : words2) ++freq2[s];\n        int ans = 0;\n        for (auto& [s, v] : freq1)\n            if (v == 1 && freq2[s] == 1) ++ans;\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Absolute Difference",
        "algo_input": "Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.\n\nReturn a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\n\n\n\ta, b are from arr\n\ta &lt; b\n\tb - a equals to the minimum absolute difference of any two elements in arr\n\n\n&nbsp;\nExample 1:\n\nInput: arr = [4,2,1,3]\nOutput: [[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\n\nExample 2:\n\nInput: arr = [1,3,6,10,15]\nOutput: [[1,3]]\n\n\nExample 3:\n\nInput: arr = [3,8,-10,23,19,-4,-14,27]\nOutput: [[-14,-10],[19,23],[23,27]]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 105\n\t-106 &lt;= arr[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n        arr.sort()\n        diff=float(inf)\n        for i in range(0,len(arr)-1):\n            if arr[i+1]-arr[i]<diff:\n                diff=arr[i+1]-arr[i]\n        lst=[]\n        for i in range(0,len(arr)-1):\n            if arr[i+1]-arr[i]==diff:\n                lst.append([arr[i],arr[i+1]])\n        return lst",
        "solution_js": "var minimumAbsDifference = function(arr) {\n    arr.sort((a, b) => a - b)\n    let minDif = Infinity\n    let res = []\n\n    for (let i = 0; i < arr.length - 1; i++) {\n        let currDif = Math.abs(arr[i + 1] - arr[i])\n        if (currDif < minDif) minDif = currDif\n    }\n\n    for (let i = 0; i < arr.length - 1; i++) {\n        let dif = Math.abs(arr[i + 1] - arr[i])\n        if (dif === minDif) {\n            res.push([arr[i], arr[i + 1]])\n        }\n    }\n    return res\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> minimumAbsDifference(int[] arr) {\n        List<List<Integer>> ans=new ArrayList<>();\n        Arrays.sort(arr);\n        int min=Integer.MAX_VALUE;\n        for(int i=0;i<arr.length-1;i++){\n            int diff=Math.abs(arr[i]-arr[i+1]);\n            if(diff<min)\n            {\n            min=diff;\n            }\n        }\n        for(int i=0;i<arr.length-1;i++){\n            int diff=Math.abs(arr[i]-arr[i+1]);\n            if(diff==min){\n                 List<Integer> pair=new ArrayList<>(2);\n                pair.add(arr[i]);\n                pair.add(arr[i+1]);\n                ans.add(pair);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {\n        sort(arr.begin(),arr.end());\n        int diff=INT_MAX;\n        for(int i=1;i<arr.size();i++){\n            diff=min(diff,abs(arr[i]-arr[i-1]));\n        }\n        vector<vector<int>>v;\n        for(int i=1;i<arr.size();i++){\n            if(abs(arr[i]-arr[i-1])==diff){\n                int a=min(arr[i],arr[i-1]);\n                int b=max(arr[i],arr[i-1]);\n                v.push_back({a,b});\n            }  \n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Graph Connectivity With Threshold",
        "algo_input": "We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true:\n\n\n\tx % z == 0,\n\ty % z == 0, and\n\tz &gt; threshold.\n\n\nGiven the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly.&nbsp;(i.e. there is some path between them).\n\nReturn an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\nOutput: [false,false,true]\nExplanation: The divisors for each number:\n1:   1\n2:   1, 2\n3:   1, 3\n4:   1, 2, 4\n5:   1, 5\n6:   1, 2, 3, 6\nUsing the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4]   1 is not connected to 4\n[2,5]   2 is not connected to 5\n[3,6]   3 is connected to 6 through path 3--6\n\n\nExample 2:\n\nInput: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\nOutput: [true,true,true,true,true]\nExplanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n\n\nExample 3:\n\nInput: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\nOutput: [false,false,false,false,false]\nExplanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 104\n\t0 &lt;= threshold &lt;= n\n\t1 &lt;= queries.length &lt;= 105\n\tqueries[i].length == 2\n\t1 &lt;= ai, bi &lt;= cities\n\tai != bi\n\n",
        "solution_py": "class Solution:\n    def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n        parent = list(range(n+1))\n        def find(i):\n            if parent[i] != i:\n                parent[i] = find(parent[i])\n            return parent[i]\n        def union(i,j):\n            parent[find(i)] = find(j)\n        if not threshold: return [True]*len(queries)\n        for i in range(1, n+1):\n            for j in range(2*i, n+1, i):\n                if i > threshold: union(i,j)\n        return [find(i) == find(j) for i,j in queries]",
        "solution_js": "var areConnected = function(n, threshold, queries) {\n\n    // if(gcd(a,b)>threshold), a and b are connected\n\n    // 2 is connected with : 2, 4,6,8,10,12,14,16, (gcd(2,y)=2)\n    // 3 is connected with : 3,6,9,12,... (gcd(3,y)=3)\n    // 4 is connected with : 4,8,12,16,20,24,28, (gcd(4,y)=4)\n    // 6 is connected with : 6,12,18...,cos (gcd(6,y)=6)\n    // 5 is connected with : 10,15,20,25,...n cos (gcd(5,y)=6)\n    // etc\n\n    let dsu=new UnionFind(n+1) //to map n=>n (no node 0 on my question)\n\n    for (let node = threshold+1; node <=n; node++) //basically this ensures that the road exists\n        //cos gcd(node,secondnode)==node >threshold\n        for (let secondnode = node+node; secondnode <=n; secondnode+=node)\n            dsu.union(node,secondnode)\n\n    return queries.map(([a,b])=>dsu.sameGroup(a,b))\n};\nclass UnionFind {\n\n    constructor(size){\n        //the total count of different elements(not groups) in this union find\n        this.count=size\n        //tracks the sizes of each of the components(groups/sets)\n        //groupsize[a] returns how many elements the component with root a has\n        this.groupSize=[...Array(size)]\n        //number of components(groups) in the union find\n        this.numComponents=size\n        //points to the parent of i, if parent[i]=i, i is a root node\n        this.parent=[...Array(size)] //which is also the index of the group\n\n        //put every element into its own group\n        // rooted at itself\n        for (let i = 0; i < size; i++) {\n            this.groupSize[i]=i\n            this.parent[i]=i\n        }\n    }\n\n    //returns to which component (group) my element belongs to\n    // (n) --Amortized constant time\n    // Update: Also compresses the paths so that each child points to its\n    // parent\n    find(element){\n        let root=element\n        //find the parent of the group the elemnt belongs to\n        // When root===parent[root] is always the parent of that group (root)\n        while(root!=this.parent[root])\n            root=this.parent[root]\n\n        // Compression, point the element to its parent if its not already pointed\n        // Tldr: Not only do I point my element to its actual root, i point any\n        // inbetween elements to that root aswell\n        while(element!=root){\n            let next=this.parent[element]\n            this.parent[element]=root\n            element=next\n        }\n\n        return root\n    }\n\n    //Unifies the sets containing A and B\n    // if not already unified\n    // (n) --Amortized constant time\n    union(A,B){\n        let root1=this.find(A) //parent of A\n            ,root2=this.find(B) //parent of B\n        if(root1===root2) //already unified\n            return\n        // I want to put the set with fewer elements\n        // to the one with more elemenets\n        if(this.groupSize[root1]<this.groupSize[root2]){\n            this.groupSize[root2]+=this.groupSize[root1]\n            this.parent[root1]=this.parent[root2]\n        }\n        else {\n            this.groupSize[root1]+=this.groupSize[root2]\n            this.parent[root2]=this.parent[root1]\n        }\n\n        this.numComponents-- //cos 1 less group, since i merged 2\n    }\n\n    //same parent=>samegroup\n    sameGroup=(A,B)=>this.find(A)==this.find(B)\n\n    //essentially the groupSize of its parent's group\n    sizeOfGroup=(A)=>this.groupSize[this.find(A)]\n\n}",
        "solution_java": "//Solving the problem using Disjoint Set Union Find approach\n\nclass Solution {\n\n    public int find(int x){\n\n        if(parent[x] == x)\n            return x;\n\n        //Optimising by placing the same parent for all the elements to reduce reduntant calls\n        return parent[x] = find(parent[x]);\n    }\n\n    public void union(int a, int b){\n\n        a = find(a);\n        b = find(b);\n\n        //Using Rank optimisation\n        if(rank[a] > rank[b]){\n            parent[b] = a;\n            rank[a] += rank[b];\n        }\n\n        else{\n            parent[a] = b;\n            rank[b] += rank[a];\n        }\n\n        //parent[b] = a;\n    }\n\n    int parent[];\n    int rank[];\n    public List<Boolean> areConnected(int n, int threshold, int[][] queries) {\n\n        List<Boolean> ans = new ArrayList<Boolean>();\n        parent = new int[n+1];\n        rank = new int[n+1];\n\n        for(int i=1; i<=n; i++){\n            //Each element is its own parent\n            parent[i] = i;\n            //At beginning each element has rank 1\n            rank[i] = 1;\n        }\n\n        // Finding the possible divisors with pairs above given threshold\n        for(int th = threshold+1; th<=n; th++){\n\n            int mul = 1;\n            while(mul * th <= n){\n                //If possible pair then making a union of those paired element\n                union(th, mul*th);\n                mul++;\n            }\n        }\n\n        //Generating ans for all possible queries\n        for(int[] query : queries){\n            ans.add((find(query[0]) == find(query[1])));\n        }\n        return ans;\n    }\n}",
        "solution_c": "// DSU Class Template\nclass DSU {\n    vector<int> parent, size;\npublic:\n\n    DSU(int n) {\n        for(int i=0; i<=n; i++) {\n            parent.push_back(i);\n            size.push_back(1);\n        }\n    }\n\n    int findParent(int num) {\n        if(parent[num] == num) return num;\n        return parent[num] = findParent(parent[num]);\n    }\n\n    void unionBySize(int u, int v) {\n        int parU = findParent(u);\n        int parV = findParent(v);\n\n        if(parU == parV) return;\n\n        if(size[parU] < size[parV]) {\n            parent[parU] = parV;\n            size[parV] += size[parU];\n        }\n        else {\n            parent[parV] = parU;\n            size[parU] += size[parV];\n        }\n    }\n};\n\nclass Solution {\npublic:\n    vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) {\n\n        DSU dsu(n);\n\n        // Make connections with its multiple\n        for(int i=threshold+1; i<=n; i++) {\n            int j = 1;\n            while(i*j <= n) {\n                dsu.unionBySize(i, i*j);\n                j++;\n            }\n        }\n\n        vector<bool> res;\n        for(auto& query : queries) {\n            int u = query[0];\n            int v = query[1];\n\n            // Check if both cities belong to same component or not\n            if(dsu.findParent(u) == dsu.findParent(v)) res.push_back(true);\n            else res.push_back(false);\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Counting Bits",
        "algo_input": "Given an integer n, return an array ans of length n + 1 such that for each i (0 &lt;= i &lt;= n), ans[i] is the number of 1's in the binary representation of i.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: [0,1,1]\nExplanation:\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n\n\nExample 2:\n\nInput: n = 5\nOutput: [0,1,1,2,1,2]\nExplanation:\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n3 --&gt; 11\n4 --&gt; 100\n5 --&gt; 101\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 105\n\n\n&nbsp;\nFollow up:\n\n\n\tIt is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?\n\tCan you do it without using any built-in function (i.e., like __builtin_popcount in C++)?\n\n",
        "solution_py": "class Solution:\n    def countBits(self, n: int) -> List[int]:\n        # We know that all exponential values of two have 1 bit turned on, the rest are turned off.\n        # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed \n        # into smaller numbers where we already have found the # of 1s, for example.\n        # F(3) = F(2^1) + F(1) = 1 + 1 = 3\n        # F(4) = F(2^2) + F(0) = 1 + 0. ( Even thought we havent defined F(4) = F(2^2), by the previous established)\n        # comment, we can safely say that all F(2^X) has only 1 bit so thats where F(4) would be = 1\n        # F(5) = F(2^2) + F(1) = 1 + 1 = 2\n        # F(6) = F(2^2) + F(2) = F(4) + F(2) = 1 + 1\n        # The relation countinues for all following numbers\n        \n        # This solution is O(N)\n        # With O(1) extra space ( considering dp is the returned answer )\n        \n        dp = [0]\n\t\t\n        for i in range(1, n + 1):\n            exponent = int(math.log(i) / math.log(2))\n            num = 2**exponent\n            decimal = i % (num)\n            if num == i:\n                dp.append(1)\n            else:\n                dp.append(dp[num] + dp[decimal])\n        return(dp)",
        "solution_js": "var countBits = function(n) {\n    if (n === 0) return [0];\n\n    const ans = new Array(n + 1).fill(0);\n\n    let currRoot = 0;\n    for (let idx = 1; idx <= n; idx++) {\n        if ((idx & (idx - 1)) === 0) {\n            ans[idx] = 1;\n            currRoot = idx;\n            continue;\n        }\n\n        ans[idx] = 1 + ans[idx - currRoot];\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n\n    public void count(int n, int[] a, int k)\n    {\n        int i;\n        for(i=k ; i<k*2 && i<=n; i++)\n            a[i]=a[i-k]+1;\n        if(i==n+1)\n            return;\n        count(n,a,k*2);\n    }\n    public int[] countBits(int n) {\n        int a[] = new int[n+1];\n        a[0]=0;\n        count(n,a,1);\n        return a;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    int countones( int n ){\n        int count = 0;\n        while(n){\n            count ++;\n            n = n & ( n-1 );\n        }\n        return count;\n    }\npublic:\n    vector<int> countBits(int n) {\n        vector<int> ans;\n        for( int i = 0; i <= n; i++ ){\n            int x = countones(i);\n            ans.push_back(x);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Incompatibility",
        "algo_input": "You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.\n\nA subset's incompatibility is the difference between the maximum and minimum elements in that array.\n\nReturn the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.\n\nA subset is a group integers that appear in the array with no particular order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,1,4], k = 2\nOutput: 4\nExplanation: The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n\nExample 2:\n\nInput: nums = [6,3,8,1,3,1,2,2], k = 4\nOutput: 6\nExplanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n\n\nExample 3:\n\nInput: nums = [5,3,3,6,3,3], k = 3\nOutput: -1\nExplanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 16\n\tnums.length is divisible by k\n\t1 &lt;= nums[i] &lt;= nums.length\n\n",
        "solution_py": "class Solution(object):\n    def minimumIncompatibility(self, nums, k):\n        nums.sort(reverse = True)\n        upperbound = len(nums) // k\n        arr = [[] for _ in range(k)]\n        self.res = float('inf')\n        def assign(i):\n            if i == len(nums):\n                self.res = min(self.res, sum(arr[i][0]-arr[i][-1] for i in range(k)))\n                return True\n            flag = 0\n            for j in range(k):\n                if not arr[j] or (len(arr[j]) < upperbound and arr[j][-1] != nums[i]):\n                    arr[j].append(nums[i])\n                    if assign(i+1):\n                        flag += 1\n                    arr[j].pop()\n                if flag >= 2: break\n            return flag != 0\n        if max(collections.Counter(nums).values()) > k: return -1\n        assign(0)\n        return self.res",
        "solution_js": "////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////\n\n\nvar minimumIncompatibility = function(nums, k) {\n\t////// FROM HERE TO\n    if (nums.length === k) return 0;\n    \n    const maxInBucket = nums.length / k;\n    const freqCount = {};\n    for (const n of nums) {\n        if (freqCount[n]) {\n            if (freqCount[n] === k) {\n                return -1\n            } else {\n                freqCount[n]++\n            }\n        } else {\n            freqCount[n] = 1\n        }\n    }\n\t/////// HERE is just saving time\n    \n\t// create a cache (aka memo, dp, dynamic programming, momoization)\n    const cache = {}\n\t// create a mask to know when all the indicies are used\n    const allIndiciesUsedMask = 2 ** nums.length - 1;\n    \n    const dfs = (usedIndicesBitMask) => {\n\t    // if we have used all the indicies then we return 0\n        if (usedIndicesBitMask === allIndiciesUsedMask) {\n            return 0;\n        }\n\t\t// if we have seen this combination before, return the\n\t\t// result that was calculated before\n\t\t// otherwise do the hard work LOL\n        if (cache[usedIndicesBitMask]) {\n            return cache[usedIndicesBitMask];\n        }\n        \n\t\t// find all the indicies that are available to be used\n\t\t// skip duplicate values\n        const valsToIndices = {};\n        for (let i = 0; i < nums.length; i++) {\n            const indexMask = 1 << i;\n            if (usedIndicesBitMask & indexMask) continue;\n            const value = nums[i];\n            if (!valsToIndices.hasOwnProperty(value)) {\n                valsToIndices[value] = i;\n            }\n        }\n        const indicesAvailable = Object.values(valsToIndices);\n\n        // this is hard to explain but it's basically calculating the minimum\n\t\t// cost while marking the indicies that are going to be used for each\n\t\t// combination\n        let minIncompatibilityCost = Infinity;\n        const combinations = createCombinations(indicesAvailable, maxInBucket);\n        for (const indices of combinations) {\n            let nextMask = usedIndicesBitMask;\n            let minVal = Infinity;\n            let maxVal = -Infinity;\n            for (const index of indices) {\n                minVal = Math.min(minVal, nums[index]);\n                maxVal = Math.max(maxVal, nums[index]);\n                nextMask = nextMask | (1 << index);\n            }\n            const incompatibilityCost = maxVal - minVal;\n            minIncompatibilityCost = \n                Math.min(minIncompatibilityCost, dfs(nextMask) + incompatibilityCost);\n        }\n        return cache[usedIndicesBitMask] = minIncompatibilityCost;\n    }\n    return dfs(0);\n};\n\nfunction createCombinations(indices, len) {\n    const combinations = [];\n    \n    if (indices.length < len) {\n        return combinations;\n    }\n    \n    const stack = [[[], 0]];\n    while (stack.length > 0) {\n        let [combi, i] = stack.pop();\n        for (; i < indices.length; i++) {\n            const combination = [...combi, indices[i]];\n            if (combination.length === len) {\n                combinations.push(combination);\n            } else {\n                stack.push([combination, i + 1]);\n            }\n        }\n    }\n    \n    return combinations;\n}",
        "solution_java": "class Solution {\n    public int minimumIncompatibility(int[] nums, int k) {\n        Arrays.sort(nums);\n        k=nums.length/k;\n        int n = nums.length,INF=100;\n        int[][] dp = new int[1<<n][n];\n        for (int[] d : dp){\n            Arrays.fill(d, INF);\n        }\n        for (int i=0;i<n;i++){\n            dp[1<<i][i]=0;\n        }\n        for (int i = 1; i < 1<<n; i++){\n            int c = Integer.bitCount(i);\n            for (int j=0;j<n&&c%k==0;j++){\n                for (int w=0;w<n&&(i&1<<j)>0;w++){\n                    if ((i&1<<w)==0){\n                        dp[i|1<<w][w]=Math.min(dp[i|1<<w][w], dp[i][j]);\n                    }\n                }\n            }\n            for (int j=0;j<n&&c%k!=0;j++){\n                for (int w=j+1;w<n&&(i&1<<j)>0;w++){\n                    if ((i&1<<w)==0&&nums[w]!=nums[j]){\n                        dp[i|1<<w][w]=Math.min(dp[i|1<<w][w], dp[i][j]+nums[w]-nums[j]);\n                    }\n                }\n            }\n        }\n        int ans = Arrays.stream(dp[(1<<n)-1]).min().getAsInt();\n        return ans==INF?-1:ans;\n    }\n}",
        "solution_c": "const int INF = 1e9;\n\nclass Solution {\npublic:\n    int minimumIncompatibility(vector<int>& nums, int k) {\n        int i, n = nums.size(), subset_size = n / k;\n        sort(nums.begin(), nums.end());\n\n        // Pre-calculate the range (max - min) for each subset of nums\n        // Note that there are (1 << n) subsets (i.e. 2 ^ n subsets) of an array of size n\n        vector<int> range(1 << n, INF);\n\n        // Each mask represents every possible subset of elements in num (so, \"mask\" == \"subset\")\n        // Specifically, if the bit at position i of mask is set to 1, then we include that number in the subset\n        for(int mask = 1; mask < (1 << n); mask++) {\n            int small = -1, big = -1;\n            bool dup = false;\n\n            // Identify elements that belong to this subset, find the largest & smallest, check for duplicates\n            // Recall that this array was sorted in the beginning of the function\n            for(i=0; i<n && !dup; i++)\n                if(mask & (1 << i)) {\n                    if(small == -1)\n                        small = nums[i];\n                    if(big == nums[i])\n                        dup = true;\n                    big = nums[i];\n                }\n\n            // If no duplicates were found, then calculate and store the range for this subset\n            if(!dup)\n                range[mask] = big - small;\n        }\n\n        vector<int> dp(1 << n, INF);\n        dp[0] = 0;\n\n        // Iterate over every mask (i.e. subset) and calculate its minimum sum\n        for(int mask = 1; mask < (1 << n); mask++) {\n\n            // Iterate over every submask for current mask\n            for(int submask = mask; submask; submask = (submask - 1) & mask) {\n\n                // Check that submask has the right number of elements\n                if(__builtin_popcount(submask) == subset_size)\n                    // Note that mask = submask + (mask ^ submask)\n                    // ==> i.e., mask ^ submask = mask - submask\n                    // In other words, (mask ^ submask) represents those elements in mask that are not in submask\n                    dp[mask] = min(dp[mask], range[submask] + dp[mask ^ submask]);\n            }\n        }\n        // dp.back() == dp[(1 << n) - 1];\n        return dp.back() >= INF ? -1 : dp.back();\n    }\n};"
    },
    {
        "title": "Sum of Nodes with Even-Valued Grandparent",
        "algo_input": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.\n\nA grandparent of a node is the parent of its parent if it exists.\n\n&nbsp;\nExample 1:\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 18\nExplanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\n\n\nExample 2:\n\nInput: root = [1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n\tdef sumEvenGrandparent(self, root: TreeNode) -> int:\n\n\t\tdef dfs(root, p, gp):\n\t\t\tif not root: return 0\n\t\t\tif gp and gp.val%2==0:\n\t\t\t\treturn root.val + dfs(root.left,root,p)+dfs(root.right,root,p)\n\t\t\treturn 0 + dfs(root.left,root,p)+dfs(root.right,root,p)\n\n\t\treturn dfs(root,None,None)",
        "solution_js": "const dfs = function(node, evenParent) {\n    if (!node) return 0;\n    \n    const isEvenNode = node.val % 2 === 0;\n    \n    const left = dfs(node.left, isEvenNode);\n    const right = dfs(node.right, isEvenNode);\n    \n    if (!evenParent) return left + right;\n    return left + right + (node.left ? node.left.val : 0) + (node.right ? node.right.val : 0);\n}\n\nvar sumEvenGrandparent = function(root) {\n    if (!root) return 0;\n    return dfs(root, false);\n};",
        "solution_java": "class Solution {\n    int sum=0;\n    public int sumEvenGrandparent(TreeNode root) {\n        dfs(root,null,null);\n        return sum;\n    }\n void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) {\n        if (current == null) return; // base case \n        if (grandParent != null && grandParent.val % 2 == 0) {\n            sum += current.val;\n        }\n\t\t\t\t//cur->cur.left ||cur.right , parent=cur,grandPrarent=parent\n        dfs(current.left, current, parent)\n        dfs(current.right, current, parent);\n    }\n    }",
        "solution_c": "class Solution {\npublic:\n    void sumGparent(TreeNode* child, int& sum, TreeNode* parent, TreeNode* Gparent){\n        if(!child) return;\n        if(Gparent) if(Gparent->val % 2 ==0) sum += child->val;\n        sumGparent(child->left, sum, child, parent);\n        sumGparent(child->right, sum, child, parent);\n    }\n\n    int sumEvenGrandparent(TreeNode* root) {\n        if(!root) return 0;\n        int sum=0;\n        sumGparent(root, sum, NULL, NULL); // (child, sum, parent, grand-parent)\n        return sum;\n    }\n};"
    },
    {
        "title": "Range Sum Query 2D - Immutable",
        "algo_input": "Given a 2D matrix matrix, handle multiple queries of the following type:\n\n\n\tCalculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n\n\nImplement the NumMatrix class:\n\n\n\tNumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.\n\tint sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n\n\nYou must design an algorithm where sumRegion works on O(1) time complexity.\n\n&nbsp;\nExample 1:\n\nInput\n[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\nOutput\n[null, 8, 11, 12]\n\nExplanation\nNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 200\n\t-104 &lt;= matrix[i][j] &lt;= 104\n\t0 &lt;= row1 &lt;= row2 &lt; m\n\t0 &lt;= col1 &lt;= col2 &lt; n\n\tAt most 104 calls will be made to sumRegion.\n\n",
        "solution_py": "class NumMatrix:\n\n    def __init__(self, matrix: List[List[int]]):\n        m, n = len(matrix), len(matrix[0])\n        # Understand why we need to create a new matrix with extra one row/column\n        self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)]\n        for r in range(1, m + 1):\n            for c in range(1, n + 1):\n                self.sum[r][c] = self.sum[r - 1][c] + self.sum[r][c - 1] - self.sum[r - 1][c - 1] + matrix[r - 1][c - 1]\n\n    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n        r1, c1, r2, c2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1\n        return self.sum[r2][c2] - self.sum[r1 - 1][c2] - self.sum[r2][c1 - 1] + self.sum[r1 - 1][c1 - 1]\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)",
        "solution_js": "/**\n * @param {number[][]} matrix\n */\nvar NumMatrix = function(matrix) {\n    const n = matrix.length, m = matrix[0].length;\n    // n * m filled with 0\n    this.prefix = Array.from({ length: n}, (_, i) => {\n        return new Array(m).fill(0);\n    });\n    const prefix = this.prefix;\n    // precompute\n    for(let i = 0; i < m; i++) {\n        if(i == 0) prefix[0][i] = matrix[0][i];\n        else prefix[0][i] = prefix[0][i-1] + matrix[0][i];\n    }\n    for(let i = 0; i < n; i++) {\n        if(i == 0) continue;\n        else prefix[i][0] = prefix[i-1][0] + matrix[i][0];\n    }\n    \n    for(let i = 1; i < n; i++) {\n        for(let j = 1; j < m; j++) {\n            prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] + matrix[i][j];\n        }\n    }\n};\n\n/** \n * @param {number} row1 \n * @param {number} col1 \n * @param {number} row2 \n * @param {number} col2\n * @return {number}\n */\nNumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {\n    const prefix = this.prefix;\n    const biggerRectSum = prefix[row2][col2];\n    if(row1 == col1 && row1 == 0) return biggerRectSum;\n    if(row1 == 0 || col1 == 0) {\n        let subtractRegion = 0;\n        if(row1 == 0) subtractRegion = prefix[row2][col1 - 1];\n        else subtractRegion = prefix[row1 - 1][col2];\n        return biggerRectSum - subtractRegion;\n    }\n    return biggerRectSum - prefix[row1-1][col2] - prefix[row2][col1 - 1] + prefix[row1-1][col1-1];\n};\n\n/** \n * Your NumMatrix object will be instantiated and called as such:\n * var obj = new NumMatrix(matrix)\n * var param_1 = obj.sumRegion(row1,col1,row2,col2)\n */",
        "solution_java": "class NumMatrix {\n\n    int mat[][];\n    public NumMatrix(int[][] matrix) {\n        mat = matrix;\n        int rows = mat.length;\n        int cols = mat[0].length;\n        \n        for(int i = 0; i< rows; i++)\n        {\n            for(int j = 0; j < cols; j++) \n            {\n                if(i > 0) mat[i][j] += mat[i-1][j];\n                if(j > 0) mat[i][j] += mat[i][j-1];\n                if(i>0 && j > 0) mat[i][j] -= mat[i-1][j-1];\n            }\n        }\n        \n    }\n    \n    public int sumRegion(int row1, int col1, int row2, int col2) {\n        int res = mat[row2][col2];\n        if(row1 > 0) res -= mat[row1-1][col2];\n        if(col1 > 0) res -= mat[row2][col1-1];\n        if(row1> 0 && col1 > 0) res += mat[row1-1][col1-1];\n        \n        return res;\n    }\n}",
        "solution_c": "//Using row prefix sum O(m)\nclass NumMatrix {\n    vector<vector<int>> prefix;\npublic:\n    NumMatrix(vector<vector<int>>& matrix) {\n        int m = matrix.size(), n = matrix[0].size();\n        for(int i = 0;i<m;i++){\n            vector<int> row(n);\n            row[0] = matrix[i][0];\n            for(int j = 1;j<n;j++){\n                row[j] = row[j-1] + matrix[i][j];\n            }\n            prefix.push_back(row);\n        }\n    }\n    \n    int sumRegion(int row1, int col1, int row2, int col2) {\n        int sum = 0;\n        for(int i = row1;i<=row2;i++){\n            sum += prefix[i][col2];\n            if(col1>0) sum -= prefix[i][col1-1];\n        }\n        return sum;\n    }\n};\n\n//Using mat prefix sum O(1)\nclass NumMatrix {\n    vector<vector<int>> prefix;\npublic:\n    NumMatrix(vector<vector<int>>& matrix) {\n        int m = matrix.size(), n = matrix[0].size();\n        prefix = vector<vector<int>>(m+1,vector<int>(n+1,0));\n        prefix[1][1] = matrix[0][0];\n        for(int i = 1;i<=m;i++){\n            for(int j = 1;j<=n;j++){\n                prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] + matrix[i-1][j-1] - prefix[i-1][j-1];\n            }\n        }\n    }\n    \n    int sumRegion(int row1, int col1, int row2, int col2) {\n        int sum = 0;\n        sum += prefix[row2+1][col2+1];\n        sum -= prefix[row1][col2+1];\n        sum -= prefix[row2+1][col1];\n        sum += prefix[row1][col1];\n        return sum;\n    }\n};"
    },
    {
        "title": "K Radius Subarray Averages",
        "algo_input": "You are given a 0-indexed array nums of n integers, and an integer k.\n\nThe k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1.\n\nBuild and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.\n\nThe average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.\n\n\n\tFor example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput: [-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:\n- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n  Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.\n\n\nExample 2:\n\nInput: nums = [100000], k = 0\nOutput: [100000]\nExplanation:\n- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n  avg[0] = 100000 / 1 = 100000.\n\n\nExample 3:\n\nInput: nums = [8], k = 100000\nOutput: [-1]\nExplanation: \n- avg[0] is -1 because there are less than k elements before and after index 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= nums[i], k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def getAverages(self, nums: list[int], k: int) -> list[int]:\n\n        n, diam = len(nums), 2*k+1\n        if n < diam: return [-1]*n\n\n        ans = [-1]*k\n\n        arr = list(accumulate(nums, initial = 0))\n\n        for i in range(n-diam+1):\n            ans.append((arr[i+diam]-arr[i])//diam)\n\n        return  ans + [-1]*k",
        "solution_js": "var getAverages = function(nums, k) {\n    const twoK = 2 * k;\n    const windowSize = twoK + 1;\n\n    const result = [...nums].fill(-1);\n    let sum = 0;\n    for (let i = 0; i < nums.length; i++) {\n        sum += nums[i];\n        if (i >= twoK) {\n            result[i - k] = Math.floor(sum / windowSize)\n            sum -= nums[i - twoK];\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution\n{\n    public int[] getAverages(int[] nums, int k)\n    {\n        if(k == 0)\n            return nums;\n\n        int N = nums.length;\n        long[] sum = new long[N];\n        sum[0] = nums[0];\n\n        for(int i = 1; i < N; i++)\n            sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i]\n\n        int[] ret = new int[N];\n        Arrays.fill(ret,-1);\n\n        for(int i = k; i < N-k; i++) // Beyond this range, there are less than k elements so -1\n        {\n            long temp = (sum[i+k]-sum[i-k]+nums[i-k])/(k*2+1);\n            ret[i] = (int)temp;\n        }\n        return ret;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> getAverages(vector<int>& nums, int k) {\n\n        int n = nums.size();\n        vector<int> ans(n , -1);\n\n        if(2 * k + 1 > n) return ans;\n\n        // Simple Sliding Window\n\n        long long int sum = 0;\n\n        // Take a window of size 2 * k + 1\n        for(int i =0 ; i < 2 * k + 1 ; i++) {\n            sum += nums[i];\n        }\n\n        ans[k] = sum / (2 * k + 1);\n\n        // Then slide it untill the end of the window reaches at the end\n\n        for(int i = 2 * k + 1 , j = k + 1, s = 0; i < n ; i++ , j++, s++) {\n\n            sum += nums[i];\n            sum -= nums[s];\n            ans[j] = sum /(2 * k + 1);\n\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Valid Perfect Square",
        "algo_input": "Given a positive integer num, write a function which returns True if num is a perfect square else False.\n\nFollow up: Do not use any built-in library function such as sqrt.\n\n&nbsp;\nExample 1:\nInput: num = 16\nOutput: true\nExample 2:\nInput: num = 14\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 2^31 - 1\n\n",
        "solution_py": "class Solution:\n    def isPerfectSquare(self, num: int) -> bool:\n        if num == 1:\n            return True\n        lo = 2\n        hi = num // 2\n        while lo <= hi:\n            mid = lo + (hi - lo) //2\n            print(mid)\n            if mid * mid == num:\n                return True\n            if mid * mid > num:\n                hi = mid - 1\n            else:\n                lo = mid + 1\n        return False",
        "solution_js": "var isPerfectSquare = function(num) {\n    let low = 1;\n    let high = 100000;\n    while(low <= high){\n        let mid = (low + high) >> 1;\n        let sqrt = mid * mid\n        if( sqrt == num) {\n            return true;\n        \n        }else if(num > sqrt ){\n            low = mid + 1\n        }else {\n            high = mid - 1\n        }\n    }\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean isPerfectSquare(int num) {\n        long start = 1;\n        long end = num;\n\n        while(start<=end){\n            long mid = start +(end - start)/2;\n\n            if(mid*mid==num){\n                return true;\n            }\n            else if(mid*mid<num){\n                start = mid+1;\n            }\n            else\n                end = mid-1;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPerfectSquare(int num) {\n\n        if (num == 1)return true;\n        long long l = 1, h = num / 2;\n\n        while (l <= h) {\n            long long mid = l + (h - l) / 2;\n            long long midSqr = mid * mid;\n\n            if (midSqr == num) return true;\n\n            if (num < midSqr) {\n                h = mid - 1;\n            } else {\n                l = mid + 1;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Single Number II",
        "algo_input": "Given an integer array nums where&nbsp;every element appears three times except for one, which appears exactly once. Find the single element and return it.\n\nYou must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.\n\n&nbsp;\nExample 1:\nInput: nums = [2,2,3,2]\nOutput: 3\nExample 2:\nInput: nums = [0,1,0,1,0,1,99]\nOutput: 99\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\tEach element in nums appears exactly three times except for one element which appears once.\n\n",
        "solution_py": "import math\nclass Solution(object):\n    def singleNumber(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        [0,-1,1,0]\n        \n        [2,2,3,2]\n        [2,2,3,2]\n        [2,2,3,2]\n        10   10   11  10\n        \"\"\"\n        total = sum(nums)\n        \n        uniqueTotals = set()\n        while nums:\n            uniqueTotals.add(nums.pop())\n        return (sum(uniqueTotals)*3 - total)/2",
        "solution_js": " /**\n * @param {number[]} nums\n * @return {number}\n */\nvar singleNumber = function(nums) {\n    if(nums.length === 1) return nums[0];\n\n    const objNums = {};\n    for(var indexI=0; indexI<nums.length; indexI++){\n       if(objNums[nums[indexI]] === 2) delete objNums[nums[indexI]];\n       else objNums[nums[indexI]] = (objNums[nums[indexI]] || 0) + 1;\n    }\n\n    return Object.keys(objNums)[0];\n};",
        "solution_java": "class Solution {\n    public int singleNumber(int[] nums) {\n\n        int[] bitCount = new int[32]; // 32 bit number\n\n        // Count occurrence of each bits in each num\n        for (int i = 0; i < bitCount.length; i++) {\n            for (int num : nums) {\n                if ((num & 1 << i) != 0) // If ith bit in \"num\" is 1\n                    bitCount[i]++;\n            }\n        }\n\n        // Check the bit which doesn't have count multiple of 3 (i.e. no of repeating digits in input nums arr)\n        // and add it to the result.\n        int result = 0;\n        for (int i = 0; i < bitCount.length; i++)\n            result += (bitCount[i] % 3) * (1 << i);\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        unordered_map<int,int> mp;\n        int ans= 0;\n        for(auto i: nums){\n            mp[i]++;\n        }\n        for(auto j: mp){\n            if(j.second == 1){\n                ans = j.first;\n                break;\n            }\n        }\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Build Array from Permutation",
        "algo_input": "Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 &lt;= i &lt; nums.length and return it.\n\nA zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).\n\n&nbsp;\nExample 1:\n\nInput: nums = [0,2,1,5,3,4]\nOutput: [0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n    = [0,1,2,4,5,3]\n\nExample 2:\n\nInput: nums = [5,0,1,2,3,4]\nOutput: [4,5,0,1,2,3]\nExplanation: The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n    = [4,5,0,1,2,3]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt; nums.length\n\tThe elements in nums are distinct.\n\n\n&nbsp;\nFollow-up: Can you solve it without using an extra space (i.e., O(1) memory)?\n",
        "solution_py": "class Solution:\n\t#As maximum value of the array element is 1000, this solution would work\n    def buildArray(self, nums: List[int]) -> List[int]:\n        for i in range(len(nums)):            \n            if nums[nums[i]] <= len(nums):\n                nums[i] = nums[nums[i]] * 1000 + nums[i]\n            else:\n                nums[i] = mod(nums[nums[i]],1000) * 1000 + nums[i]\n            \n        for i in range(len(nums)):\n            nums[i]  = nums[i] // 1000\n            \n        return nums",
        "solution_js": "var buildArray = function(nums) {\n    return nums.map(a=>nums[a]);\n};",
        "solution_java": "class Solution {\n    public int[] buildArray(int[] nums) {\n        int n=nums.length;\n        for(int i=0;i<n;i++)\n            nums[i] = nums[i] + n*(nums[nums[i]]%n);\n        for(int i=0;i<n;i++)\n\t\t\tnums[i] = nums[i]/n;\n\t\t\n\t\treturn nums;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> buildArray(vector<int>& nums) {\n        int n=nums.size();\n        vector<int> ans(n);\n        for(int i=0;i<n;i++){\n            ans[i]=nums[nums[i]];\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Match Substring After Replacement",
        "algo_input": "You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times:\n\n\n\tReplace a character oldi of sub with newi.\n\n\nEach character in sub cannot be replaced more than once.\n\nReturn true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]\nOutput: true\nExplanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = \"l3e7\" is a substring of s, so we return true.\n\nExample 2:\n\nInput: s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]\nOutput: false\nExplanation: The string \"f00l\" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.\n\n\nExample 3:\n\nInput: s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]\nOutput: true\nExplanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = \"l33tb\" is a substring of s, so we return true.\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sub.length &lt;= s.length &lt;= 5000\n\t0 &lt;= mappings.length &lt;= 1000\n\tmappings[i].length == 2\n\toldi != newi\n\ts and sub consist of uppercase and lowercase English letters and digits.\n\toldi and newi are either uppercase or lowercase English letters or digits.\n\n",
        "solution_py": "from collections import defaultdict\nimport re\n\nclass Solution:\n    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n        reachable = defaultdict(set)\n        for a, b in mappings:\n            reachable[a].add(b)\n        for c in sub:\n            reachable[c].add(c)\n        regex = \"\"\n        for c in sub:\n            if len(reachable[c]) > 1:\n                regex += \"(\"\n                regex += \"|\".join(reachable[c])\n                regex += \")\"\n            else:\n                regex += c\n        return re.compile(regex).search(s)",
        "solution_js": "var matchReplacement = function(s, sub, mappings) {\n    let n= s.length;\n    let m = sub.length;\n    let map = new Array(36).fill().map(_=>new Array(36).fill(0));\n    for(let i=0;i<mappings.length;i++) {\n        let [o,ne] = mappings[i];\n        if(isNaN(o)) {\n            o = (o.toUpperCase()).charCodeAt(0)-55;\n        } else {\n            o = parseInt(o);\n        }\n        \n        if(isNaN(ne)) {\n            ne = (ne.toUpperCase()).charCodeAt(0)-55;\n        } else {\n            ne = parseInt(ne);\n        }\n        map[o][ne]=1;\n    }\n    // let map = new Map(mappings);\n    for(let i=0;i<=n-m;i++) {\n        let z=i;\n        let j=0;\n        while(j<m){\n            if(s[z] !== sub[j]) {\n                let ne = s[z];\n                let o = sub[j];\n                if(isNaN(o)) {\n                    o = (o.toUpperCase()).charCodeAt(0)-55;\n                } else {\n                    o = parseInt(o);\n                }\n\n                if(isNaN(ne)) {\n                    ne = (ne.toUpperCase()).charCodeAt(0)-55;\n                } else {\n                    ne = parseInt(ne);\n                }\n                if(map[o][ne] !== 1){\n                    break;\n                }\n            }\n            z++;\n            j++;\n        }\n        if(j == m){\n            return true\n        }\n    }\n    return false\n};",
        "solution_java": "class Solution {\n    public boolean matchReplacement(String s, String sub, char[][] mappings) {\n        HashMap<Character, HashSet<Character>> m = new HashMap<>();\n        for(char[] carr: mappings) {\n            if (!m.containsKey(carr[0])){\n                m.put(carr[0], new HashSet<Character>());\n            }\n            m.get(carr[0]).add(carr[1]);\n        }\n        int len_s = s.length();\n        int len_sub = sub.length();\n        for (int pos = 0; pos < s.length(); pos++ ){\n            int i = pos;\n            int j = 0;\n            boolean cont = false; \n            while (j <= sub.length()) {\n                if ( j == sub.length()) return true;\n                int lenlefts = len_s - i;\n                int lenleftsub = len_sub - j;\n                if (lenlefts < lenleftsub) {\n                    break;\n                } else if ((s.charAt(i) == sub.charAt(j)) || \n\t\t\t\t              (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) {\n                    i += 1;\n                    j += 1;\n                } else {\n                    break;\n                }\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) {\n\n        int m(size(s)), n(size(sub));\n        unordered_map<char, unordered_set<char>> mp;\n\n        auto doit = [&](int ind) {\n\n            for (int i=ind, j=0; i<ind+n; i++, j++) {\n                if (s[i] == sub[j] or mp[sub[j]].count(s[i])) continue;\n                return false;\n            }\n            return true;\n        };\n\n        for (auto& mapping : mappings) mp[mapping[0]].insert(mapping[1]);;\n        for (int i=0; i<=m-n; i++) if (doit(i)) return true;\n        return false;\n    }\n};"
    },
    {
        "title": "Unique Email Addresses",
        "algo_input": "Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.\n\n\n\tFor example, in \"alice@leetcode.com\", \"alice\" is the local name, and \"leetcode.com\" is the domain name.\n\n\nIf you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.\n\n\n\tFor example, \"alice.z@leetcode.com\" and \"alicez@leetcode.com\" forward to the same email address.\n\n\nIf you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.\n\n\n\tFor example, \"m.y+name@email.com\" will be forwarded to \"my@email.com\".\n\n\nIt is possible to use both of these rules at the same time.\n\nGiven an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.\n\n&nbsp;\nExample 1:\n\nInput: emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]\nOutput: 2\nExplanation: \"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.\n\n\nExample 2:\n\nInput: emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= emails.length &lt;= 100\n\t1 &lt;= emails[i].length &lt;= 100\n\temails[i] consist of lowercase English letters, '+', '.' and '@'.\n\tEach emails[i] contains exactly one '@' character.\n\tAll local and domain names are non-empty.\n\tLocal names do not start with a '+' character.\n\tDomain names end with the \".com\" suffix.\n\n",
        "solution_py": "class Solution:\n    def numUniqueEmails(self, emails: List[str]) -> int:\n        def ets(email):\n            s, domain = email[:email.index('@')], email[email.index('@'):]\n            s = s.replace(\".\", \"\")\n            s = s[:s.index('+')] if '+' in s else s\n            return s+domain\n        dict = {}\n        for i in emails:\n            dict[ets(i)] = 1\n        return len(dict)",
        "solution_js": "var numUniqueEmails = function(emails) {\n    let set = new Set();\n    \n    for (let email of emails) {\n        let curr = email.split('@');\n        let currEmail = '';\n        \n        for (let char of curr[0]) {\n            if (char === '.') continue;\n            if (char === '+') break;\n            currEmail += char;\n        }\n        \n        currEmail += '@' + curr[1];\n        set.add(currEmail)\n    }\n    \n    return set.size\n};",
        "solution_java": "class Solution {\n    public int numUniqueEmails(String[] emails) {\n\n        Set<String> finalEmails = new HashSet<>();\n        for(String email: emails){\n            StringBuilder name = new StringBuilder();\n            boolean ignore = false;\n            for(int i=0;i<email.length();i++){\n                char c = email.charAt(i);\n                switch(c){\n                    case '.':\n                        break;\n                    case '+':\n                        ignore = true;\n                        break;\n                    case '@':\n                        name.append(email.substring(i));\n                        i = email.length();\n                        break;\n                    default:\n                        if(!ignore) name.append(c);\n                }\n            }\n            finalEmails.add(name.toString());\n        }\n        finalEmails.forEach(System.out::println);\n        return finalEmails.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numUniqueEmails(vector<string>& emails)\n    {\n        unordered_set<string> st;\n        for(auto &e:emails)\n        {\n            string clean_email=\"\";\n            for(auto &ch:e)\n            {\n                if(ch=='+'||ch=='@')\n                    break;\n                if(ch=='.')\n                    continue;\n                clean_email+=ch;\n            }\n            clean_email+=e.substr(e.find('@'));\n            st.insert(clean_email);\n        }\n        return st.size();\n\n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Merge Triplets to Form Target Triplet",
        "algo_input": "A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.\n\nTo obtain target, you may apply the following operation on triplets any number of times (possibly zero):\n\n\n\tChoose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].\n\n\t\n\t\tFor example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].\n\t\n\t\n\n\nReturn true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\nThe target triplet [2,7,5] is now an element of triplets.\n\n\nExample 2:\n\nInput: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\nOutput: false\nExplanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\n\n\nExample 3:\n\nInput: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\nThe target triplet [5,5,5] is now an element of triplets.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= triplets.length &lt;= 105\n\ttriplets[i].length == target.length == 3\n\t1 &lt;= ai, bi, ci, x, y, z &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n\n        i=0\n        while True:\n            if i==len(triplets):\n                break\n            for j in range(3):\n                if triplets[i][j]>target[j]:\n                    triplets.pop(i)\n                    i-=1\n                    break\n            i+=1\n\n        a = [x[0] for x in triplets]\n        b = [x[1] for x in triplets]\n        c = [x[2] for x in triplets]\n\n        if target[0] not in a:\n            return False\n        if target[1] not in b:\n            return False\n        if target[2] not in c:\n            return False\n        return True",
        "solution_js": "var mergeTriplets = function(triplets, target) {\n\n    let fst = false, snd = false, thrd = false;\n\n    const [t1, t2, t3] = target;\n\n    for(let i = 0; i < triplets.length; i++) {\n\n        const [a, b, c] = triplets[i];\n\n        if(a === t1 && b <= t2 && c <= t3) fst = true;\n\n        if(b === t2 && a <= t1 && c <= t3) snd = true;\n\n        if(c === t3 && a <= t1 && b <= t2) thrd = true;\n\n        if(fst && snd && thrd) return true;\n    }\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean mergeTriplets(int[][] triplets, int[] target) {\n\n        boolean xFound = false, yFound = false, zFound = false;\n                \n        for(int[] triplet : triplets){\n\t\t\n            //Current Triplet is target\n            if(triplet[0] == target[0] && triplet[1] == target[1] && triplet[2] == target[2])return true;\n            \n            if(triplet[0] == target[0]){\n                if(triplet[1] <= target[1] && triplet[2] <= target[2])\n                    if(yFound && zFound)return true;\n                    else xFound = true;\n            }\n            if(triplet[1] == target[1]){\n                if(triplet[0] <= target[0] && triplet[2] <= target[2])\n                    if(xFound && zFound)return true;\n                    else yFound = true;\n            }\n            if(triplet[2] == target[2]){\n                if(triplet[1] <= target[1] && triplet[0] <= target[0])\n                    if(yFound && xFound)return true;\n                    else zFound = true;\n            }        \n        }\n        return xFound && yFound && zFound;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {\n        int first = 0, second = 0, third = 0;\n        for (auto tr : triplets) {\n            if (tr[0] == target[0] && tr[1] <= target[1] && tr[2] <= target[2]) first = 1;\n            if (tr[0] <= target[0] && tr[1] == target[1] && tr[2] <= target[2]) second = 1;\n            if (tr[0] <= target[0] && tr[1] <= target[1] && tr[2] == target[2]) third = 1;\n        }\n        return first && second && third;\n    }\n};"
    },
    {
        "title": "Implement Queue using Stacks",
        "algo_input": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).\n\nImplement the MyQueue class:\n\n\n\tvoid push(int x) Pushes element x to the back of the queue.\n\tint pop() Removes the element from the front of the queue and returns it.\n\tint peek() Returns the element at the front of the queue.\n\tboolean empty() Returns true if the queue is empty, false otherwise.\n\n\nNotes:\n\n\n\tYou must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.\n\tDepending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 1, 1, false]\n\nExplanation\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= x &lt;= 9\n\tAt most 100&nbsp;calls will be made to push, pop, peek, and empty.\n\tAll the calls to pop and peek are valid.\n\n\n&nbsp;\nFollow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.\n",
        "solution_py": "class MyStack:\n    def __init__(self):\n        self.stack = []\n\n    def push(self, x):\n        self.stack.append(x)\n\n    def top(self):\n        return self.stack[-1]\n\n    def pop(self):\n        return self.stack.pop()\n\n    def size(self):\n        return len(self.stack)\n\n    def isEmpty(self):\n        return len(self.stack) == 0\n\nclass MyQueue:\n\n    def __init__(self):\n        self.stack1 = MyStack()\n        self.stack2 = MyStack()\n\n    def push(self, x: int) -> None:\n        self.stack1.push(x)\n\n    def pop(self) -> int:\n        while not self.stack1.isEmpty():\n            self.stack2.push(self.stack1.pop())\n        out = self.stack2.pop()\n        while not self.stack2.isEmpty():\n            self.stack1.push(self.stack2.pop())\n        return out\n\n    def peek(self) -> int:\n        while not self.stack1.isEmpty():\n            self.stack2.push(self.stack1.pop())\n        out = self.stack2.top()\n        while not self.stack2.isEmpty():\n            self.stack1.push(self.stack2.pop())\n        return out\n\n    def empty(self) -> bool:\n        return self.stack1.isEmpty()\n\n# Your MyQueue object will be instantiated and called as such:\n# obj = MyQueue()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.peek()\n# param_4 = obj.empty()",
        "solution_js": "var MyQueue = function() {\n    this.queue = [];\n};\n\n/** \n * @param {number} x\n * @return {void}\n */\nMyQueue.prototype.push = function(x) {\n    this.queue.push(x);\n};\n\n/**\n * @return {number}\n */\nMyQueue.prototype.pop = function() {\n    return this.queue.splice(0, 1);\n};\n\n/**\n * @return {number}\n */\nMyQueue.prototype.peek = function() {\n    return this.queue[0]\n};\n\n/**\n * @return {boolean}\n */\nMyQueue.prototype.empty = function() {\n    return this.queue.length === 0;\n};\n\n/** \n * Your MyQueue object will be instantiated and called as such:\n * var obj = new MyQueue()\n * obj.push(x)\n * var param_2 = obj.pop()\n * var param_3 = obj.peek()\n * var param_4 = obj.empty()\n */",
        "solution_java": "class MyQueue {\n\n    private final Deque<Integer> stack = new ArrayDeque<>();\n    private final Deque<Integer> temp = new ArrayDeque<>();\n\n    /**\n     * Initialize your data structure here.\n     */\n    public MyQueue() {}\n\n    /**\n     * Pushes element x to the back of the queue.\n     */\n    public void push(int x) {\n        stack.push(x);\n    }\n\n    /**\n     * @return the element at the front of the queue and remove it.\n     */\n    public int pop() {\n        while (stack.size() > 1)\n            temp.push(stack.pop());\n\n        var val = stack.pop();\n        while (!temp.isEmpty())\n            stack.push(temp.pop());\n\n        return val;\n    }\n\n    /**\n     * @return the element at the front of the queue.\n     */\n    public int peek() {\n        while (stack.size() > 1)\n            temp.push(stack.pop());\n\n        var val = stack.peek();\n        while (!temp.isEmpty())\n            stack.push(temp.pop());\n\n        return val;\n    }\n\n    /**\n     * @return true if the queue is empty, false otherwise.\n     */\n    public boolean empty() {\n        return stack.isEmpty();\n    }\n}",
        "solution_c": "class MyQueue {\npublic:\n    stack<int>s1;\n    stack<int>s2;\n\n    MyQueue() {\n        \n    }\n    \n    void push(int x) {\n        s1.push(x);\n    }\n    \n    int pop() {\n        if(s1.empty() && s2.empty()) return -1;\n        while(s2.empty()){\n        while(!s1.empty()){\n            s2.push(s1.top());\n            s1.pop();\n        }\n        }\n        int x = s2.top();\n        s2.pop();\n        return x;\n    }\n    \n    int peek() {\n        if(!s2.empty()){\n            return s2.top();\n        }\n        else{\n            while(!s1.empty()){\n                int val = s1.top();\n                s2.push(val);\n                s1.pop();\n            }\n            return s2.top();\n        }\n    }\n    \n    bool empty() {\n        if(s1.empty() && s2.empty()){\n            return true;\n        }\n        return false;\n    }\n};\n\n/**\n * Your MyQueue object will be instantiated and called as such:\n * MyQueue* obj = new MyQueue();\n * obj->push(x);\n * int param_2 = obj->pop();\n * int param_3 = obj->peek();\n * bool param_4 = obj->empty();\n */"
    },
    {
        "title": "Maximum of Absolute Value Expression",
        "algo_input": "Given two arrays of integers with equal lengths, return the maximum value of:\n\n|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\n\nwhere the maximum is taken over all 0 &lt;= i, j &lt; arr1.length.\n\n&nbsp;\nExample 1:\n\nInput: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput: 13\n\n\nExample 2:\n\nInput: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput: 20\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr1.length == arr2.length &lt;= 40000\n\t-10^6 &lt;= arr1[i], arr2[i] &lt;= 10^6\n\n",
        "solution_py": "class Solution(object):\n    def maxAbsValExpr(self, arr1, arr2):\n        \"\"\"\n        :type arr1: List[int]\n        :type arr2: List[int]\n        :rtype: int\n        \"\"\"\n        max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf')\n        min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),float('inf'),float('inf'),float('inf')\n        for i,(a,b) in enumerate(zip(arr1,arr2)):\n            ppp=a+b+i\n            if ppp>max_ppp:max_ppp=ppp\n            if ppp<min_ppp:min_ppp=ppp\n            ppm=a+b-i\n            if ppm>max_ppm:max_ppm=ppm\n            if ppm<min_ppm:min_ppm=ppm\n            pmp=a-b+i\n            if pmp>max_pmp:max_pmp=pmp\n            if pmp<min_pmp:min_pmp=pmp\n            pmm=a-b-i\n            if pmm>max_pmm:max_pmm=pmm\n            if pmm<min_pmm:min_pmm=pmm\n        return max(max_ppp-min_ppp,max_ppm-min_ppm,max_pmp-min_pmp,max_pmm-min_pmm)   ",
        "solution_js": "var maxAbsValExpr = function(arr1, arr2) {\n    const l1 = [], l2 = [], l3 = [], l4 = [], res = [];\n    \n    for (let i = 0; i < arr1.length; i++) {\n        l1.push(arr1[i] + arr2[i] + i)\n        l2.push(arr1[i] - arr2[i] + i)\n        l3.push(-arr1[i] + arr2[i] + i)\n        l4.push(-arr1[i] - arr2[i] + i)\n    }\n    \n    res.push(Math.max(...l1) - Math.min(...l1))\n    res.push(Math.max(...l2) - Math.min(...l2))\n    res.push(Math.max(...l3) - Math.min(...l3))\n    res.push(Math.max(...l4) - Math.min(...l4))\n    \n    return Math.max(...res);\n};",
        "solution_java": "class Solution {\n    public int maxAbsValExpr(int[] arr1, int[] arr2) {\n\n        //1. remove the modulas -\n        //i & j are interchangable because they are inside the modulas\n        // A[i] - A[j] + B[i] -B[j] + i-j\n        // A[i] + B[i] + i - B[j] - A[j] - j\n        // (A[i] + B[i] + i) ->X\n        // (B[j] - A[j] - j) -> y\n        // X - Y;\n        //to get max value X should be max & Y should min\n\n        // Possible cases (Since both arrays have same number of indexes, we can use single for loop & i as index)\n        //A[i] + B[i] + i ->1\n        //A[i] - B[i] + i ->2\n        //A[i] + B[i] - i ->3\n        //A[i] - B[i] - i ->4\n\n        // Find out max of all response\n\n        int arrayLength =arr1.length;\n        int v1[] = new int [arrayLength];\n        int v2[] = new int [arrayLength] ;\n        int v3[] = new int [arrayLength] ;\n        int v4[] = new int [arrayLength] ;\n        int res = 0;\n        for(int i = 0 ; i< arrayLength; i++)\n        {\n            v1[i] = i + arr1[i] + arr2[i];\n            v2[i] = i + arr1[i] - arr2[i];\n            v3[i] = i - arr1[i] + arr2[i];\n            v4[i] = i - arr1[i] - arr2[i];\n        }\nres = Math.max(res,Arrays.stream(v1).max().getAsInt()-Arrays.stream(v1).min().getAsInt());\n                res = Math.max(res,Arrays.stream(v2).max().getAsInt()-Arrays.stream(v2).min().getAsInt());\n                res = Math.max(res,Arrays.stream(v3).max().getAsInt()-Arrays.stream(v3).min().getAsInt());\n                res = Math.max(res,Arrays.stream(v4).max().getAsInt()-Arrays.stream(v4).min().getAsInt());\n    return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {\n        int res=0;\n        int n = arr1.size();\n        vector<int>v1;\n        vector<int>v2;\n        vector<int>v3;\n        vector<int>v4;\n        for(int i=0;i<n;i++)\n        {\n            v1.push_back(i+arr1[i]+arr2[i]);\n            v2.push_back(i+arr1[i]-arr2[i]);\n            v3.push_back(i-arr1[i]+arr2[i]);\n            v4.push_back(i-arr1[i]-arr2[i]);\n        }\n        res = max(res,*max_element(v1.begin(),v1.end())-*min_element(v1.begin(),v1.end()));\n        res = max(res,*max_element(v2.begin(),v2.end())-*min_element(v2.begin(),v2.end()));\n        res = max(res,*max_element(v3.begin(),v3.end())-*min_element(v3.begin(),v3.end()));\n        res = max(res,*max_element(v4.begin(),v4.end())-*min_element(v4.begin(),v4.end()));\n        return res;\n    }\n};"
    },
    {
        "title": "Distribute Coins in Binary Tree",
        "algo_input": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.\n\nIn one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.\n\nReturn the minimum number of moves required to make every node have exactly one coin.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,0,0]\nOutput: 2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.\n\n\nExample 2:\n\nInput: root = [0,3,0]\nOutput: 3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t1 &lt;= n &lt;= 100\n\t0 &lt;= Node.val &lt;= n\n\tThe sum of all Node.val is n.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def distributeCoins(self, root: Optional[TreeNode]) -> int:\n        \n        def dfs(root):\n            if not root:\n                return 0,0\n            \n            net_left,left_walk = dfs(root.left)\n            net_right,right_walk = dfs(root.right)\n            \n\t\t\t# if any node has extra or deficiency in both cases there has to be a walk of abs(extra) or abs(deficiency)\n\t\t\t\n            return net_left+net_right+(root.val-1), left_walk+right_walk+abs(net_left)+abs(net_right)\n        return dfs(root)[1]",
        "solution_js": "var distributeCoins = function(root) {\n    var moves = 0;\n    postorder(root);\n    return moves;\n\n    function postorder(node){\n        if(!node)\n            return 0;\n\n        const subTotal = postorder(node.left) + postorder(node.right);\n        const result = node.val - 1 + subTotal;\n        moves += Math.abs(result);\n\n        return result;\n\n    }\n};",
        "solution_java": "class Solution {\n    int count = 0;\n        public int helper(TreeNode root)\n        {\n            if(root == null)\n                return 0;\n            int left = helper(root.left);\n            int right = helper(root.right);\n            count+= Math.abs(left)+Math.abs(right);\n            return (left+right+root.val-1);\n        }\n        public int distributeCoins(TreeNode root) {\n            helper(root);\n            return count;\n        }\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = 0;\n    int recr(TreeNode *root)\n    {\n        if(!root) return 0;\n        int left = recr(root->left);\n        int right = recr(root->right);\n        int curr = root->val + left + right;\n        ans += abs(curr-1);\n        return curr-1;\n    }\n    int distributeCoins(TreeNode* root) {\n        recr(root);\n        return ans;\n    }\n};"
    },
    {
        "title": "Special Array With X Elements Greater Than or Equal X",
        "algo_input": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.\n\nNotice that x does not have to be an element in nums.\n\nReturn x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,5]\nOutput: 2\nExplanation: There are 2 values (3 and 5) that are greater than or equal to 2.\n\n\nExample 2:\n\nInput: nums = [0,0]\nOutput: -1\nExplanation: No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers &gt;= x, but there are 2.\nIf x = 1, there should be 1 number &gt;= x, but there are 0.\nIf x = 2, there should be 2 numbers &gt;= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.\n\n\nExample 3:\n\nInput: nums = [0,4,3,0,4]\nOutput: 3\nExplanation: There are 3 values that are greater than or equal to 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def specialArray(self, nums: List[int]) -> int:\n        nums.sort()\n        for i in range(max(nums)+1):\n            y=len(nums)-bisect.bisect_left(nums,i)\n            if y==i:\n                return i\n        return -1\n\n        \n        ",
        "solution_js": "var specialArray = function(nums) {\n    const freq = new Array(1001).fill(0);\n    for(let n of nums)\n        freq[n]++;\n    \n    for(let i=1000, cnt=0; i>=0; i--){\n        cnt += freq[i];\n        if(i==cnt) return i;\n    }\n    \n    return -1;\n};",
        "solution_java": "class Solution {\n    public int specialArray(int[] nums) {\n        int x = nums.length;\n        int[] counts = new int[x+1];\n\n        for(int elem : nums)\n            if(elem >= x)\n                counts[x]++;\n            else\n                counts[elem]++;\n\n        int res = 0;\n        for(int i = counts.length-1; i > 0; i--) {\n            res += counts[i];\n            if(res == i)\n                return i;\n        }\n\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int specialArray(vector<int>& nums) {\n        int v[102];\n        memset(v, 0, sizeof v);\n        for (const auto &n : nums) {\n            ++v[n > 100 ? 100 : n];\n        }\n        for (int i = 100; i > 0; --i) {\n            v[i] = v[i + 1] + v[i];\n            if (v[i] == i)\n                return i;\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Sort Integers by The Power Value",
        "algo_input": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:\n\n\n\tif x is even then x = x / 2\n\tif x is odd then x = 3 * x + 1\n\n\nFor example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1).\n\nGiven three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.\n\nReturn the kth integer in the range [lo, hi] sorted by the power value.\n\nNotice that for any integer x (lo &lt;= x &lt;= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: lo = 12, hi = 15, k = 2\nOutput: 13\nExplanation: The power of 12 is 9 (12 --&gt; 6 --&gt; 3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\n\n\nExample 2:\n\nInput: lo = 7, hi = 11, k = 4\nOutput: 7\nExplanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= lo &lt;= hi &lt;= 1000\n\t1 &lt;= k &lt;= hi - lo + 1\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def power(self,n):\n        if n in self.dic:\n            return self.dic[n]\n        if n % 2:\n            self.dic[n] = self.power(3 * n + 1) + 1\n        else:\n            self.dic[n] = self.power(n // 2) + 1\n        return self.dic[n]    \n    def getKth(self, lo: int, hi: int, k: int) -> int:\n        self.dic = {1:0}\n        for i in range(lo,hi+1):\n            self.power(i)\n                        \n        lst = [(self.dic[i],i) for i in range(lo,hi+1)]\n        heapq.heapify(lst)\n        \n        for i in range(k):\n            ans = heapq.heappop(lst)\n        \n        return ans[1]     ",
        "solution_js": "var getKth = function(lo, hi, k) {\n    const dp = new Map();\n    dp.set(1, 0);\n    const powerVals = [];\n    for(let num = lo; num <= hi; ++num) {\n        powerVals.push([num, findPowerVal(num, dp)]);\n    }\n    const heap = new MinHeap();\n    heap.build(powerVals);\n    let top;\n    while(k--) {    // O(klogn)\n        top = heap.removeTop();\n    }\n    return top[0];\n};\n\nfunction findPowerVal(num, dp) {\n    if(dp.has(num)) {\n        return dp.get(num);\n    }\n    let powerVal;\n    if(num % 2 === 0) {\n        powerVal = findPowerVal(num/2, dp) + 1;\n    } else {\n        powerVal = findPowerVal(3 * num + 1, dp) + 1;\n    }\n    dp.set(num, powerVal);\n    return dp.get(num);\n}\n\nclass Heap {\n    constructor(property) {\n        this.data = [];\n    }\n    size() {\n        return this.data.length;\n    }\n    build(arr) {    // O(n)\n        this.data = [...arr];\n        for(let i = Math.floor((this.size() - 1)/2); i >= 0; --i) {\n            this.heapify(i);\n        }\n    }\n    heapify(i) {    // O(logn)\n        const left = 2 * i + 1, right = 2 * i + 2;\n        let p = i;\n        if(left < this.size() && this.compare(left, p)) {\n            p = left;\n        }\n        if(right < this.size() && this.compare(right, p)) {\n            p = right;\n        }\n        if(p !== i) {\n            [this.data[p], this.data[i]] = [this.data[i], this.data[p]];\n            this.heapify(p);\n        }\n    }\n    removeTop() {   // O(logn)\n        if(this.size() === 1) {\n            return this.data.pop();\n        }\n        const top = this.data[0];\n        [this.data[0], this.data[this.size() - 1]] = [this.data[this.size() - 1], this.data[0]];\n        this.data.pop();\n        this.heapify(0);\n        return top;\n    }\n}\n\nclass MinHeap extends Heap {\n    constructor() {\n        super();\n    }\n    compare(a, b) {\n        return this.data[a][1] < this.data[b][1] || (this.data[a][1] === this.data[b][1] && this.data[a][0] < this.data[b][0]);\n    }\n}",
        "solution_java": "class Solution {\n    public int getKth(int lo, int hi, int k) {\n\n        int p = 0;\n        int[][] powerArr = new int[hi - lo + 1][2];\n\n        Map<Integer, Integer> memo = new HashMap<>();\n        for (int i = lo; i <= hi; i++)\n            powerArr[p++] = new int[]{i, getPower(i, memo)};\n\n        Arrays.sort(powerArr, (a1, a2) -> a1[1] - a2[1] == 0 ? a1[0] - a2[0] : a1[1] - a2[1]);\n\n        return powerArr[k - 1][0];\n    }\n\n    private int getPower(int i, Map<Integer, Integer> memo) {\n        if (memo.containsKey(i)) return memo.get(i);\n\n        if (i == 1) return 0;\n\n        int power = 1 + (i % 2 == 0 ? getPower(i / 2, memo) : getPower(i * 3 + 1, memo));\n\n        memo.put(i, power);\n        return power;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getPower(int num) {\n        if (num == 1)\n            return 0;\n\n        int res = 0;\n        if (num %2 == 0)\n            res += getPower(num/2);\n        else\n            res += getPower(3*num + 1);\n        res++;\n        return res;\n    }\n\n    int getKth(int lo, int hi, int k) {\n        multimap<int,int> um;\n        for (int i = lo; i <= hi; i++) {\n            um.insert({getPower(i), i});\n        }\n        int cnt = 1;\n        int res = 0;\n        for (auto iter = um.begin(); iter != um.end(); iter++) {\n            if (cnt == k) {\n                res = iter->second;\n            }\n            cnt++;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Evaluate Boolean Binary Tree",
        "algo_input": "You are given the root of a full binary tree with the following properties:\n\n\n\tLeaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.\n\tNon-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.\n\n\nThe evaluation of a node is as follows:\n\n\n\tIf the node is a leaf node, the evaluation is the value of the node, i.e. True or False.\n\tOtherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.\n\n\nReturn the boolean result of evaluating the root node.\n\nA full binary tree is a binary tree where each node has either 0 or 2 children.\n\nA leaf node is a node that has zero children.\n\n&nbsp;\nExample 1:\n\nInput: root = [2,1,3,null,null,0,1]\nOutput: true\nExplanation: The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.\n\nExample 2:\n\nInput: root = [0]\nOutput: false\nExplanation: The root node is a leaf node and it evaluates to false, so we return false.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 &lt;= Node.val &lt;= 3\n\tEvery node has either 0 or 2 children.\n\tLeaf nodes have a value of 0 or 1.\n\tNon-leaf nodes have a value of 2 or 3.\n\n",
        "solution_py": "class Solution:\n    def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n        def recur(node):\n            if not node.left and not node.right: #leaf node\n                return True if node.val == 1 else False\n            left = recur(node.left)\n            right = recur(node.right)\n            if node.val == 2: #if node is or\n                return left or right\n            if node.val == 3: #if node is and\n                return left and right\n        return recur(root)",
        "solution_js": "/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar evaluateTree = function(root) {\n  return root.val === 3 ? evaluateTree(root.left) && evaluateTree(root.right) :\n         root.val === 2 ? evaluateTree(root.left) || evaluateTree(root.right) :\n         root.val;\n};",
        "solution_java": "class Solution {\n    public boolean evaluateTree(TreeNode root) {\n        if(root.val == 1)\n            return true;\n        if(root.val == 0)\n            return false;\n        if(root.val == 2)\n            return evaluateTree(root.left) || evaluateTree(root.right);\n        return evaluateTree(root.left) && evaluateTree(root.right);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool evaluateTree(TreeNode* root) {\n\n        if (!root->left and !root->right) return root->val;\n        int l = evaluateTree(root->left);\n        int r = evaluateTree(root->right);\n        return (root->val == 2) ? l or r : l and r;\n    }\n};"
    },
    {
        "title": "All O`one Data Structure",
        "algo_input": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.\n\nImplement the AllOne class:\n\n\n\tAllOne() Initializes the object of the data structure.\n\tinc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1.\n\tdec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.\n\tgetMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\".\n\tgetMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\".\n\n\nNote that each function must run in O(1) average time complexity.\n\n&nbsp;\nExample 1:\n\nInput\n[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\nOutput\n[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]\n\nExplanation\nAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= key.length &lt;= 10\n\tkey consists of lowercase English letters.\n\tIt is guaranteed that for each call to dec, key is existing in the data structure.\n\tAt most 5 * 104&nbsp;calls will be made to inc, dec, getMaxKey, and getMinKey.\n\n",
        "solution_py": "from collections import defaultdict\n\n\nclass Set(object):\n\n    def __init__(self):\n        self._dict = {}\n        self._list = []\n        self._len = 0\n\n    def add(self, v):\n        if v in self._dict:\n            pass\n        else:\n            self._list.append(v)\n            self._dict[v] = self._len\n            self._len += 1\n\n    def __contains__(self, item):\n        return item in self._dict\n\n    def remove(self, v):\n        if v not in self._dict:\n            pass\n        else:\n            idx = self._dict[v]\n\n            if idx < self._len - 1:\n                self._list[idx] = self._list[-1]\n                self._dict[self._list[idx]] = idx\n\n            del self._dict[v]\n            self._list.pop()\n            self._len -= 1\n\n    def __iter__(self):\n        return iter(self._list)\n\n    def check(self):\n        assert len(self._dict) == len(self._list)\n        for idx, key in enumerate(self._list):\n            assert self._dict[key] == idx\n\n    def __len__(self):\n        return self._len\n\n    def __repr__(self):\n        return f\"{self._dict}\\n{self._list}\"\n\n\nclass Node(object):\n\n    def __init__(self, value):\n        self.value = value\n        self.prev = None\n        self.next = None\n\n    def set_prev(self, other_node):\n        self.prev = other_node\n        if other_node is not None:\n            other_node.next = self\n\n    def set_next(self, other_node):\n        self.next = other_node\n        if other_node is not None:\n            other_node.prev = self\n\n    def __repr__(self):\n        return str(self.value)\n\n\nclass SortedKeyList(object):\n\n    def __init__(self):\n        self.head = Node(value=0)\n        self.tail = Node(value=float(\"inf\"))\n        self.head.set_next(self.tail)\n\n    def is_empty(self):\n        return self.head.next is self.tail\n\n    def min_key(self):\n        if self.is_empty():\n            return None\n        else:\n            return self.head.next.value\n\n    def max_key(self):\n        if self.is_empty():\n            return None\n        else:\n            return self.tail.prev.value\n\n    def incr_key(self, orig_node):\n        orig_value = orig_node.value\n        new_value = orig_value + 1\n        next_node = orig_node.next\n        if next_node.value == new_value:\n            return self\n        else:\n            new_node = Node(new_value)\n            new_node.set_prev(orig_node)\n            new_node.set_next(next_node)\n            return self\n\n    def decr_key(self, orig_node):\n        orig_value = orig_node.value\n        new_value = orig_value - 1\n        prev_node = orig_node.prev\n        if prev_node.value == new_value:\n            return self\n        else:\n            new_node = Node(new_value)\n            new_node.set_next(orig_node)\n            new_node.set_prev(prev_node)\n            return self\n\n    def delete_node(self, node):\n        prev_node = node.prev\n        next_node = node.next\n        prev_node.set_next(next_node)\n        return self\n\n    def __repr__(self):\n        a = []\n        node = self.head.next\n        while True:\n            if node is self.tail:\n                break\n\n            assert node.next.prev is node\n            assert node.prev.next is node\n\n            a.append(node.value)\n            node = node.next\n        return str(a)\n\n\nclass AllOne:\n\n    def __init__(self):\n        self.count_list = SortedKeyList()\n        self.counter = defaultdict(lambda: self.count_list.head)\n        self.keyed_by_count = defaultdict(set)\n\n    def __repr__(self):\n        return f\"count_list={self.count_list}\\ncounter={dict(self.counter)}\\nkeyed_by_count={dict(self.keyed_by_count)}\"\n\n    def inc(self, key: str) -> None:\n        orig_count_node = self.counter[key]\n        orig_count = orig_count_node.value\n\n        self.count_list.incr_key(orig_count_node)\n        new_count_node = orig_count_node.next\n        new_count = new_count_node.value\n        assert new_count == orig_count + 1\n\n        self.counter[key] = new_count_node\n\n        if key in self.keyed_by_count[orig_count]:\n            self.keyed_by_count[orig_count].remove(key)\n        self.keyed_by_count[new_count].add(key)\n\n        if len(self.keyed_by_count[orig_count]) == 0:\n            del self.keyed_by_count[orig_count]\n            if orig_count_node.value > 0:\n                self.count_list.delete_node(orig_count_node)\n\n    def dec(self, key: str) -> None:\n        orig_count_node = self.counter[key]\n        orig_count = orig_count_node.value\n\n        self.count_list.decr_key(orig_count_node)\n        new_count_node = orig_count_node.prev\n        new_count = new_count_node.value\n        assert new_count == orig_count - 1\n\n        self.counter[key] = new_count_node\n\n        if key in self.keyed_by_count[orig_count]:\n            self.keyed_by_count[orig_count].remove(key)\n        self.keyed_by_count[new_count].add(key)\n\n        if new_count == 0:\n            del self.counter[key]\n\n        if len(self.keyed_by_count[orig_count]) == 0:\n            del self.keyed_by_count[orig_count]\n            self.count_list.delete_node(orig_count_node)\n\n    def getMaxKey(self) -> str:\n        max_count = self.count_list.max_key()\n        if max_count is not None:\n            return next(iter(self.keyed_by_count[max_count]))\n        else:\n            return \"\"\n\n    def getMinKey(self) -> str:\n        min_count = self.count_list.min_key()\n        if min_count is not None:\n            return next(iter(self.keyed_by_count[min_count]))\n        else:\n            return \"\"\n\n\ndef drive(m, p):\n    s = AllOne()\n\n    naive_counter = defaultdict(int)\n\n    for method, param in zip(m, p):\n        if method in (\"inc\", \"dec\"):\n            word = param[0]\n\n            if method == \"inc\":\n                s.inc(word)\n                naive_counter[word] += 1\n\n            elif method == 'dec':\n                s.dec(word)\n                naive_counter[word] -= 1\n\n            if naive_counter[word] == 0:\n                del naive_counter[word]\n\n            tmp_counter = defaultdict(set)\n            for k, v in naive_counter.items():\n                tmp_counter[v].add(k)\n\n            sorted_keys = sorted(tmp_counter.keys())\n            min_key = sorted_keys[0]\n            max_key = sorted_keys[-1]\n\n            if s.getMaxKey() not in tmp_counter[max_key]:\n                print(\"Oh No!!!\")\n                return s, naive_counter, tmp_counter\n\n            if s.getMinKey() not in tmp_counter[min_key]:\n                print(\"Oh No!!!\")\n                return s, naive_counter, tmp_counter\n\n    return None, None, None\n\n\nif __name__ == '__main__':\n    m = [\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n    p = [[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\n    s, naive_counter, tmp_counter = drive(m, p)",
        "solution_js": "var AllOne = function() {\n  this.map = new Map();\n  this.pre = '';\n};\n\n/** \n * @param {set} map\n * @param {function} handler\n * @return {map}\n */\nAllOne.prototype.sort = function(map, handler) {\n  return new Map([...map].sort(handler));\n};\n\n/** \n * @param {string} key\n * @return {void}\n */\nAllOne.prototype.inc = function(key) {\n  this.map.set(key, this.map.get(key) + 1 || 1);\n  this.pre = 'inc';\n};\n\n/** \n * @param {string} key\n * @return {void}\n */\nAllOne.prototype.dec = function(key) {\n  this.map.get(key) == 1 ? this.map.delete(key) : this.map.set(key, this.map.get(key) - 1);\n  this.pre = 'dec';\n};\n\n/**\n * @return {string}\n */\nAllOne.prototype.getMaxKey = function() {\n  if (this.pre != 'max') {\n    this.map = this.sort(this.map, (a, b) => b[1] - a[1]);\n  }\n  this.pre = 'max';\n  return this.map.keys().next().value || '';\n};\n\n/**\n * @return {string}\n */\nAllOne.prototype.getMinKey = function() {\n  if (this.pre != 'min') {\n    this.map = this.sort(this.map, (a, b) => a[1] - b[1]);\n  }\n  this.pre = 'min';\n  return this.map.keys().next().value || '';\n};",
        "solution_java": "//Intuitions get from the top answer by @AaronLin1992\nclass AllOne {\n    //Thoughts\n    //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)?\n    //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min\n    //to maintain some kind of ordering, the first thing we think about is arrays/lists, however, arrays/lists when insert and delete in the middle, it is O(N) operation\n    //so instead, a linked list might work\n    //as a result, we considering using Map(s) and LinkedList for our supporting data structures, details below\n    \n    private Map<String, Bucket> stringToBucket; //maps a string to bucket\n    private Map<Integer, Bucket> countToBucket; //maps string count to bucket, note that because when we design this we can have multiple strings in a bucket, that makes it convenient so that for each count, we only need 1 bucket, thus the map data structure\n    private BucketList bucketList;\n    \n    //first, we need to create a class for the LinkedList elements\n    class Bucket {\n        private Bucket prev;\n        private Bucket next;\n        \n        private int count; //recording the count of instances\n        private Set<String> keys; //note that we are using Set of Strings. The reason is because multiple Strings can have the same count and we want to put them in one bucket. This makes the problem easier to solve instead of putting them into different buckets.\n        \n        Bucket() {\n            this.keys = new HashSet<>();\n        }\n        \n        Bucket(String key) {\n            this();\n            this.count = 1;\n            this.keys.add(key);\n        }\n        \n    }\n    \n    //second, we need to create a linked list data structure of buckets\n    class BucketList {\n        private Bucket dummyHead; //the fake head before the real head //useful for getMinKey()\n        private Bucket dummyTail; //the fake tail before the real tail //useful for getMaxKey()\n        \n        public BucketList() {\n            dummyHead = new Bucket();\n            dummyTail = new Bucket();\n            dummyHead.next = dummyTail;\n            dummyTail.prev = dummyHead;\n        }\n        \n        public Bucket createNewBucket(String key) {\n            Bucket bucket = new Bucket(key);\n            \n            Bucket nextBucket = dummyHead.next;\n            dummyHead.next = bucket;\n            bucket.prev = dummyHead;\n            nextBucket.prev = bucket;\n            bucket.next = nextBucket;\n            \n            return bucket;\n        }\n        \n        public Bucket createBucketToTheRight(Bucket fromBucket, String key, int count) {\n            //initialize\n            Bucket toBucket = new Bucket(key);\n            toBucket.count = count;\n            \n            Bucket nextBucket = fromBucket.next;\n            fromBucket.next = toBucket;\n            toBucket.prev = fromBucket;\n            nextBucket.prev = toBucket;\n            toBucket.next = nextBucket;\n            \n            return toBucket;\n        }\n        \n        public Bucket createBucketToTheLeft(Bucket fromBucket, String key, int count) {\n            //initialize\n            Bucket toBucket = new Bucket(key);\n            toBucket.count = count;\n            \n            Bucket prevBucket = fromBucket.prev;\n            prevBucket.next = toBucket;\n            toBucket.prev = prevBucket;\n            fromBucket.prev = toBucket;\n            toBucket.next = fromBucket;\n            \n            return toBucket;\n        }\n        \n        public boolean clean(Bucket oldBucket) {//clean bucket if bucket does not have any keys\n            if (!oldBucket.keys.isEmpty()) {\n                return false;\n            }\n            \n            removeBucket(oldBucket);\n            \n            return true;\n        }\n        \n        public void removeBucket(Bucket bucket) {\n            Bucket prevBucket = bucket.prev;\n            Bucket nextBucket = bucket.next;\n            \n            prevBucket.next = nextBucket;\n            nextBucket.prev = prevBucket;\n        }\n    }\n    \n\n    public AllOne() {\n        this.stringToBucket = new HashMap<>();\n        this.countToBucket = new HashMap<>();\n        this.bucketList = new BucketList();\n    }\n    \n    public void inc(String key) {\n        //first check if the string already present\n        if (!stringToBucket.containsKey(key)) { //if not present \n            Bucket bucket = null;\n            \n            //check if there is count of 1 bucket already\n            if (!countToBucket.containsKey(1)) { //if does not contain count of 1\n                //we need to create a new bucket for count of 1 and add to the head (the minimum). Because count 1 should be the minimum exists in the bucket list\n                bucket = bucketList.createNewBucket(key);\n            } else { //if contains count of 1\n                //then we just need to add the key to the bucket\n                bucket = countToBucket.get(1);\n                bucket.keys.add(key);\n            }\n            \n            //don't forget to update the maps\n            stringToBucket.put(key, bucket);\n            countToBucket.put(1, bucket);\n        } else { //if the key alreay present\n            //first of all we need to get the current count for the key\n            Bucket oldBucket = stringToBucket.get(key);\n            Bucket newBucket = null;\n            \n            int count = oldBucket.count;\n            count++; //increment 1\n            //don't forget that we need to remove the key from existing bucket\n            oldBucket.keys.remove(key);\n            \n            //now let's add the key with new count\n            if (countToBucket.containsKey(count)) { //if there is already a bucket for this count\n                //then just add to the set of keys\n                newBucket = countToBucket.get(count);\n                newBucket.keys.add(key);\n            } else { //if there is no bucket for this count, create a new bucket, but where to place it? Ans: to the right of the old bucket\n                newBucket = bucketList.createBucketToTheRight(oldBucket, key, count);     \n            }\n            \n            //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n            if (bucketList.clean(oldBucket)) {\n                countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n            }\n            \n            //don't forget to update the maps\n            stringToBucket.put(key, newBucket);\n            countToBucket.putIfAbsent(count, newBucket);\n        }\n    }\n    \n    public void dec(String key) {\n        //since it is given that \"It is guaranteed that key exists in the data structure before the decrement.\" we don't do additional validation for key exists here\n        Bucket oldBucket = stringToBucket.get(key);\n        Bucket newBucket = null;\n        \n        int count = oldBucket.count;\n        count--; //decrement\n        oldBucket.keys.remove(key);\n        \n        //special scenario - when count == 0\n        if (count == 0) {\n            stringToBucket.remove(key);\n        } else {\n            //now let's find a new bucket for the decremented count\n            if (countToBucket.containsKey(count)) {//if there is already a bucket for the count\n                newBucket = countToBucket.get(count);\n                newBucket.keys.add(key);\n            } else {//if there is no bucket for the count, then following similar logic as before, we need to add a bucket to the left of the existing bucket\n                newBucket = bucketList.createBucketToTheLeft(oldBucket, key, count);\n            }\n            \n            //don't forget to update the maps\n            stringToBucket.put(key, newBucket);\n            countToBucket.putIfAbsent(count, newBucket);\n        }\n        \n        //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n        if (bucketList.clean(oldBucket)) {\n            countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n        }\n    }\n    \n    public String getMaxKey() {\n        Set<String> maxSet = bucketList.dummyTail.prev.keys;\n        \n        return maxSet.isEmpty() ? \"\" : maxSet.iterator().next(); //if maxSet is empty, that means the bucketList don't have actual buckets\n        \n    }\n    \n    public String getMinKey() {\n        Set<String> minSet = bucketList.dummyHead.next.keys;\n        \n        return minSet.isEmpty() ? \"\" : minSet.iterator().next(); //if minSet is empty, that means the bucketList don't have actual buckets\n    }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */",
        "solution_c": "class AllOne {\npublic:\n    map<int,unordered_set<string>> minmax;\n    unordered_map<string,int> count;\n    AllOne() {\n        \n    }\n    \n    void inc(string key) {\n         int was = count[key]++;\n         if(was>0) {\n             minmax[was].erase(key);\n             if(minmax[was].size()==0) minmax.erase(was);\n         }\n         minmax[was+1].insert(key);\n    }\n    \n    void dec(string key) {\n         int was = count[key]--;\n         minmax[was].erase(key);\n         if(minmax[was].size()==0) minmax.erase(was);\n         if(was-1==0) {\n             count.erase(key);\n         }else {\n             minmax[was-1].insert(key);\n         }\n    }\n    \n    string getMaxKey() {\n         return minmax.size() == 0 ? \"\" : *minmax.rbegin()->second.begin();\n    }\n    \n    string getMinKey() { \n        return minmax.size() == 0 ? \"\" : *minmax.begin()->second.begin();\n    }\n};\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne* obj = new AllOne();\n * obj->inc(key);\n * obj->dec(key);\n * string param_3 = obj->getMaxKey();\n * string param_4 = obj->getMinKey();\n */"
    },
    {
        "title": "Numbers At Most N Given Digit Set",
        "algo_input": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.\n\nReturn the number of positive integers that can be generated that are less than or equal to a given integer n.\n\n&nbsp;\nExample 1:\n\nInput: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\nOutput: 20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n\n\nExample 2:\n\nInput: digits = [\"1\",\"4\",\"9\"], n = 1000000000\nOutput: 29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.\n\n\nExample 3:\n\nInput: digits = [\"7\"], n = 8\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= digits.length &lt;= 9\n\tdigits[i].length == 1\n\tdigits[i] is a digit from&nbsp;'1'&nbsp;to '9'.\n\tAll the values in&nbsp;digits are unique.\n\tdigits is sorted in&nbsp;non-decreasing order.\n\t1 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution():\n    def atMostNGivenDigitSet(self, digits, n):\n        cache = {}\n        target = str(n)\n\n        def helper(idx, isBoundary, isZero):\n            if idx == len(target): return 1\n            if (idx, isBoundary, isZero) in cache: return cache[(idx, isBoundary, isZero)]\n            \n            res = 0\n            if isZero and idx != len(target)-1:\n                res+= helper(idx+1, False, True)\n            for digit in digits:\n                if isBoundary and int(digit) > int(target[idx]): continue\n                res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False)\n\n            cache[(idx, isBoundary, isZero)] = res\n            return res\n\n        return helper(0, True, True)",
        "solution_js": "var atMostNGivenDigitSet = function(digits, n) {\n    const asString = \"\"+ n;\n    let smaller = 0;\n    let prev = 1;\n    for (let i = asString.length - 1; i >= 0; --i) {\n        const L = asString.length - 1 - i;\n        const num = +asString[i];\n        let equal = 0;\n        let less = 0;\n        for (let digit of digits) {\n            if (digit == num) {\n                equal = 1;\n            }\n            if (digit > num) {\n                break;\n            }\n            if (digit < num) {\n                less++;\n            }\n        }\n        prev = (less * Math.pow(digits.length, L)) + equal * prev;\n        if (L < asString.length - 1) {\n            smaller += Math.pow(digits.length, L + 1);\n        }\n    }\n    return smaller + prev;\n};",
        "solution_java": "class Solution {\n    \n    \n    // DIGIT DP IS LOVE \n    Integer[][][] digitdp;\n    public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) {\n\n        if (pos == num.length()) {\n            return 1;\n        }\n\n        int maxDigit = -1;\n        \n        if(digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] !=null) return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0];\n\n        if (bound) {\n            maxDigit = num.charAt(pos) - '0';\n        } else {\n            maxDigit = 9;\n        }\n\n        int ans = 0;\n        for (int i = 0; i <=maxDigit; i++) {\n            \n            // 0 can only be leading \n            if(i==0 && lead){\n\n                ans += solve(num,pos+1,false,dig,lead);\n                \n            }else{\n                \n              int res =  Arrays.binarySearch(dig,i);\n\n              if(res>=0){\n                 // lead = false; // now it is not possible to 0 to be in lead any more once any other call has been made\n                 ans += solve(num, pos + 1, bound & (i == num.charAt(pos)-'0'), dig,false);\n              }\n                \n            }\n        }\n\n        return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] = ans;\n\n    }\n\n    public int atMostNGivenDigitSet(String[] digits, int n) {\n\n        String num = n + \"\";\n        Integer[] dig = new Integer[digits.length];\n        for(int i=0;i<dig.length;i++){\n            dig[i] = Integer.parseInt(digits[i]);\n        }\n        \n        digitdp = new Integer[20][2][2];\n        return solve(num, 0, true, dig,true)-1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    using ll = long long;\n\n    int countLen(int n) {\n        int cnt = 0;\n        while(n) {\n            cnt++;\n            n /= 10;\n        }\n        return cnt;\n    }\n\n    vector<int>getDigits(int n) {\n        vector<int>digits;\n        while(n) {\n            digits.push_back(n % 10);\n            n /= 10;\n        }\n\n        reverse(digits.begin(), digits.end());\n        return digits;\n    }\n\n\n    int solve(int idx, bool flag, vector<int>&digits, vector<int>&number) {\n        if(!flag) {\n            int res = 1;\n            for(int i = idx; i<number.size(); i++) {\n                res *= digits.size();\n            }\n            return res;\n        }\n\n\n        if(idx >= number.size()) return 1;\n\n        int curr = 0;\n\n        for(int dig: digits) {\n            if(dig < number[idx]) {\n                curr += solve(idx + 1, false, digits, number);\n            } else if(dig == number[idx]) {\n                curr += solve(idx + 1, true, digits, number);\n            } else break;\n        }\n\n        return curr;\n    }\n\n\n    int atMostNGivenDigitSet(vector<string>& digits, int n) {\n        int len = countLen(n);\n        vector<int>nums;\n        for(string str: digits) {\n            nums.push_back(stoi(str));\n        }\n        sort(nums.begin(), nums.end());\n        ll res = 0;\n        \n        \n        for(int i = 1; i<len; i++) {\n            int curr = 1;\n            bool flag = false;\n            for(int j = 0; j<i; j++) {\n                flag = true;\n                curr *= (int)digits.size();\n            }\n            if(flag)\n                res += curr;\n        }\n\n        vector<int>number = getDigits(n);\n        \n        res += solve(0, true, nums, number);\n\n        return res;\n\n    }\n};"
    },
    {
        "title": "Circle and Rectangle Overlapping",
        "algo_input": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.\n\nReturn true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.\n\n&nbsp;\nExample 1:\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput: true\nExplanation: Circle and rectangle share the point (1,0).\n\n\nExample 2:\n\nInput: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput: false\n\n\nExample 3:\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= radius &lt;= 2000\n\t-104 &lt;= xCenter, yCenter &lt;= 104\n\t-104 &lt;= x1 &lt; x2 &lt;= 104\n\t-104 &lt;= y1 &lt; y2 &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n        \n        def find(a1, a2, aCenter):\n            if a1 <= aCenter and aCenter <= a2:\n                return 0 \n            elif a1 > aCenter:\n                return  a1 - aCenter\n            else:\n                return aCenter - a2\n\n        return (find(x1, x2, xCenter))**2 + (find(y1, y2, yCenter))**2 <= radius**2 \n\t```",
        "solution_js": "var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) {\n    const closestX = clamp(xCenter, x1, x2);\n    const closestY = clamp(yCenter, y1, y2);\n    \n    const dist = (xCenter - closestX)**2 + (yCenter - closestY)**2;\n    \n    return dist <= radius * radius ? true : false;\n    \n    \n    function clamp(val, min, max) {\n        if (val < min) return min;\n        if (max < val) return max;\n        return val;\n    }\n};",
        "solution_java": "class Solution\n{\n    public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2)\n    {\n        return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2)\n            + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {\n        //nearest_x = x1 when xCenter<x1<x2 (OR) x2 when x1<x2<xCenter (OR) xCenter when x1<xCenter<x2\n        int nearest_x = (xCenter < x1) ? x1 : (xCenter > x2) ? x2 : xCenter;\n        //same logic for nearest_y as in nearest_x\n        int nearest_y = (yCenter < y1) ? y1 : (yCenter > y2) ? y2 : yCenter;\n        int dist_x = xCenter - nearest_x, dist_y = yCenter - nearest_y;\n        return dist_x * dist_x + dist_y * dist_y <= radius * radius;\n    }\n};"
    },
    {
        "title": "Rotated Digits",
        "algo_input": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.\n\nA number is valid if each digit remains a digit after rotation. For example:\n\n\n\t0, 1, and 8 rotate to themselves,\n\t2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),\n\t6 and 9 rotate to each other, and\n\tthe rest of the numbers do not rotate to any other number and become invalid.\n\n\nGiven an integer n, return the number of good integers in the range [1, n].\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 4\nExplanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 0\n\n\nExample 3:\n\nInput: n = 2\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def rotatedDigits(self, n: int) -> int:\n        d={\n            0:0,\n            1:1,\n            2:5,\n            3:None,\n            4: None,\n            5:2,\n            6:9,\n            7:None,\n            8:8,\n            9:6\n        }\n        res=0\n        for i in range(n+1):\n            t=i\n            pos=0\n            temp=0\n            status=True\n            while t>0:\n                r=d[t%10] #Every Digit Rotation Is Must, We Don't Have Choice To Leave It Without Rotating\n                if r is None:\n                    status=False\n                    break\n\n                temp+=((10**pos)*r)\n                pos+=1\n                t=t//10\n\n            if temp!=i and status:\n                res+=1\n        return res",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar rotatedDigits = function(n) {\n    let count=0;\n    for(let i=1;i<=n;i++){\n        let str=i.toString().split(\"\");\n        let f=str.filter(s=> s!=1 && s!=0 && s!=8);\n        if(f.length===0) continue;\n        let g=f.filter(s=> s!=5 && s!=2 && s!=6 && s!=9);\n        if(g.length===0) count++;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int rotatedDigits(int n) {\n        int ans=0;\n        for(int i=1; i<=n; i++){\n            int k = i;\n            boolean bool1=true; boolean bool2=false;\n            while(k>0){\n                int m=k%10;\n                if(m==3 || m==4 || m==7){ bool1=false; break; }\n                else if(m==2 || m==5 || m==6 || m==9){ bool2=true; }\n                k/=10;\n            }\n            if(bool1 && bool2){ ans++; }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    bool isValid(int n)\n    {\n        bool check = false;\n        while (n > 0)\n        {\n            int k = n % 10;\n            if (k == 2 || k == 5 || k == 6 || k == 9)\n                check = true;\n            if (k == 3 || k == 4 || k == 7)\n                return false;\n            n /= 10;\n        }\n        return check;\n    }\n    int rotatedDigits(int n)\n    {\n        vector<int> dp(n + 1, 0);\n        for (int i = 2; i <= n; i++)\n        {\n            if (isValid(i))\n                dp[i]++;\n            dp[i] += dp[i - 1];\n        }\n        return dp[n];\n    }\n};"
    },
    {
        "title": "Maximum Fruits Harvested After at Most K Steps",
        "algo_input": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.\n\nYou are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.\n\nReturn the maximum total number of fruits you can harvest.\n\n&nbsp;\nExample 1:\n\nInput: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput: 9\nExplanation: \nThe optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.\n\n\nExample 2:\n\nInput: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput: 14\nExplanation: \nYou can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.\n\n\nExample 3:\n\nInput: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput: 0\nExplanation:\nYou can move at most k = 2 steps and cannot reach any position with fruits.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= fruits.length &lt;= 105\n\tfruits[i].length == 2\n\t0 &lt;= startPos, positioni &lt;= 2 * 105\n\tpositioni-1 &lt; positioni for any i &gt; 0&nbsp;(0-indexed)\n\t1 &lt;= amounti &lt;= 104\n\t0 &lt;= k &lt;= 2 * 105\n\n",
        "solution_py": "class Solution:\n    def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n        arr = [0 for _ in range(2*k+1)]\n        for pos, numOfFruit in fruits:\n            if pos < startPos-k or pos > startPos+k:\n                continue\n            arr[pos-(startPos-k)] += numOfFruit\n\n        left, right = sum(arr[:k+1]), sum(arr[k:])\n        maxSeen = max(left, right)\n\n        turn = 1 # turning point\n        for i in range(2, k+1, 2):\n            left = left-arr[i-2]-arr[i-1]+arr[k+turn]\n            right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn]\n            maxSeen = max(maxSeen, left, right)\n            turn += 1\n\n        return maxSeen",
        "solution_js": "/**\n * @param {number[][]} fruits\n * @param {number} startPos\n * @param {number} k\n * @return {number}\n */\nvar maxTotalFruits = function(fruits, startPos, k) {\n    \n    let n = Math.max(fruits[fruits.length-1][0], startPos)+1;\n    let numFruits = new Array(n).fill(0);\n    let sums = new Array(n).fill(0);\n    for(let obj of fruits) {\n        let [pos, num] = obj;\n        numFruits[pos] = num;\n    }\n    sums[startPos] = numFruits[startPos] ;\n    for(let i = startPos+1; i < n && i <= startPos + k; i++) {\n        sums[i] = sums[i-1] + numFruits[i];\n    }\n    for(let i = startPos-1; i >=0 && i >= startPos - k; i--) {\n        sums[i] = sums[i+1] + numFruits[i];\n    }\n    //console.log(sums);\n    let output = 0;\n    for(let leftMoves = k; leftMoves >= 0; leftMoves--) {\n        let rightMoves = Math.max(k - 2*leftMoves, 0);\n        let leftPos = Math.max(0, startPos - leftMoves);\n        let rightPos = Math.min(n-1, startPos + rightMoves);\n        let count = sums[leftPos] + sums[rightPos] - sums[startPos];\n        output = Math.max(output, count);\n    }\n    for(let rightMoves = k; rightMoves >= 0; rightMoves--) {\n        let leftMoves = Math.max(k - 2*rightMoves, 0);\n        let leftPos = Math.max(0, startPos - leftMoves);\n        let rightPos = Math.min(n-1, startPos + rightMoves);\n        let count = sums[leftPos] + sums[rightPos] - sums[startPos];\n        output = Math.max(output, count);\n    }\n    return output;\n};",
        "solution_java": "class Solution {\n    public int maxTotalFruits(int[][] fruits, int startPos, int k) {\n        int n = fruits.length;\n        int posOfLastFruit = fruits[n-1][0];\n        int prefixArr[] = new int[posOfLastFruit + 1];\n        int start = Math.max(startPos - k, 0);\n        int end = Math.min(startPos + k, prefixArr.length-1);\n\n        if(startPos > posOfLastFruit) {\n            int diff = startPos - posOfLastFruit;\n            startPos = posOfLastFruit;\n             k = k - diff;\n            if(k == 0)\n                return fruits[posOfLastFruit][1];\n            else if(k < 0)\n                return 0;\n        }\n\n        for(int i = 0 ; i < n ; i++) {\n            prefixArr[fruits[i][0]] = fruits[i][1];\n        }\n\n        int curr = 0;\n        for(int i = startPos-1 ; i >= start ; i--) {\n            curr += prefixArr[i];\n            prefixArr[i] = curr;\n        }\n\n        curr = 0;\n        for(int i = startPos+1 ; i <= end ; i++) {\n            curr += prefixArr[i];\n            prefixArr[i] = curr;\n        }\n\n        int minimum = prefixArr[startPos];\n        prefixArr[startPos] = 0;\n        int ans = 0;\n\n        for(int i = start ; i < startPos ; i++) {\n            int maxCurrPossible = prefixArr[i];\n            int stepsAlreadyWalked = startPos - i;\n            int stepsRemaining = k - stepsAlreadyWalked;\n            int endIndex = i + stepsRemaining;\n\n            if(endIndex > startPos && endIndex < prefixArr.length) {\n                maxCurrPossible += prefixArr[endIndex];\n            } else if(endIndex >= prefixArr.length) {\n                maxCurrPossible += prefixArr[prefixArr.length-1];\n            }\n\n            ans = Math.max(ans, maxCurrPossible);\n        }\n\n        for(int i = startPos+1 ; i <= end ; i++) {\n            int maxCurrPossible = prefixArr[i];\n            int stepsAlreadyWalked = i - startPos;\n            int stepsRemaining = k - stepsAlreadyWalked;\n            int endIndex = i - stepsRemaining;\n\n            if(endIndex < startPos && endIndex >= 0) {\n                maxCurrPossible += prefixArr[endIndex];\n            } else if(endIndex < 0) {\n                maxCurrPossible += prefixArr[0];\n            }\n\n            ans = Math.max(ans, maxCurrPossible);\n        }\n\n        return ans + minimum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) {\n        vector<int> arr;\n        for (int i=0; i<2*k+1; ++i) {\n            arr.push_back(0);\n        }\n\n        for (int i=0; i<fruits.size(); ++i) {\n            if ((fruits[i][0] < startPos-k) || (fruits[i][0] > startPos+k)) continue;\n            arr[fruits[i][0]-(startPos-k)] += fruits[i][1];\n        }\n\n        int left = 0, right = 0;\n        for (int i = 0; i <= k; ++i) {\n            left += arr[i];\n            right += arr[k+i];\n        }\n        int maxSeen = max(left, right);\n        int L = arr.size();\n        int turn = 1;\n        for (int i = 2; i < k+1; i += 2) {\n            left = left+arr[k+turn]-arr[i-1]-arr[i-2];\n            right = right+arr[k-turn]-arr[L-1-(i-1)]-arr[L-1-(i-2)];\n            if (left > maxSeen) maxSeen = left;\n            if (right > maxSeen) maxSeen = right;\n            turn++;\n        }\n        return maxSeen;\n\n    }\n};"
    },
    {
        "title": "Surrounded Regions",
        "algo_input": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally&nbsp;surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nOutput: [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nExplanation: Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.\n\n\nExample 2:\n\nInput: board = [[\"X\"]]\nOutput: [[\"X\"]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m, n &lt;= 200\n\tboard[i][j] is 'X' or 'O'.\n\n",
        "solution_py": "# The question is an awesome example of multi-source bfs.\n# The intuition is to add the boundary to a heap if it is 'O'.\n# Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start\n# convertin all these 'O's to 'E's. \n# The last step is to traverse the matrix and if the element is still 'O' turn it to 'X' if it is 'E' turn it to 'O' and we get our answer.\n# Pro-Tip -> Try to reduce the number of append operations in python. The lesser the append operations the better is the runtime!\nfrom collections import deque\nclass Solution:\n    def solve(self, bb: List[List[str]]) -> None:\n        \"\"\"\n        Do not return anything, modify board in-place instead.\n        \"\"\"\n        heap = deque()\n        directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n        r, c = len(bb), len(bb[0])\n        for i in range(r):\n            if bb[i][0] == 'O': heap.append((i, 0))\n            if bb[i][c - 1] == 'O': heap.append((i, c - 1))\n        for i in range(1, c - 1):\n            if bb[0][i] == 'O': heap.append((0, i))\n            if bb[r - 1][i] == 'O': heap.append((r - 1, i))\n        visited = set()\n        def isValid(nr, nc):\n            if 0 <= nr < r and 0 <= nc < c: return True\n            else: return False\n        while heap:\n            ri, ci = heap.popleft()\n            bb[ri][ci] = 'E'\n            for i, j in directions:\n                nr, nc = ri + i, ci + j\n                if isValid(nr, nc) and (nr, nc) not in visited and bb[nr][nc] == 'O':\n                    heap.append((nr, nc))\n                    visited.add((nr, nc))\n        for i in range(r):\n            for j in range(c):\n                if bb[i][j] == 'O':\n                    bb[i][j] = 'X'\n                if bb[i][j] == 'E':\n                    bb[i][j] = 'O'\n            ",
        "solution_js": "// time O(n * m) | space O(1)\n\n// We essentially invert this question\n// Instead of looking whether an 'O' node is surrounded,\n// we check if an 'O' node is on the edge (outer layer can't be surrounded)\n// and check if that is connected with any other nodes 'O' nodes (top, down, left, right).\n// We do no care if it is not connected to an 'O' edge node and thus never dfs for it.\nvar solve = function(board) {\n    if (!board.length) return [];\n\n    for (let i = 0; i < board.length; i++) {\n        for (let j = 0; j < board[0].length; j++) {\n            // Only dfs if an 'O' and on the edge\n            if (board[i][j] === 'O' && (i === 0 || i === board.length - 1 || j === 0 || j === board[0].length - 1)) {\n                dfs(i, j);\n            }\n        }\n    }\n\n    for (let i = 0; i < board.length; i++) {\n        for (let j = 0; j < board[0].length; j++) {\n            if (board[i][j] === 'V') {\n                board[i][j] = 'O';\n            } else {\n                board[i][j] = 'X';\n            }\n        }\n    }\n\n    return board;\n\n    function dfs(r, c) {\n        if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] === 'X' || board[r][c] === 'V') {\n            return;\n        }\n\n        board[r][c] = 'V';\n\n        dfs(r + 1, c);\n        dfs(r - 1, c);\n        dfs(r, c - 1);\n        dfs(r, c + 1);\n    }\n};",
        "solution_java": "class Solution {\n        boolean isClosed = true;\n\n    public void solve(char[][] board) {\n        int m = board.length;\n        int n = board[0].length;\n\n        // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                if(board[i][j] == 'O' && (i == 0 || j == 0 || i == m-1 || j == n-1) ){\n                     dfs(board, i, j);\n                }\n            }\n        }\n\n        // revert the temperoray value and also replace remaining O with X\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                if(board[i][j] == 'T') board[i][j] = 'O';\n                else if(board[i][j] == 'O') board[i][j] = 'X';\n            }\n        }\n\n    }\n\n    public void dfs(char[][] board, int i, int j){\n        if(i<0 || j<0 || i>= board.length || j>=board[0].length || board[i][j] != 'O') return;\n\n        board[i][j] = 'T'; // to put a temperory mark/ to mark as visited\n\n        dfs(board, i, j+1); // Top\n        dfs(board, i, j-1); // Bottom\n        dfs(board, i+1, j); // Right\n        dfs(board, i-1, j); // Left\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int n,m; int visited[201][201] = {0};\n    // Breadth First Search\n    // Flood Fill Algorithm\n    void bfs(vector<vector<char>>& board, int x, int y){\n        queue<int> q; q.push(m*x+y);\n        visited[x][y] = 1;\n        int curr,i,j;\n        while(!q.empty()){\n            curr = q.front();\n            q.pop();\n            i = curr/m; j = curr%m;\n            board[i][j] = 'O';\n            if(i > 0 && !visited[i-1][j] && board[i-1][j] == 'C'){\n                visited[i-1][j] = 1;\n                q.push(m*(i-1)+j);\n            }\n            if(i < n-1 && !visited[i+1][j] && board[i+1][j] == 'C'){\n                visited[i+1][j] = 1;\n                q.push(m*(i+1)+j);\n            }\n            if(j > 0 && !visited[i][j-1] && board[i][j-1] == 'C'){\n                visited[i][j-1] = 1;\n                q.push(m*i+j-1);\n            }\n            if(j < m-1 && !visited[i][j+1] && board[i][j+1] == 'C'){\n                visited[i][j+1] = 1;\n                q.push(m*i+j+1);\n            }\n        }\n    }\n    void solve(vector<vector<char>>& board) {\n        n = board.size(); m = board[0].size();\n        // Marking the regions to capture\n        // mark all the O to C\n        for(int i=0; i<n; i++){\n            for(int j=0; j<m; j++){\n                if(board[i][j] == 'O') board[i][j] = 'C';\n            }\n        }\n        // if we have found C on the outer edges, then all the connected C to it should be\n        // converted to O as they can't be captured\n        for(int i=0; i<m; i++){\n            if(board[0][i] == 'C' && !visited[0][i]) bfs(board, 0, i);\n            if(board[n-1][i] == 'C' && !visited[n-1][i]) bfs(board, n-1, i);\n        }\n        for(int i=1; i<n-1; i++){\n            if(board[i][0] == 'C' && !visited[i][0]) bfs(board, i, 0);\n            if(board[i][m-1] == 'C' && !visited[i][m-1]) bfs(board, i, m-1);\n        }\n        // capturing the regions\n        // now remaining C can be capture\n        for(int i=0; i<n; i++){\n            for(int j=0; j<m; j++){\n                if(board[i][j] == 'C') board[i][j] = 'X';\n            }\n        }\n    }\n};\nstatic const auto speedup =[](){\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n    std::cout.tie(nullptr);\n    return 0;\n}();"
    },
    {
        "title": "Find Lucky Integer in an Array",
        "algo_input": "Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.\n\nReturn the largest lucky integer in the array. If there is no lucky integer return -1.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\n\n\nExample 2:\n\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\n\n\nExample 3:\n\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 500\n\t1 &lt;= arr[i] &lt;= 500\n\n",
        "solution_py": "class Solution:\n    def findLucky(self, arr: List[int]) -> int:\n        dc = {}\n        \n        for i in range(len(arr)):\n            if arr[i] not in dc:\n                dc[arr[i]] = 1\n            else:\n                dc[arr[i]] = dc[arr[i]] + 1\n        mx = -1\n        for key,value in dc.items():\n            if key == value:\n                mx = max(key, mx)\n        return mx",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\n \nvar findLucky = function(arr) {\n\tlet obj = {};\n\tarr.map((num) => {\n\t\tobj[num] = obj[num] + 1 || 1;\n\t});\n\n\tlet answer = -1;\n\tfor (let key in obj) {\n\t\tif (Number(key) === obj[key]) answer = Math.max(answer, Number(key));\n\t}\n\n\treturn answer;\n};",
        "solution_java": "class Solution {\n    public int findLucky(int[] arr) {\n        HashMap<Integer,Integer> map = new HashMap<>();\n        for(int i : arr){\n            map.put(i, map.getOrDefault(i,0)+1);\n        }\n        System.out.print(map);\n         int max = 0;\n        for (Map.Entry<Integer, Integer> e : map.entrySet()){\n           int temp = 0;\n            if(e.getKey() == (int)e.getValue()){\n                temp = (int)e.getKey();\n            }\n            if(max < temp){\n                max= temp;\n            }\n        }\n         if(max != 0)return max;\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLucky(vector<int>& arr) {\n        // sort(arr.begin(),arr.end());\n        map<int,int>mp;\n        vector<int>v;\n        for(int i=0;i<arr.size();i++)\n        {\n            mp[arr[i]]++;\n        }\n\n        for(auto x:mp)\n        {\n            if(x.first == x.second)\n            {\n                v.push_back(x.first);\n            }\n           \n        }\n\n        int mx = -1;\n        for(int i=0;i<v.size();i++)\n        {\n            mx = max(mx,v[i]);\n        }\n\n\n\n        return mx;\n        \n    }\n};"
    },
    {
        "title": "Successful Pairs of Spells and Potions",
        "algo_input": "You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.\n\nYou are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.\n\nReturn an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.\n\n&nbsp;\nExample 1:\n\nInput: spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput: [4,0,3]\nExplanation:\n- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.\n\n\nExample 2:\n\nInput: spells = [3,1,2], potions = [8,5,8], success = 16\nOutput: [2,0,2]\nExplanation:\n- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == spells.length\n\tm == potions.length\n\t1 &lt;= n, m &lt;= 105\n\t1 &lt;= spells[i], potions[i] &lt;= 105\n\t1 &lt;= success &lt;= 1010\n\n",
        "solution_py": "class Solution:\n    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n        result = self.function(spells,potions,success)\n        return result\n\n    def function(self,arr1,arr2,success):\n        n2 = len(arr2)\n        arr2.sort() #Sorting Enables Us To Do Binary Search\n        ans = []\n        for i in arr1:\n            val = math.ceil(success/i) #Finding the Value Of Portion With Least Strength So That It Can Be Greater Than Success\n            idx = bisect.bisect_left(arr2,val) #Finding The Left Most Index So That The Value Can Be Inserted\n            res = n2-idx+1 #Calculating the remaining numbers after finding the suitable index\n            ans.append(res-1)\n        return ans",
        "solution_js": "/**\n * @param {number[]} spells\n * @param {number[]} potions\n * @param {number} success\n * @return {number[]}\n */\n var successfulPairs = function(spells, potions, success) {\n    let res = [];\n    potions.sort((a, b) => b-a);\n    let map = new Map();\n    \n    for(let i=0; i<spells.length; i++){\n        if(!map.has(spells[i])){\n            let s = success / spells[i];\n            let len = search(potions, s);\n            res.push(len);\n            map.set(spells[i], len);\n        }else{\n            let len = map.get(spells[i]);\n            res.push(len);\n        }\n    }\n    \n    return res;\n};\n\nfunction search(potions, target){\n    let res = 0;\n    let left = 0;\n    let right = potions.length-1;\n    while(left <= right){\n        let mid = Math.floor((left + right) / 2);\n        if(potions[mid] < target){\n            right = mid - 1;\n        }else{\n            left = mid + 1;\n            res = mid + 1;\n        }\n    }\n\n    return res;\n}",
        "solution_java": "class Solution {\n    public int[] successfulPairs(int[] spells, int[] potions, long success) {\n        int n = spells.length;\n        int m = potions.length;\n        int[] pairs = new int[n];\n        Arrays.sort(potions);\n        for (int i = 0; i < n; i++) {\n            int spell = spells[i];\n            int left = 0;\n            int right = m - 1;\n            while (left <= right) {\n                int mid = left + (right - left) / 2;\n                long product = (long) spell * potions[mid];\n                if (product >= success) {\n                    right = mid - 1;\n                } else {\n                    left = mid + 1;\n                }\n            }\n            pairs[i] = m - left;\n        }\n        return pairs;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {\n        \n        vector<int> res;\n        int n(size(potions));\n        sort(begin(potions), end(potions));\n        \n        for (auto& spell : spells) {\n            int start(0), end(n);\n            while (start < end) {\n                int mid = start + (end-start)/2;\n                ((long long)spell*potions[mid] >= success) ? end = mid : start = mid+1;\n            }\n            res.push_back(n-start);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Shortest Path to Get All Keys",
        "algo_input": "You are given an m x n grid grid where:\n\n\n\t'.' is an empty cell.\n\t'#' is a wall.\n\t'@' is the starting point.\n\tLowercase letters represent keys.\n\tUppercase letters represent locks.\n\n\nYou start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.\n\nIf you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.\n\nFor some 1 &lt;= k &lt;= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\n\nReturn the lowest number of moves to acquire all keys. If it is impossible, return -1.\n\n&nbsp;\nExample 1:\n\nInput: grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput: 8\nExplanation: Note that the goal is to obtain all the keys not to open all the locks.\n\n\nExample 2:\n\nInput: grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput: 6\n\n\nExample 3:\n\nInput: grid = [\"@Aa\"]\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 30\n\tgrid[i][j] is either an English letter, '.', '#', or '@'.\n\tThe number of keys in the grid is in the range [1, 6].\n\tEach key in the grid is unique.\n\tEach key in the grid has a matching lock.\n\n",
        "solution_py": "class Solution:\n    def shortestPathAllKeys(self, grid: List[str]) -> int:\n        \n        m=len(grid)\n        n=len(grid[0])\n        visited=set()\n        \n        steps=0\n        q=deque([])\n        keyCt=0\n        \n        for i in range(m):\n            for j in range(n):\n                if grid[i][j]==\"@\":\n                    q.append((i,j,''))\n                elif grid[i][j].islower():\n                    keyCt+=1\n        \n        while q:\n            for _ in range(len(q)):\n                curr_x,curr_y,keys = q.popleft()\n                if (curr_x,curr_y,keys) in visited:\n                    continue\n                \n                visited.add((curr_x,curr_y,keys))\n                \n                if len(keys)==keyCt:\n                    return steps\n                \n                for x,y in ((0,1),(1,0),(-1,0),(0,-1)):\n                    nx=curr_x+x\n                    ny=curr_y+y\n                    if nx<0 or ny<0 or nx>=m or ny>=n or grid[nx][ny]=='#' or (nx,ny,keys) in visited:\n                        continue\n                        \n                    curr=grid[nx][ny]                    \n                    if curr in 'abcdef' and curr not in keys:\n                        q.append((nx,ny,keys+curr))                            \n                    elif curr.isupper() and curr.lower() not in keys:\n                        continue\n                    else:\n                        q.append((nx,ny,keys))\n            steps+=1\n        \n        return -1",
        "solution_js": "var shortestPathAllKeys = function(grid) {\n    const n = grid.length;\n    const m = grid[0].length;\n\n    function isKey(letter) {\n        return (\n            letter.charCodeAt(0) >= 'a'.charCodeAt(0) && letter.charCodeAt(0) <= 'z'.charCodeAt(0)\n        );\n    }\n\n    function isLock(letter) {\n        return (\n            letter.charCodeAt(0) >= 'A'.charCodeAt(0) && letter.charCodeAt(0) <= 'Z'.charCodeAt(0)\n        );\n    }\n\n    const dns = [\n        [1, 0],\n        [0, 1],\n        [-1, 0],\n        [0, -1],\n    ];\n\n    let start = { x: 0, y: 0, keys: new Set() };\n    let keyMap = new Map();\n\n    for (let y = 0; y < n; ++y) {\n        for (let x = 0; x < m; ++x) {\n            const cell = grid[y][x];\n            if (cell === '@') {\n                start.x = x;\n                start.y = y;\n            } else if (isKey(cell)) {\n                keyMap.set(cell, [x, y]);\n            }\n        }\n    }\n\n    function attemptToGetKey(x, y, keys, kx, ky) {\n        let q = [[x, y, keys, 0]];\n        let v = new Set();\n        while (q.length) {\n            let nextQueue = [];\n            for (let i = 0; i < q.length; ++i) {\n                const [x, y, keys, steps] = q[i];\n                if (x === kx && ky === y) {\n                    keys.add(grid[ky][kx]);\n                    return { keysAcquired: keys, movesUsed: steps };\n                }\n                const locationHash = x + y * m;\n                if (v.has(locationHash)) continue;\n                v.add(locationHash);\n                const cell = grid[y][x];\n                if (cell !== '.') {\n                    if (isLock(cell) && !keys.has(cell.toLowerCase())) {\n                        continue;\n                    }\n                    if (isKey(cell)) {\n                        keys.add(cell);\n                    }\n                }\n                for (const [mx, my] of dns) {\n                    const nx = x + mx;\n                    const ny = y + my;\n                    const nextHash = ny * m + nx;\n                    if (grid[ny]?.[nx] != null && grid[ny]?.[nx] !== '#') {\n                        if (!v.has(nextHash)) {\n                            q.push([nx, ny, new Set(Array.from(keys)), steps + 1]);\n                        }\n                    }\n                }\n            }\n            q = nextQueue;\n        }\n        return { keysAcquired: null, movesUsed: 0 };\n    }\n\n    let q = new MinPriorityQueue();\n    q.enqueue([start.x, start.y, start.keys], 0);\n    while (q.size()) {\n        const { element, priority: steps } = q.dequeue();\n        const [x, y, keys] = element;\n        if (keys.size === keyMap.size) {\n            return steps;\n        }\n        for (const [key, [kx, ky]] of keyMap) {\n            if (!keys.has(key)) {\n                let { movesUsed, keysAcquired } = attemptToGetKey(x, y, keys, kx, ky);\n                if (movesUsed) {\n                    q.enqueue([kx, ky, keysAcquired], movesUsed + steps);\n                }\n            }\n        }\n    }\n    return -1;\n}",
        "solution_java": "class Solution {\n    \n    private static final int[][] DIRS = new int[][]{ \n        {1,0}, {-1,0}, {0,1}, {0,-1}\n    };\n    \n    public int shortestPathAllKeys(String[] grid) {\n        int m = grid.length, n = grid[0].length();\n        int numKeys = 0, startRow = -1, startCol = -1;\n        \n        for(int i=0; i<m; i++) {\n            for(int j=0; j<n; j++) {\n                char c = grid[i].charAt(j);\n                \n                if( isStart(c) ) {\n                    startRow = i;\n                    startCol = j;\n                } \n                else if( isKey(c) )\n                    numKeys++;\n            }\n        }\n        if( startRow == -1 ) return -1;\n        \n        int keyMask = (1 << numKeys) - 1;\n        State start = new State(startRow, startCol, 0);\n        Queue<State> queue = new LinkedList();\n        Set<State> visited = new HashSet();   \n        int steps = 0;\n        \n        queue.offer(start);\n        visited.add(start);\n        \n        while( !queue.isEmpty() ) {\n            int size = queue.size();\n            \n            while( size-- > 0 ) {\n                int i = queue.peek().i;\n                int j = queue.peek().j;\n                int keys = queue.peek().keys;\n                queue.poll();\n                \n                if( keys == keyMask )\n                    return steps;\n                \n                for(int[] dir : DIRS) {\n                    int di = i + dir[0];\n                    int dj = j + dir[1];\n                    int newKeys = keys;\n\n                    if( di < 0 || dj < 0 || di == m || dj == n )\n                        continue;\n\n                    char c = grid[di].charAt(dj);\n\n                    if( isWall(c) ) continue;\n                    \n                    if( isLock(c) && !isKeyPresent(keys, c) )\n                        continue;\n\n                    if( isKey(c) ) \n                        newKeys |= (1 << (c - 'a'));\n                    \n                    State newState = new State(di, dj, newKeys);\n                    \n                    if( visited.add(newState) ) \n                        queue.offer(newState);\n                }\n            }\n            steps++;\n        }\n        return -1;\n    }\n    \n    private boolean isLock(char c) {\n        return c >= 'A' && c <= 'Z';\n    }\n    private boolean isKey(char c) {\n        return c >= 'a' && c <= 'z';\n    }\n    private boolean isWall(char c) {\n        return c == '#';\n    }\n    private boolean isStart(char c) {\n        return c == '@';\n    }\n    private boolean isKeyPresent(int keys, char lock) {\n        return (keys & (1 << (lock-'A'))) != 0;\n    }\n}\nclass State {\n    public int i, j, keys;\n    \n    public State(int i, int j, int keys) {\n        this.i = i;\n        this.j = j;\n        this.keys = keys;\n    }\n    \n    @Override\n    public boolean equals(Object obj) {\n        if( !(obj instanceof State) ) return false;\n        State that = (State)obj;\n        return i == that.i && j == that.j && keys == that.keys;\n    }\n    \n    @Override\n    public int hashCode() {\n        int prime = 31;\n        int hash = 1;\n        hash = hash * prime + i;\n        hash = hash * prime + j;\n        hash = hash * prime + keys;\n        return hash;\n    }\n}",
        "solution_c": "class Solution {\n    int dirx[4] = {-1,1,0,0};\n    int diry[4] = {0,0,1,-1};\npublic:\n    int shortestPathAllKeys(vector<string>& grid) {\n        int n = grid.size();\n        int m = grid[0].size();\n        vector<vector<int>> matrix(n, vector<int>(m));\n        vector<int> lock(7,0);\n        int sx, sy;\n        int lk = 0;\n        for(int i = 0; i < n; i++)\n        {\n            for(int j = 0; j < m; j++)\n            {\n                if(grid[i][j] == '@')\n                {\n                    sx = i, sy = j;\n                    matrix[i][j] = 0;\n                }\n                else if(grid[i][j] == '.')\n                {\n                    matrix[i][j] = 0;\n                    //cout << grid[i][j];\n                }\n                else if(grid[i][j] >= 'A' && grid[i][j] <= 'F')\n                {\n                    matrix[i][j] = -1*((grid[i][j]-'A') + 1);\n                    lock[(grid[i][j]-'A') + 1] = (1 << (grid[i][j]-'A'));\n                }\n                else if(grid[i][j] == '#')\n                    matrix[i][j] = -8;\n                else\n                {\n                    matrix[i][j] = (1 << (grid[i][j]-'a'));\n                    lk++;\n                }\n                //cout << matrix[i][j] << \" \";\n            }\n            //cout << endl;\n        }\n        int fnl = (1 << lk) - 1;\n        //cout << fnl;\n        vector<vector<int>> visited(n*m, vector<int>(fnl,1));\n        queue<pair<pair<int,int>,int>> q;\n        int ans = 0;\n        q.push({{sx,sy},0});\n        visited[sx*m+sy][0] = 0;\n        while(!q.empty())\n        {\n            ans++;\n            int sz = q.size();\n            while(sz--)\n            {\n                int x = q.front().first.first;\n                int y = q.front().first.second;\n                int bit = q.front().second;\n                q.pop();\n                for(int i = 0; i < 4; i++)\n                {\n                    int nxtx = x + dirx[i];\n                    int nxty = y + diry[i];\n                    if(nxtx >= n || nxtx < 0 || nxty >= m || nxty < 0) continue;\n                    if(matrix[nxtx][nxty] == -8) continue;\n                    if(visited[nxtx*m+nxty][bit] == 0) continue;\n                    if(matrix[nxtx][nxty] < 0)\n                    {\n                        int lkidx = -1*matrix[nxtx][nxty];\n                        if(bit&lock[lkidx])\n                        {\n                            q.push({{nxtx,nxty},bit});\n                            visited[nxtx*m+nxty][bit] = 0;\n                        }\n                    }\n                    else if(matrix[nxtx][nxty] == 0)\n                    {\n                        q.push({{nxtx,nxty},bit});\n                        visited[nxtx*m+nxty][bit] = 0;\n                        continue;\n                    }\n                    else\n                    {\n                        int fbit = bit | matrix[nxtx][nxty];\n                        if(fbit == fnl) return ans;\n                        q.push({{nxtx,nxty},fbit});\n                        visited[nxtx*m+nxty][fbit] = 0;\n                    }\n                }\n            }\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Verify Preorder Serialization of a Binary Tree",
        "algo_input": "One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.\n\nFor example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where '#' represents a null node.\n\nGiven a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.\n\nIt is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.\n\nYou may assume that the input format is always valid.\n\n\n\tFor example, it could never contain two consecutive commas, such as \"1,,3\".\n\n\nNote:&nbsp;You are not allowed to reconstruct the tree.\n\n&nbsp;\nExample 1:\nInput: preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\nExample 2:\nInput: preorder = \"1,#\"\nOutput: false\nExample 3:\nInput: preorder = \"9,#,#,1\"\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= preorder.length &lt;= 104\n\tpreorder consist of integers in the range [0, 100] and '#' separated by commas ','.\n\n",
        "solution_py": "class Solution:\n    def isValidSerialization(self, preorder: str) -> bool:\n        nodes = preorder.split(',')\n        counter=1\n        for i, node in enumerate(nodes):\n            if node != '#':\n                counter+=1\n            else:\n                if counter <= 1 and i != len(nodes) - 1:\n                    return False\n                counter-=1\n        return counter == 0",
        "solution_js": "/**\n * @param {string} preorder\n * @return {boolean}\n */\nvar isValidSerialization = function(preorder) {\n    let balance = 1\n    for(const node of preorder.split(','))\n        if (balance > 0)\n            if (node === '#') --balance\n            else ++balance\n        else return false\n    return balance < 1\n}",
        "solution_java": "class Solution {\n    public boolean isValidSerialization(String preorder) {\n        String[] strs = preorder.split(\",\");\n        //In starting we have one vacany for root\n        int vacancy = 1;\n        \n        for(String str : strs){\n            \n            if(--vacancy < 0 ) return false;\n            \n            // whenever we encounter a new node vacancy decreases by 1 and  left and right two vacancy for                   that node will added in total\n            if(!str.equals(\"#\"))            \n                vacancy += 2;\n           \n        }\n        \n        \n        return vacancy == 0;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isValidSerialization(string preorder) {\n        stringstream s(preorder);\n        string str;\n        int slots=1;\n        while(getline(s, str, ',')) {\n            if(slots==0) return 0;\n            if(str==\"#\") slots--;\n            else slots++;\n        }\n        return slots==0;\n    }\n};"
    },
    {
        "title": "Partition Equal Subset Sum",
        "algo_input": "Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,5,11,5]\nOutput: true\nExplanation: The array can be partitioned as [1, 5, 5] and [11].\n\n\nExample 2:\n\nInput: nums = [1,2,3,5]\nOutput: false\nExplanation: The array cannot be partitioned into equal sum subsets.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def canPartition(self, nums: List[int]) -> bool:\n        total = sum(nums)\n        if total % 2: return False\n        total //= 2\n        leng = len(nums)\n        dp = [[False] * (total + 1) for _ in range(leng + 1)]\n        \n        for i in range(leng + 1): dp[i][0] = True\n        for i in range(1, leng + 1):\n            for j in range(1, total + 1):\n                dp[i][j] = dp[i-1][j]\n                if j - nums[i-1] >= 0:\n                    dp[i][j] |= dp[i-1][j-nums[i-1]] \n        return dp[leng][total]",
        "solution_js": "var canPartition = function(nums) {\n    let sum = nums.reduce((prevVal, currValue) => prevVal + currValue, 0); // sum of each values\n    if (sum % 2 !== 0) return false; // return false if odd sum\n    \n    let target = sum / 2;  // ex.[1,5,11,5]  target is half which is 11\n    let dp = new Set(); // add unique values\n    dp.add(0); //intialize with 0\n    for (var i = nums.length - 1; i >= 0; i--) {  //start from end\n        nextDp = new Set(); \n        for (const ele of dp.values()) {\n           let newVal = ele + nums[i];\n           if(newVal === target) return true; \n           nextDp.add(newVal); \n        }\n        dp = new Set([...dp, ...nextDp]);\n    }\n    \n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean canPartition(int[] nums) {\n        int sum = 0;\n        for(int i=0; i<nums.length; i++){\n            sum = sum+nums[i];\n        }\n       \n        if(sum%2 !=0){\n            return false;\n        }\n        int[][] dp = new int[nums.length+1][sum];\n        for(int i=0; i<dp.length; i++){\n            Arrays.fill(dp[i],-1);\n        }\n       \n        return helper(nums,sum/2,0,dp)>= 1? true : false;\n    }\n    public int helper(int[] nums, int sum, int i, int[][] dp){\n        if(i==nums.length && sum==0){\n            return 1;\n        }\n        if(i==nums.length){\n            return 0;\n        }\n        if(sum < 0){\n            return 0;\n        }\n        if(dp[i][sum] != -1){\n            return dp[i][sum];\n        }\n        if(sum<nums[i]){\n           return dp[i][sum] = helper(nums,sum,i+1,dp);\n        }\n        int a = helper(nums,sum-nums[i],i+1,dp); //Take the value\n        int b = helper(nums,sum,i+1,dp); //Not take the value\n        if(a==1 || b==1){   // if any of the options is returning true then whole answer would be true\n                return dp[i][sum]=1;\n        }else{\n                return dp[i][sum]=0;\n        }\n    }\n}",
        "solution_c": " class Solution {\npublic:\n    bool canPartition(vector<int>& nums) {\n        int sum = 0;\n        int n = nums.size();\n        for(int i = 0;i<n;i++)\n            sum = sum + nums[i];\n        cout<<sum;\n        \n        if(sum % 2 == 0){\n            int s = sum/2;\n            int t[n+1][s+1];\n            for(int i = 0; i<s+1;i++)\n                t[0][i] = false;\n            for(int i = 0;i<n+1;i++)\n                t[i][0] = true;\n            \n            for(int i =1;i<n+1;i++){\n                for(int j = 1; j<s+1;j++){\n                    if(nums[i-1] <= j)\n                        t[i][j] = t[i-1][j-nums[i-1]] || t[i-1][j];\n                    else\n                        t[i][j] = t[i-1][j];\n                }\n            }\n            return t[n][s];\n        }else\n            return false;\n    }\n};"
    },
    {
        "title": "Replace the Substring for Balanced String",
        "algo_input": "You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.\n\nA string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.\n\nReturn the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.\n\n&nbsp;\nExample 1:\n\nInput: s = \"QWER\"\nOutput: 0\nExplanation: s is already balanced.\n\n\nExample 2:\n\nInput: s = \"QQWE\"\nOutput: 1\nExplanation: We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.\n\n\nExample 3:\n\nInput: s = \"QQQW\"\nOutput: 2\nExplanation: We can replace the first \"QQ\" to \"ER\". \n\n\n&nbsp;\nConstraints:\n\n\n\tn == s.length\n\t4 &lt;= n &lt;= 105\n\tn is a multiple of 4.\n\ts contains only 'Q', 'W', 'E', and 'R'.\n\n",
        "solution_py": "class Solution:\n    def balancedString(self, s):\n        count = collections.Counter(s)\n        res = n = len(s)\n        if all(n/4==count[char] for char in 'QWER'):\n            return 0\n        left = 0\n        for right, char in enumerate(s):\n            # replace char whose index==right to check if it is balanced\n            count[char] -= 1\n            # if it is balanced, window shrinks to get the smallest length of window\n            while left <= right and all(n / 4 >= count[char] for char in 'QWER'):\n                res = min(res, right - left + 1)\n                count[s[left]] =count[s[left]]+ 1\n                left += 1\n        return res",
        "solution_js": "var balancedString = function(s) {\n    \n    let output = Infinity;\n    \n    let map = {\"Q\":0, \"W\":0, \"E\":0, \"R\":0};\n    \n    for(let letter of s){\n        map[letter]++;\n    }\n    \n    let valueGoal = s.length / 4\n        \n    let remainder = 0;\n    \n    let count = 4;\n    \n    for(let [key, val] of Object.entries(map)){\n        \n        if(val > valueGoal){\n            remainder = remainder + (val - valueGoal); \n        }\n        \n        if(val === valueGoal || val < valueGoal){\n            map[key] = -Infinity;\n            count--;\n        }\n    }\n    \n    if(remainder === 0){\n        return 0;\n    }\n    \n    let left = 0;\n    \n    let right = 0;\n    \n    while(right < s.length){\n\n        if(map[s[right]] !== -Infinity){\n            \n            map[s[right]]--;\n\n            if(map[s[right]] === valueGoal){\n                count--;\n            }\n            \n        }\n        \n        while(count === 0){\n\n            output = Math.min(output, right - left + 1);\n            \n            if(map[s[left]] !== -Infinity){\n                \n                map[s[left]]++;\n                \n                if(map[s[left]] > valueGoal){\n                    count++;\n                }\n                \n            }\n            left++\n        }\n\n        right++;\n    }\n\n    return output;\n};",
        "solution_java": "class Solution {\n    public int balancedString(String s) {\n        int n = s.length(), ans = n, excess = 0;\n        int[] cnt = new int[128];\n        cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4;\n        for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be removed.\n        if (excess == 0) return 0;\n        for (int i = 0, j = 0; i < n; i++){//i = window right end, j = window left end\n            if (--cnt[s.charAt(i)] == 0) excess--; //remove letter at index i\n            while (excess == 0){ //if no more excess, then \n                if (++cnt[s.charAt(j)] == 1) excess++; //we put letter at index j back\n                ans = Math.min(i - j + 1, ans);; //and update ans accordingly\n                j++;\n            }\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int balancedString(string s) {\n      int n=s.length();\n      unordered_map<char,int>umap;\n      for(auto x:s)\n      {\n         umap[x]++;   \n      }\n        umap['Q']=umap['Q']-n/4>0?umap['Q']-n/4:0;\n        umap['W']=umap['W']-n/4>0?umap['W']-n/4:0;\n        umap['E']=umap['E']-n/4>0?umap['E']-n/4:0;\n        umap['R']=umap['R']-n/4>0?umap['R']-n/4:0;\n        int count=umap['Q']+umap['W']+umap['E']+umap['R'];\n        if(count==0)\n            return 0;\n        int i=0,ans=INT_MAX;\n        unordered_map<char,int>newMap;\n        for(int j=0;j<n;j++)\n        {\n            newMap[s[j]]++;\n            if(newMap[s[j]]<=umap[s[j]])\n            {\n                count--;\n                while(count==0)\n                {\n                    newMap[s[i]]--;\n                    if(newMap[s[i]]<umap[s[i]])\n                    {\n                        count++;\n                        ans=min(ans,j-i+1);\n                    }\n                    i++;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Guess Number Higher or Lower",
        "algo_input": "We are playing the Guess Game. The game is as follows:\n\nI pick a number from 1 to n. You have to guess which number I picked.\n\nEvery time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.\n\nYou call a pre-defined API int guess(int num), which returns three possible results:\n\n\n\t-1: Your guess is higher than the number I picked (i.e. num &gt; pick).\n\t1: Your guess is lower than the number I picked (i.e. num &lt; pick).\n\t0: your guess is equal to the number I picked (i.e. num == pick).\n\n\nReturn the number that I picked.\n\n&nbsp;\nExample 1:\n\nInput: n = 10, pick = 6\nOutput: 6\n\n\nExample 2:\n\nInput: n = 1, pick = 1\nOutput: 1\n\n\nExample 3:\n\nInput: n = 2, pick = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\t1 &lt;= pick &lt;= n\n\n",
        "solution_py": "class Solution:\n    def guessNumber(self, n: int) -> int:\n        l=1\n        h=n\n        while l<=h:\n            mid=(l+h)//2\n            x =guess(mid)\n            if(x==0):\n                return mid\n            elif(x==1):\n                l = mid+1\n            else:\n                h = mid-1",
        "solution_js": "/** \n * Forward declaration of guess API.\n * @param {number} num   your guess\n * @return \t     -1 if num is higher than the picked number\n *\t\t\t      1 if num is lower than the picked number\n *               otherwise return 0\n * var guess = function(num) {}\n */\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar guessNumber = function(n) {\n    let lower=1;\n    let higher=n;\n    while(lower<=higher){\n        let mid=Math.floor((lower+higher)/2);\n        if(guess(mid)==0){\n            return mid;            \n        }\n        else if(guess(mid)==-1){\n            higher=mid-1;\n        }\n        else{\n            lower=mid+1;\n        }\n    }\n    return 0;\n    \n};",
        "solution_java": "/** \n * Forward declaration of guess API.\n * @param  num   your guess\n * @return \t     -1 if num is higher than the picked number\n *\t\t\t      1 if num is lower than the picked number\n *               otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n    public int guessNumber(int n) {\n        int left = 1;\n        int right = n;\n        \n        while(left < right){\n            int mid = ((right - left) / 2) + left;\n            if(guess(mid) == 0)\n                return mid;\n            else if(guess(mid) < 0)\n                right = mid - 1;\n            else\n                left = mid + 1;\n        }\n        \n        return left;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int guessNumber(int n) {\n        int s = 1, e = n;\n        int mid = s + (e - s)/2;\n        \n        while (s <= e){\n            if (guess(mid) == 0){   \n                return mid;\n            }\n            \n            else if (guess(mid) == -1){\n                e = mid - 1;\n            }\n            \n            else if (guess(mid) == 1){\n                s = mid +1;\n            }\n            \n            mid = s + (e - s)/2;\n        }\n        \n        return mid;\n    }\n};"
    },
    {
        "title": "Arithmetic Subarrays",
        "algo_input": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.\n\nFor example, these are arithmetic sequences:\n\n1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9\n\nThe following sequence is not arithmetic:\n\n1, 1, 2, 5, 7\n\nYou are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.\n\nReturn a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]\nOutput: [true,false,true]\nExplanation:\nIn the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.\n\nExample 2:\n\nInput: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput: [false,true,false,false,true,true]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\tm == l.length\n\tm == r.length\n\t2 &lt;= n &lt;= 500\n\t1 &lt;= m &lt;= 500\n\t0 &lt;= l[i] &lt; r[i] &lt; n\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n        out=[]\n        for i, j in zip(l, r):\n            out.append(self.canMakeArithmeticProgression(nums[i:j+1]))\n        return out\n        \n    def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n        minArr = min(arr)\n        maxArr = max(arr)\n\t\t\n\t\t# if difference between minArr and maxArr cannot be divided into equal differences, then return false\n        if (maxArr-minArr)%(len(arr)-1)!=0:\n            return False\n\t\t\t\n\t\t# consecutive difference in arithmetic progression\n        diff = int((maxArr-minArr)/(len(arr)-1))\n        if diff == 0:\n            if arr != [arr[0]]*len(arr):\n                return False\n            return True\n\t\t\n\t\t# array to check all numbers in A.P. are present in input array.\n\t\t# A.P.[minArr, minArr+d, minArr+2d, . . . . . . . maxArr]\n        check = [1]*len(arr)\n        for num in arr:\n            if (num-minArr)%diff != 0:\n                return False\n            check[(num-minArr)//diff]=0\n\t\t\n\t\t# if 1 is still in check array it means at least one number from A.P. is missing from input array.\n        if 1 in check:\n            return False\n        return True",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number[]} l\n * @param {number[]} r\n * @return {boolean[]}\n */\n var checkArithmeticSubarrays = function(nums, l, r) {\n    let result = [];\n    for(let i=0;i<l.length;i++) {\n        let subNums = [...nums].slice(l[i], r[i]+1);\n        subNums = subNums.sort((a,b) => a-b);\n        let diff = subNums[1]-subNums[0];\n        let s = true\n        for(let j=0;j<subNums.length-1;j++) {\n            if(!(subNums[j+1]-subNums[j] == diff))\n                s = false\n        }\n        result.push(s)\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n        List<Boolean> result = new ArrayList<>();\n        int L = nums.length, ll = l.length,ind=0;\n        for(int i=0;i<ll;i++){\n            int[] arr = new int[r[i]-l[i]+1];\n            ind=0;\n            for(int k=l[i];k<=r[i];k++){\n                arr[ind] =nums[k];\n                ind++;\n            }\n            Arrays.sort(arr);\n            result.add(isArithmetic(arr));\n        }\n        return result;\n    }\n    \n    public boolean isArithmetic(int[] nums) {\n        int L = nums.length;\n        boolean b = true;\n        if(L<=2) return true;\n        for(int i=1;i<L-1;i++){\n            if(nums[i]-nums[i-1]!=nums[i+1]-nums[i]) return false;\n        }\n        return b;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {\n        \n        vector<bool> ans(l.size(),false);\n        for(int i=0;i<l.size();i++)\n        {\n            //if the sub array size is equal to 2\n            if(r[i]-l[i]+1==2)\n                ans[i]=true;\n            else if(isArthemetic(nums,l[i],r[i]))\n                ans[i]=true;\n        }\n        return ans;\n    }\n    \n    //return true if the sub array can be rearranged in a arthemetic sequence\n    bool isArthemetic(vector<int>& nums,int start,int end)\n    {\n        //get the maximum and min elements \n        int mini=INT_MAX;\n        int maxi=INT_MIN;\n        for(int i=start;i<=end;i++)\n        {\n            mini=min(nums[i],mini);\n            maxi=max(nums[i],maxi);\n        }\n        \n        //when mini==maxi it means all the elements are same in the sub array\n        if(mini==maxi)\n            return true; \n        \n        //we cant have same common difference betweeen  two adjacent  elements\n        //when we arrange in arthemetic sequence\n        if((maxi-mini)%(end-start)!=0)\n            return false;\n        \n        \n        //the diff between every two integers when we rearrange sub array\n        int diff=(maxi-mini)/(end-start);\n        \n        //to check  if the duplicate elemnts are present\n        //ex- [2,4,6,6]\n        //6 is repeating two times \n        vector<bool> present(end-start+1,false);\n        for(int i=start;i<=end;i++)\n        {\n            \n            //we cant set a index of nums[i]\n            if((nums[i]-mini)%diff!=0)\n                return false;\n            \n            int ind=(nums[i]-mini)/diff;\n            \n            // same element is alreeady repeated ( 6 in the above  example)\n            if(present[ind])\n                return false;\n            //mark it presence\n            present[ind]=true;\n            \n        }\n        return true;\n        \n    }\n};"
    },
    {
        "title": "Check Array Formation Through Concatenation",
        "algo_input": "You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].\n\nReturn true if it is possible to form the array arr from pieces. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: arr = [15,88], pieces = [[88],[15]]\nOutput: true\nExplanation: Concatenate [15] then [88]\n\n\nExample 2:\n\nInput: arr = [49,18,16], pieces = [[16,18,49]]\nOutput: false\nExplanation: Even though the numbers match, we cannot reorder pieces[0].\n\n\nExample 3:\n\nInput: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput: true\nExplanation: Concatenate [91] then [4,64] then [78]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pieces.length &lt;= arr.length &lt;= 100\n\tsum(pieces[i].length) == arr.length\n\t1 &lt;= pieces[i].length &lt;= arr.length\n\t1 &lt;= arr[i], pieces[i][j] &lt;= 100\n\tThe integers in arr are distinct.\n\tThe integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).\n\n",
        "solution_py": "class Solution:\n    def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n        keys, ans = {}, []\n        for piece in pieces:\n            keys[piece[0]] = piece\n        for a in arr:\n            if a in keys:\n                ans.extend(keys[a])\n        return ''.join(map(str, arr)) == ''.join(map(str, ans))",
        "solution_js": "var canFormArray = function(arr, pieces) {\n\tlet total = \"\";\n    arr=arr.join(\"\");\n    for (let i = 0; i < pieces.length; i++) {\n      pieces[i] = pieces[i].join(\"\");\n      total += pieces[i];\n      if (arr.indexOf(pieces[i]) == -1) return false;\n    }\n    return total.length == arr.length;\n};",
        "solution_java": "class Solution {\n    public boolean canFormArray(int[] arr, int[][] pieces) {\n        HashMap<Integer,int[]> hm = new HashMap();\n        for(int[] list:pieces)\n            hm.put(list[0],list);\n        \n        int index = 0;\n        while(index<arr.length){\n            if(!hm.containsKey(arr[index]))\n                return false;\n            \n            int[] list = hm.get(arr[index]);\n            for(int val:list){\n                if(index>=arr.length || val!=arr[index])\n                    return false;\n                index++;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {\n        map<int,vector<int>> mp; \n        // map the 1st element in pieces[i] to pieces[i]\n        for(auto p:pieces) \n            mp[p[0]] = p;\n        vector<int> result;\n        for(auto a:arr) {\n            if(mp.find(a)!=mp.end()) \n                result.insert(result.end(),mp[a].begin(),mp[a].end());\n        }\n        return result ==arr;\n    }\n};"
    },
    {
        "title": "Power of Three",
        "algo_input": "Given an integer n, return true if it is a power of three. Otherwise, return false.\n\nAn integer n is a power of three, if there exists an integer x such that n == 3x.\n\n&nbsp;\nExample 1:\n\nInput: n = 27\nOutput: true\n\n\nExample 2:\n\nInput: n = 0\nOutput: false\n\n\nExample 3:\n\nInput: n = 9\nOutput: true\n\n\n&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?",
        "solution_py": "class Solution:\n    def isPowerOfThree(self, n: int) -> bool:\n        return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False",
        "solution_js": "var isPowerOfThree = function(n) {\n    if(n === 1){return true;}\n    if(n === 0){return false;}\n\n    n/=3;\n\n    if(n%3 != 0 && n != 1){\n        return false;\n    }else{\n        let x = isPowerOfThree(n);\n        return x;\n    }\n};",
        "solution_java": "class Solution {\n    public boolean isPowerOfThree(int n) {\n       if(n==1){\n            return true;\n        }\n        if(n<=0){\n            return false;\n        }\n        if(n%3 !=0 && n>1){\n            return false;\n        }\n        else{\n            return isPowerOfThree(n/3); // recurssion \n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool isPowerOfThree(int n) {\n\t\tif(n<=0){return false;}\n\t\tif(n>pow(2, 31)-1 || n<pow(2, 31)*(-1)){return false;}\n\t\treturn 1162261467%n==0;\n\t}\n};"
    },
    {
        "title": "Frog Jump",
        "algo_input": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.\n\nGiven a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.\n\nIf the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.\n\n&nbsp;\nExample 1:\n\nInput: stones = [0,1,3,5,6,8,12,17]\nOutput: true\nExplanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n\n\nExample 2:\n\nInput: stones = [0,1,2,3,4,8,9,11]\nOutput: false\nExplanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= stones.length &lt;= 2000\n\t0 &lt;= stones[i] &lt;= 231 - 1\n\tstones[0] == 0\n\tstones&nbsp;is sorted in a strictly increasing order.\n\n",
        "solution_py": "class Solution:\n    def possible(self, i, n, stones, pos, allowedJumps):\n        if i == n - 1:\n            return True\n        key = tuple([i] + allowedJumps)\n        if key in self.cache:\n            return self.cache[key]\n        for jump in allowedJumps:\n            if jump > 0 and stones[i] + jump in pos:\n                if self.possible(pos[stones[i] + jump], n, stones, pos, [jump - 1, jump, jump + 1]):\n                    self.cache[key] = True\n                    return True\n        self.cache[key] = False\n        return False\n\n    def canCross(self, stones: List[int]) -> bool:\n        n = len(stones)\n        pos = {}\n        for i, stone in enumerate(stones):\n            pos[stone] = i\n        self.cache = {}\n        return self.possible(0, n, stones, pos, [1])",
        "solution_js": "var canCross = function(stones) {\n    let hash = {};\n    function dfs(idx = 0, jumpUnits = 0) {\n        let key = `${idx}-${jumpUnits}`;\n        if (key in hash) return hash[key];\n\t\t\n        if (idx === stones.length - 1) return true;\n        if (idx >= stones.length) return false;\n\t\t\n        let minJump = jumpUnits - 1, maxJump = jumpUnits + 1;\n        for (let i = idx + 1; i < stones.length; i++) {\n            let jump = stones[i] - stones[idx];\n            if (jump >= minJump && jump <= maxJump) {\n                if (dfs(i, jump)) return hash[idx] = true;\n            } else if (jump > maxJump) break;\n        } return hash[key] = false;\n    }\n    return dfs();\n};",
        "solution_java": "class Solution {\n    static boolean flag = false;   // If flag is true no more operations in recursion, directly return statement\n    public boolean canCross(int[] stones) {\n        int i = 0; // starting stone\n        int k = 1; // starting jump\n        flag = false; \n        return canBeCrossed(stones, k, i);\n    }\n    \n    public boolean canBeCrossed(int[] stones, int k, int i){\n        if(!flag){ // If flag is false \n        if(stones[i] + k == stones[stones.length - 1]){ // If frog do 'k' jump from current stone lands on last stones, no more recusive calls and return true\n            flag = true;\n            return true;\n        }\n\t\t// If frog do 'k' jump from current stone crosses last stone or not able to reach next stone\n\t\t//return false\n        if((stones[i] + k > stones[stones.length - 1]) || (stones[i]+k<stones[i+1])) return false;\n        int temp = i+1; // identify which next stone frog can reach\n\t\t//Find untill which stone frog can jump \n\t\t//So jump from current stone not greater than next possible stone exit loop\n        while(stones[i]+k > stones[temp]) temp++;\n\t\t//If loop exited 2 condition possible\n\t\t//jump from current stone is reached next possible stone\n\t\t//or not\n\t\t\n\t\t//If next possible stone reached\n\t\t//then do all possible jumps from this stone \n\t\t//the current stone is 'temp'\n\t\t//possible jumps are 'k-1', k, 'k+1'\n        if(stones[i]+k == stones[temp]) return (canBeCrossed(stones, k+1, temp) || canBeCrossed(stones, k, temp) || canBeCrossed(stones,k-1,temp));\n\t\t\n\t\t//If next possible stone not reached means jump from the current stone can't reach any stone\n\t\t//hence return false\n        else return false;\n    }\n        else return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canCross(vector<int>& stones) {\n       unordered_map<int,bool>mp; //to see the position where stone is present\n       for(int i=0;i<stones.size();i++)\n       {\n           mp[stones[i]]=true;\n       }\n       int stone=1; //current stone\n       int jump=1; //jump made\n       int last_stone=stones[stones.size()-1]; //last stone on which frog will land to cross river\n       map<pair<int,int>,bool>dp;\n       return fun(mp,stone,jump,dp,last_stone);\n    }\n    bool fun( unordered_map<int,bool>&mp,int stone,int jump,map<pair<int,int>,bool>&dp,int &ls)\n    {\n        if(stone==ls) //reached last stone\n        {\n            return true;\n        }\n        if(mp.find(stone)==mp.end()) //stone is not present\n        {\n            return false;\n        }\n        if(dp.find({stone,jump})!=dp.end())\n        {\n            return dp[{stone,jump}];\n        }\n        bool jump1=false;\n        bool jump2=false;\n        bool jump3=false;\n        if((stone+jump-1)>stone) //can take jump of k-1 units\n        {\n            jump1=fun(mp,stone+jump-1,jump-1,dp,ls);\n        }\n        if((stone+jump)>stone) //can take jump of k units\n        {\n            jump2=fun(mp,stone+jump,jump,dp,ls);\n        }\n        if((stone+jump+1)>stone) //can take jump of k+1 units\n        {\n            jump3=fun(mp,stone+jump+1,jump+1,dp,ls);\n        }\n        dp[{stone,jump}]=jump1 or jump2 or jump3;\n        return dp[{stone,jump}];\n    }\n};"
    },
    {
        "title": "Critical Connections in a Network",
        "algo_input": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.\n\nA critical connection is a connection that, if removed, will make some servers unable to reach some other server.\n\nReturn all critical connections in the network in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput: [[1,3]]\nExplanation: [[3,1]] is also accepted.\n\n\nExample 2:\n\nInput: n = 2, connections = [[0,1]]\nOutput: [[0,1]]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 105\n\tn - 1 &lt;= connections.length &lt;= 105\n\t0 &lt;= ai, bi &lt;= n - 1\n\tai != bi\n\tThere are no repeated connections.\n\n",
        "solution_py": "class Solution:\n    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n        \n        dic = collections.defaultdict(list)\n        for c in connections:\n            u, v = c\n            dic[u].append(v)\n            dic[v].append(u)\n            \n        \n        timer = 0\n        \n        depth, lowest, parent, visited = [float(\"inf\")]*n, [float(\"inf\")]*n, [float(\"inf\")]*n, [False]*n\n        res = []\n        \n        def find(u):\n            \n            nonlocal timer\n            \n            visited[u] = True\n            depth[u], lowest[u] = timer, timer\n            timer += 1\n            \n            for v in dic[u]:   \n                \n                if not visited[v]:\n                    parent[v] = u\n                    find(v)\n                    if lowest[v]>depth[u]:\n                        res.append([u,v])\n                \n                if parent[u]!=v:\n                    lowest[u] = min(lowest[u], lowest[v])\n                \n        find(0)\n        return res\n        ",
        "solution_js": "var criticalConnections = function(n, connections) {\n    // Graph Formation\n    const graph = new Map();\n    connections.forEach(([a, b]) => {\n        const aconn = graph.get(a) || [];\n        const bconn = graph.get(b) || [];\n\n        aconn.push(b), bconn.push(a);\n        graph.set(a, aconn);\n        graph.set(b, bconn);\n    });\n\n    // Find Bridges\n    const bridges = [];\n    const visited = new Array(n).fill(false);\n    const tin = new Array(n).fill(-1);\n    const dis = new Array(n).fill(-1);\n\n    let time = 0;\n\n    const dfs = (node, parent = -1) => {\n        visited[node] = true;\n        ++time;\n        tin[node] = time;\n        dis[node] = time;\n\n        const connections = graph.get(node);\n        for(let conn of connections) {\n            if(conn == parent) {\n                continue;\n            }\n            if(visited[conn]) {\n                dis[node] = Math.min(dis[node], tin[conn]);\n            } else {\n                dfs(conn, node);\n                dis[node] = Math.min(dis[node], dis[conn]);\n                if(dis[conn] > tin[node]) {\n                    bridges.push([node, conn]);\n                }\n            }\n        };\n    }\n\n    dfs(0);\n\n    return bridges;\n};",
        "solution_java": "class Solution {\n    // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection\n    public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {\n        List<Integer>[] graph = new ArrayList[n];\n        for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n        \n        for(List<Integer> oneConnection :connections) {\n            graph[oneConnection.get(0)].add(oneConnection.get(1));\n            graph[oneConnection.get(1)].add(oneConnection.get(0));\n        }\n        int timer[] = new int[1];\n        List<List<Integer>> results = new ArrayList<>();\n        boolean[] visited = new boolean[n];\n        int []timeStampAtThatNode = new int[n]; \n        criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode);\n        return results;\n    }\n    \n    \n    public void criticalConnectionsUtil(List<Integer>[] graph, int parent, int node, int timer[], boolean[] visited, List<List<Integer>> results, int []timeStampAtThatNode) {\n        visited[node] = true;\n        timeStampAtThatNode[node] = timer[0]++;\n        int currentTimeStamp = timeStampAtThatNode[node];\n        \n        for(int oneNeighbour : graph[node]) {\n            if(oneNeighbour == parent) continue;\n            if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode);\n            timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]);\n            if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour));\n        }\n        \n        \n    }\n    \n}",
        "solution_c": "class Solution {\n    int timer = 1;\npublic:\nvoid dfs(vector<int>adj[] , int node , int parent , vector<int>&tin , vector<int>&low , vector<int>&vis , vector<vector<int>>&ans)\n{\n    vis[node] = 1;\n    tin[node] = low[node] = timer;\n    timer++;\n    for(auto it:adj[node])\n    {\n        if(it == parent) continue;\n        if(vis[it] == 0)\n        {\n            dfs(adj , it , node , tin , low , vis , ans);\n            low[node] = min(low[node] , low[it]);\n            if(tin[node] < low[it])\n            ans.push_back({node , it});\n        }\n        else\n        {\n            low[node] = min(low[node] , low[it]);\n        }\n    }\n}\n    vector<vector<int>> criticalConnections(int n, vector<vector<int>>& con) {\n        vector<int>adj[n];\n        for(int i =  0;i<con.size();i++)\n        {\n            adj[con[i][0]].push_back(con[i][1]);\n            adj[con[i][1]].push_back(con[i][0]);\n        }\n        vector<vector<int>>ans;\n        vector<int>vis(n , 0) , tin(n , 0) , low(n , 0);\n        dfs(adj ,  0 , -1 , tin , low , vis , ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Number of Events That Can Be Attended II",
        "algo_input": "You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.\n\nYou can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\n\nReturn the maximum sum of values that you can receive by attending events.\n\n&nbsp;\nExample 1:\n\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput: 7\nExplanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n\nExample 2:\n\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput: 10\nExplanation: Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n\nExample 3:\n\n\n\nInput: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput: 9\nExplanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= events.length\n\t1 &lt;= k * events.length &lt;= 106\n\t1 &lt;= startDayi &lt;= endDayi &lt;= 109\n\t1 &lt;= valuei &lt;= 106\n\n",
        "solution_py": "import bisect\nfrom functools import lru_cache\n\nclass Solution:\n    def maxValue(self, events: List[List[int]], k: int) -> int:\n        if k == 1: # optimization for TLE test case 57/67\n            return max([event[2] for event in events])\n        \n        events.sort()\n        event_starts = [event[0] for event in events] # enables binary search\n        \n        @lru_cache(None)\n        def dp(i, j):\n            if j == 0: # out of turns\n                return 0\n            if i >= len(events): # end of events array\n                return 0\n            max_score = events[i][2]\n            \n            # get minimum index where start day is greater than current end day\n            next_index_minimum = bisect.bisect_left(event_starts, events[i][1] + 1)\n            \n            # check each possibility from the minimum next index until end of the array\n            for k in range(next_index_minimum, len(events)):\n                max_score = max(max_score, events[i][2] + dp(k, j - 1))\n            \n            # check if we can get a better score if we skip this index altogether\n            max_score = max(max_score, dp(i + 1, j))\n            return max_score\n        return dp(0, k)",
        "solution_js": "/**\n * @param {number[][]} events\n * @param {number} k\n * @return {number}\n */\nvar maxValue = function(events, k) {\n    events = events.sort((a, b) => a[1] - b[1]);\n    const n = events.length;\n    var ans = 0;\n    var dp = Array.from(Array(k+1), () => new Array(n).fill(0));\n    \n    for(let i = 0; i < n; i++) {\n        dp[1][i] = Math.max((i ? dp[1][i-1] :0), events[i][2]);\n        ans = Math.max(dp[1][i], ans);\n    }\n    \n    function binarySearch(l, r, target) {\n        var pos = -1;\n        while(l <= r) {\n            const mid = Math.floor((l+r)/2);\n            if (events[mid][1] < target) {\n                pos = mid;\n                l = mid+1;\n            }\n            else r = mid-1;\n        }\n        return pos;\n    }\n    \n    for(let i = 0; i < n; i++) {\n        const j = binarySearch(0, i-1, events[i][0]);\n            for(let l = 2; l <= k; l++) {\n                dp[l][i] = Math.max(( j >= 0 ? dp[l-1][j] + events[i][2] : 0), (i ? dp[l][i-1] : 0));\n                ans = Math.max(dp[l][i], ans);\n            }\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxValue(int[][] events, int k) {\n        Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0]));\n        return maxValue(events, 0, k, 0, new int[k+1][events.length]);\n    }\n\n    private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEndDay, int[][] dp) {\n        // Return 0 if no events are left or maximum choice is reached\n        if (index >= events.length || remainingEvents == 0)\n            return 0;\n\n        // An Event cannot be picked if the previous event has not completed before current event\n        if (lastEventEndDay >= events[index][0])\n            return maxValue(events, index+1, remainingEvents, lastEventEndDay, dp);\n\n        // Return the value if the solution is already available\n        if (dp[remainingEvents][index] != 0)\n            return dp[remainingEvents][index];\n\n        // There are 2 choices that we can make,\n            // SKIP this meeting or PICK this meeting\n        return dp[remainingEvents][index] = Math.max(\n            maxValue(events, index+1, remainingEvents, lastEventEndDay, dp), // skip\n            maxValue(events, index+1, remainingEvents-1, events[index][1], dp) + events[index][2] // pick\n        );\n    }\n}",
        "solution_c": "class Solution {\npublic:\n     \n    int ans;    \n    unordered_map<int,unordered_map<int,unordered_map<int,int>>> dp;\n    \n    int Solve(vector<vector<int>>& events, int start, int n, int k, int endtime){\n        if(k == 0 || start == n){\n            return 0;\n        }\n        \n        if(dp.find(start) != dp.end() && dp[start].find(k) != dp[start].end() && dp[start][k].find(endtime) != dp[start][k].end()){\n        \n            return dp[start][k][endtime];\n        }\n        int t1 = 0;\n        if(events[start][0] > endtime){\n            t1 = events[start][2] + Solve(events, start+1, n, k-1, events[start][1]);\n        }\n        \n        int t2 = Solve(events,start+1,n,k,endtime);\n        \n        dp[start][k][endtime] = max(t1,t2);\n       // cout<< dp[start][k][endtime]<<endl;\n     \n        return dp[start][k][endtime];\n        \n    }\n    int maxValue(vector<vector<int>>& events, int k) {\n        \n        dp.clear();\n     \n        // sort according to start time\n        sort(events.begin(), events.end(),[](vector<int> &a,vector<int> &b){\n            return a[0] < b[0];\n        });\n        \n    return Solve(events,0,events.size(),k,0);\n    \n    }\n};"
    },
    {
        "title": "Generate Random Point in a Circle",
        "algo_input": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.\n\nImplement the Solution class:\n\n\n\tSolution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).\n\trandPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]\nOutput\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\nExplanation\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;&nbsp;radius &lt;= 108\n\t-107 &lt;= x_center, y_center &lt;= 107\n\tAt most 3 * 104 calls will be made to randPoint.\n\n",
        "solution_py": "class Solution:\n\n    def __init__(self, radius: float, x_center: float, y_center: float):\n        self.rad = radius\n        self.xc = x_center\n        self.yc = y_center\n\n    def randPoint(self) -> List[float]:\n        while True:\n            xg=self.xc+random.uniform(-1, 1)*self.rad*2\n            yg=self.yc+random.uniform(-1, 1)*self.rad*2\n            if (xg-self.xc)**2 + (yg-self.yc)**2 <= self.rad**2:\n                return [xg, yg]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(radius, x_center, y_center)\n# param_1 = obj.randPoint()",
        "solution_js": "/**\n * @param {number} radius\n * @param {number} x_center\n * @param {number} y_center\n */\nvar Solution = function(radius, x_center, y_center) {\n  this.radius = radius;\n  this.x_center = x_center;\n  this.y_center = y_center;\n};\n\n/**\n * @return {number[]}\n */\nSolution.prototype.randPoint = function() {\n  const randomX = randRange(this.x_center + this.radius, this.x_center - this.radius);\n  const randomY = randRange(this.y_center + this.radius, this.y_center - this.radius);\n  \n  const distanceInSquares = Math.pow(randomX - this.x_center, 2) + Math.pow(randomY - this.y_center, 2);\n  const isOutOfTheCircle = distanceInSquares > Math.pow(this.radius, 2);\n  \n  if (isOutOfTheCircle)) {\n    return this.randPoint();\n  }\n\n  return [randomX, randomY];\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(radius, x_center, y_center)\n * var param_1 = obj.randPoint()\n */\n\nfunction randRange(maximum, minimum) {\n  return Math.random() * (maximum - minimum) + minimum;\n}",
        "solution_java": "class Solution {\n    double radius;\n    double x_center;\n    double y_center;\n    Random r=new Random();\n    public Solution(double radius, double x_center, double y_center) {\n        this.radius=radius;\n        this.x_center=x_center;\n        this.y_center=y_center;\n    }\n    \n    public double[] randPoint() {\n        double angle=r.nextDouble(Math.PI*2);\n\t\t//For probability is inversely proportional to radius, we use sqrt of random number.\n        double rad=Math.sqrt(r.nextDouble())*radius;\n        double[] ret=new double[2];\n        ret[0]=rad*Math.cos(angle)+x_center;\n        ret[1]=rad*Math.sin(angle)+y_center;\n        return ret;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double r,x,y;\n    Solution(double radius, double x_center, double y_center) {\n        r = radius;\n        x = x_center;\n        y = y_center;\n    }\n    \n    vector<double> randPoint() {\n        double x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r);\n        double y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r);\n        \n        while(solve(x_r,y_r,x,y)>=r*r)\n        {\n            x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r);\n            y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r);\n        }\n        \n        return {x_r,y_r};\n    }\n    \n    double solve(double x_r,double y_r,double x,double y)\n    {\n        return (x-x_r)*(x-x_r) + (y-y_r)*(y-y_r);\n    }\n};"
    },
    {
        "title": "Swap For Longest Repeated Character Substring",
        "algo_input": "You are given a string text. You can swap two of the characters in the text.\n\nReturn the length of the longest substring with repeated characters.\n\n&nbsp;\nExample 1:\n\nInput: text = \"ababa\"\nOutput: 3\nExplanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.\n\n\nExample 2:\n\nInput: text = \"aaabaaa\"\nOutput: 6\nExplanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.\n\n\nExample 3:\n\nInput: text = \"aaaaa\"\nOutput: 5\nExplanation: No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 2 * 104\n\ttext consist of lowercase English characters only.\n\n",
        "solution_py": "class Solution:\n    def maxRepOpt1(self, text: str) -> int:\n        char_groups = []\n        \n        for char, group in groupby(text):\n            group_len = len(list(group))\n            char_groups.append((char, group_len))\n        \n        char_count = Counter(text)\n        \n        longest_substr_len = 1 # Each char itself is substring of len 1\n        \n        # Scenario-1: Get the longest substr length by just adding one more char to each group\n        for char, group_len in char_groups:\n            # NOTE: If the total count of the char across full string is < group_len+1,\n            # make sure to take the total count only\n            #\n            # It means we don't have any extra char occurrence which we can add to the current group\n            \n            group_len_w_one_addition = min(group_len+1, char_count[char])\n            longest_substr_len = max(longest_substr_len, group_len_w_one_addition)\n        \n        \n        # Scenario-2: \n        # If there are two groups of same char, separated by a group of different char with length=1:\n        #   1) We can either swap that one char in the middle with the same char as those two groups \n        #       Ex: 'aaa b aaa c a'\n        #           - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index\n        #           - So after swapping, it will become 'aaa a aaa c b' \n        #           - hence longest substr len of same char 'a' = 7\n        #\n        #   2) We can merge the two groups\n        #       Ex: 'aaa b aaa' \n        #           -> here there are two groups of char 'a' with len = 3 each.\n        #           -> they are separated by a group of char 'b' with len = 1\n        #           -> hence, we can merge both groups of char 'a' - so that longest substr len = 6\n        #           -> basically, swap the 'b' with 'a' at very last index\n        #           -> the final string will look like 'aaaaaa b'\n        #\n        #   We will take max length we can get from above two options.\n        #\n        # Since we need to check the group prior to curr_idx \"i\" and also next to curr_idx \"i\";\n        # we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive\n        \n        for i in range(1, len(char_groups)-1):\n            prev_group_char, prev_group_len = char_groups[i-1]\n            curr_group_char, curr_group_len = char_groups[i]\n            next_group_char, next_group_len = char_groups[i+1]\n            \n            if curr_group_len != 1 or prev_group_char != next_group_char:\n                continue\n                \n            len_after_swapping = min(prev_group_len + next_group_len + 1, char_count[next_group_char])\n            longest_substr_len = max(longest_substr_len, len_after_swapping)\n        \n        return longest_substr_len",
        "solution_js": "/**\n * @param {string} text\n * @return {number}\n */\n\nconst getLast = (ar)=> ar[ar.length-1];\n var maxRepOpt1 = function(text) {\n\n    let freq = {};\n\n    // compute frequency map\n    for(let i=0;i<text.length;i++){\n        let e=text[i];\n        !freq[e] && (freq[e]=0);\n        freq[e]++;\n    }\n\n    let segments = [];\n    segments.push({\n        v:text[0],\n        c:1\n    });\n\n    let max = 1;\n    for(let i=1;i<text.length;i++){\n        let e = text[i];\n        let last = getLast(segments);\n\n        if(last.v == e){\n            last.c++;\n            max = Math.max(max,last.c);\n        }else{\n            segments.push({v:e,c:1});\n        }\n    }\n\n    for(let i=0,len=segments.length;i<len;i++){\n        let {v,c} = segments[i];\n        if(freq[v] > c){ // x x a , a x x , x a x\n            max = Math.max(max,c+1);\n        }\n        if(i+2<len && v==segments[i+2].v){ // x a x a x a x a x x a x a\n            let sum = c+segments[i+2].c;\n            if(segments[i+1].c == 1){\n                if(freq[v] > sum){\n                    max = Math.max(max,1+sum);\n                }else{\n                    max = Math.max(max,sum);\n                }\n            }\n        }\n    }\n\n    return max;\n\n};",
        "solution_java": "class Solution {\n\t\tpublic int maxRepOpt1(String s) {\n\t\t   int[] count = new int[26];\n\t\t   int[] left = new int[s.length()];\n\t\t   int[] right = new int[s.length()];\n\t\t\tint max =0;\n\t\t\t// Left Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=0;i<s.length();i++){\n\t\t\t\tcount[s.charAt(i) -'a']++;\n\t\t\t\tif(i> 0){\n\t\t\t\t\tif(s.charAt(i) == s.charAt(i-1)){\n\t\t\t\t\t\tleft[i] = left[i-1]+1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleft[i] = 1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tleft[i] =1;\n\t\t\t\t}\n\t\t\t\tmax = Math.max(max,left[i]);\n\t\t\t}\n\t\t\t// Right Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=s.length()-1;i>=0;i--){\n\t\t\t\tif(i < s.length()-1){\n\t\t\t\t\tif(s.charAt(i+1) == s.charAt(i)){\n\t\t\t\t\t\tright[i] = right[i+1] +1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tright[i] =1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tright[i] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Count The Length Of SubString Having Maximum Length When A Character Is Swapped\n\t\t\tfor(int i=1 ; i<s.length()-1 ; i++){\n\t\t\t\tif(s.charAt(i-1) == s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)){\n\t\t\t\t\tif(count[s.charAt(i-1) -'a'] == left[i-1] + right[i+1]){\n\t\t\t\t\t\tmax = Math.max(max , left[i-1] + right[i+1]);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tmax = Math.max(max,left[i-1] + right[i+1]+1);\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif(count[s.charAt(i) -'a'] == left[i]){\n\t\t\t\t\t\tmax = Math.max(max,left[i]);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tmax = Math.max(max,left[i]+1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t if(count[s.charAt(s.length()-1)-'a']!=left[s.length()-1])\n\t\t\t\t\t{\n\t\t\t\t\t\tmax = Math.max(max, left[s.length()-1]+1);\n\t\t\t\t\t}\n\t\t   return max; \n\t\t}\n\t}\n\t",
        "solution_c": "class Solution {\npublic:\n    int maxRepOpt1(string text) {\n        vector<pair<int, int>> intervals[26];\n        // a: [st, ed], .....\n        for(int i = 0; i < text.size();){\n            int st = i, ed = i;\n            while(i < text.size() && text[i] == text[st]){\n                ed = i;\n                i++;\n            }\n            intervals[text[st] - 'a'].push_back({st, ed});\n        }\n        \n        int ans = 0;\n        for(int i = 0; i < 26; i++){\n            for(int j = 0; j < intervals[i].size(); j++){\n                // 单个的最大值\n                int len1 = intervals[i][j].second - intervals[i][j].first + 1;\n                if(intervals[i].size() > 1)\n                    len1++;\n                ans = max(ans, len1);\n                \n                // 合并\n                // [1, 2] [4, 6]\n                if(j+1 < intervals[i].size() && intervals[i][j].second + 2 == intervals[i][j+1].first){\n                    int len2 = intervals[i][j].second - intervals[i][j].first + 1 + intervals[i][j+1].second - intervals[i][j+1].first + 1;\n                    if(intervals[i].size() > 2){ // 一定有一个愿意牺牲\n                        len2++;\n                    }\n                    ans = max(ans, len2);\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n\n/**\nabababababac\n\n*/"
    },
    {
        "title": "Construct Target Array With Multiple Sums",
        "algo_input": "You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :\n\n\n\tlet x be the sum of all elements currently in your array.\n\tchoose index i, such that 0 &lt;= i &lt; n and set the value of arr at index i to x.\n\tYou may repeat this procedure as many times as needed.\n\n\nReturn true if it is possible to construct the target array from arr, otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: target = [9,3,5]\nOutput: true\nExplanation: Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done\n\n\nExample 2:\n\nInput: target = [1,1,1,2]\nOutput: false\nExplanation: Impossible to create target array from [1,1,1,1].\n\n\nExample 3:\n\nInput: target = [8,5]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\tn == target.length\n\t1 &lt;= n &lt;= 5 * 104\n\t1 &lt;= target[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def isPossible(self, target: List[int]) -> bool:\n        if len(target) == 1:\n            return target == [1]\n        res = sum(target)\n        heap = [-elem for elem in target]\n        heapify(heap)\n        while heap[0]<-1:\n            maximum = -heappop(heap)\n            res -= maximum\n\n            if res == 1:\n                return True\n            x = maximum % res\n            if x == 0 or (x != 1 and x == maximum):\n                return False\n\n            res += x\n            heappush(heap,-x)\n        return True",
        "solution_js": "var isPossible = function(target) {\n    let max=0\n    let index=-1\n\n    for(let i=target.length-1;i>=0;i--){\n        if(target[i]>max){\n            max=target[i]\n            index=i\n        }\n    }\n    if(max===1)return true // if max itself is 1 return true\n\n    let total=0\n    for(let i=0;i<target.length;i++){\n        if(i!==index){\n            total+=target[i]\n        }\n    }\n    // If total=1,it means only one element was remaining apart from max and its value is 1 return true\n    // eg target=[10,1] we started with [1,1] so next steps would be [2,1]->[3,1]->...[10,1] we can make sure it leads to target\n    if(total===1)return true;\n     // max should be greater than remaining nums sum OR if total is 0 it would lead to infinite loop( num%0 === NaN) so return false\n    if(max<=total||total===0)return false;\n    max=max%total;\n    if(max<1)return false; // it should not be less than 1\n    target[index]=max;\n\n    return isPossible(target)\n};",
        "solution_java": "class Solution {\n    public boolean isPossible(int[] target) {\n        if(target.length==1) return target[0]==1;\n\n        PriorityQueue<Integer> que = new PriorityQueue<Integer>(Collections.reverseOrder());\n        int totsum = 0;\n\n        for(int i=0;i<target.length;i++){\n            que.add(target[i]);\n            totsum += target[i];\n        }\n\n        while(que.peek()!=1){\n            int max = que.remove();\n            int rem = totsum-max;\n            int maxprev = max % rem;\n            totsum = rem+maxprev;\n\n            if(rem==1) return true;\n\n            if(maxprev == 0 || maxprev == max){\n                return false;\n            } else {\n                que.add(maxprev);\n            }\n        }\n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPossible(vector<int>& target) {\n        \n        //Priority queue for storing all the nums in taget in decreasing order.\n        priority_queue<int> pq;\n        long long sum = 0; //for storing total sum\n\n        for(auto num : target){ //adding the nums in pq and sum\n            pq.push(num);\n            sum+=num;\n        }\n        \n        //iterating untill all elements in pq become 1 (in turn pq.top() will also become 1);\n        while(pq.top() != 1){\n\n            sum -= pq.top(); //removing the greatest element as it was last upadted when converting [1,1,1...] array to target. So we are left with sum of other elements.\n            \n            //when there are elements greeter than 1 then sum of other elements can not be 0 or sum can not be greater than top element because sum + x(any number>0) is pq.top().\n            if(sum == 0 || sum >= pq.top()) return false;\n            \n            //if we delete all copies of sum from pq.top() we get an old element.\n            int old = pq.top() % sum;\n            \n            //all old elements were > 0 so it can not be 0 unless sum is 1 (This is only possible if array has only 2 elements)\n            if(sum != 1 && old == 0) return false;\n            \n            pq.pop();     //Deleting greatest element\n\n            pq.push(old); //Adding old element to restore array.\n            sum += old;   //Updating sum\n        }\n        \n        //if all elements are 1 then return true\n        return true;\n    }\n};"
    },
    {
        "title": "Perfect Squares",
        "algo_input": "Given an integer n, return the least number of perfect square numbers that sum to n.\n\nA perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.\n\n&nbsp;\nExample 1:\n\nInput: n = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4.\n\n\nExample 2:\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "class Solution:\n\n    def __init__(self):\n        self.perSq = []\n\n    def numSquares(self, n):\n        # finding perfect squares up to n\n        i = 1\n        while i*i <= n:\n            self.perSq.append(i*i)\n            i += 1\n\n        return self.lengths(n)\n\n    # algorithm to find sum from perfect squares\n    def outcomes(self, n, current):\n        rem = n\n        nums = []\n        while sum(nums) != n:\n            if current < len(self.perSq)*-1:\n                current = self.perSq[0]\n\n            val = self.perSq[current]\n\n            if rem < val:\n                current -= 1\n                continue\n            else:\n                nums.append(val)\n                rem -= val\n                if (rem > 0) and (rem % val == 0):\n                    nums.append(val)\n                    rem -= val\n\n        return len(nums)\n\n    # algorithm to find sum with least possible numbers\n    def lengths(self, n):\n        data = []\n        for i in range(-1, -1*(len(self.perSq)+1), -1):\n            data.append(self.outcomes(n, i))\n\n        return min(data)",
        "solution_js": "var numSquares = function(n) {\n    let dp = new Array(n+1).fill(Infinity);\n    \n    dp[0] = 0;\n    \n    for(let i=1; i <= n; i++){\n        for(let k=1; k*k <= i; k++){\n            dp[i] = Math.min(dp[i],dp[i - (k*k)] + 1);\n        }\n    }\n    \n    return dp[n];\n};",
        "solution_java": "class Solution {\n    public int numSquares(int n) {\n        \n        ArrayList<Integer> perfect_squares = new ArrayList<>();\n        int i=1;\n        while(i*i <= n){\n            perfect_squares.add(i*i);\n            i++;\n        }\n        Integer[][] dp = new Integer[n+1][perfect_squares.size()+1];\n        int answer = helper(n , perfect_squares , perfect_squares.size()-1,dp);\n        return answer;\n    }\n    \n    public int helper(int n , ArrayList<Integer> coins ,int i,Integer[][] dp){\n        \n        if(n == 0){\n            return 0;\n        }\n        if(i<0){\n            return 999999;      //  I'm not taking INT_MAX here, since int variables will overflow with (1 + INT_MAX)\n\t\t\t                             // just take any number greater than constraint ( 10^4) \n        }\n        if(dp[n][i] != null){\n            return dp[n][i];\n        }\n        int nottake = 0 + helper(n , coins, i-1,dp);\n        int take = 9999999;\n        if(coins.get(i) <= n){\n            take = 1 + helper(n-coins.get(i),coins,i,dp );          \n        }\n        dp[n][i] = Math.min(nottake,take);\n        return dp[n][i];\n        \n        \n        \n    }\n    \n    \n}",
        "solution_c": "class Solution {\npublic:\n    int numSquares(int n) {\n        \n        vector<int> perfectSq;\n        \n        for(int i = 1; i*i <= n; ++i){\n            perfectSq.push_back(i*i);\n        }\n        \n        int m = perfectSq.size();\n        vector<vector<int>> dp( m+1, vector<int>(n+1, 0));\n        \n        dp[0][0] = 0;\n        for( int i = 1; i <= n; ++i ) dp[0][i] = INT_MAX;\n        \n        for(int i = 1; i <= m; ++i){\n            for(int j = 1; j <= n; ++j){\n                \n                if( j < perfectSq[i-1]){\n                    dp[i][j] = dp[i-1][j];\n                }\n                else{\n                    dp[i][j] = min( dp[i-1][j], dp[i][ j - perfectSq[i-1] ] + 1);\n                }\n                \n            }\n        }\n   \n        return dp[m][n];\n    }\n};"
    },
    {
        "title": "Count Number of Maximum Bitwise-OR Subsets",
        "algo_input": "Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.\n\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.\n\nThe bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,1]\nOutput: 2\nExplanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]\n\n\nExample 2:\n\nInput: nums = [2,2,2]\nOutput: 7\nExplanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.\n\n\nExample 3:\n\nInput: nums = [3,2,1,5]\nOutput: 6\nExplanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 16\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def countMaxOrSubsets(self, nums: List[int]) -> int:\n        \n        def dfs(i,val):\n            if maxBit == val : return 1<<(len(nums)-i)\n            if i == len(nums): return 0\n            return dfs(i+1,val|nums[i]) + dfs(i+1,val)\n        maxBit = 0\n        for i in nums: maxBit |= i\n        return dfs(0,0)",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function(nums) {\n\n    let n = nums.length;\n    let len = Math.pow(2, n);\n    let ans = 0;\n    let hash = {};\n\n    for (let i = 0; i < len; i++) {\n        let tmp = 0;\n        for (let j = 0; j < n; j++) {\n            if(i & (1 << j)) {\n                tmp |= nums[j];\n            }\n        }\n        if (hash[tmp]) {\n            hash[tmp] += 1;\n        } else {\n            hash[tmp] = 1;\n        }\n        ans = Math.max(ans, tmp);\n    }\n\n    return hash[ans];\n};",
        "solution_java": "class Solution {\n    public int countMaxOrSubsets(int[] nums) {\n        \n        subsets(nums, 0, 0);\n        return count;\n    }\n    \n    int count = 0;\n    int maxOR = 0;\n    \n    private void subsets(int[] arr, int vidx, int OR){\n        \n        if(vidx == arr.length){\n            \n            if(OR == maxOR){\n                count ++;\n            }else if(OR > maxOR){\n                count = 1;\n                maxOR = OR;\n            }\n            \n            return;\n        }\n        \n        // include\n        subsets(arr, vidx+1, OR | arr[vidx]);\n        \n        // exclude\n        subsets(arr, vidx+1, OR);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countMaxOrSubsets(vector<int>& nums) {\n        \n        int i,j,max_possible_or=0,n=nums.size(),ans=0;\n        \n        //maximum possible or=or of all number in array\n        for(i=0;i<n;i++)\n        {\n            max_possible_or=nums[i]|max_possible_or;\n        }\n        \n        //checking all subset \n        \n        \n        for(i=1;i<(1<<n);i++)\n        {\n            int p=0;\n            for(j=0;j<n;j++)\n            {\n                if(i&(1<<j))\n                {\n                    p=p|nums[j];\n                }\n            }\n            //if xor of given subset is equal to maximum possible or\n\t\t\t\n            if(p==max_possible_or)\n            {\n                ans++;\n            }\n        }\n        \n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Maximum Product of Three Numbers",
        "algo_input": "Given an integer array nums, find three numbers whose product is maximum and return the maximum product.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,3]\nOutput: 6\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 24\nExample 3:\nInput: nums = [-1,-2,-3]\nOutput: -6\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;=&nbsp;104\n\t-1000 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def maximumProduct(self, nums: List[int]) -> int:\n        # TC = O(NlogN) because sorting the array \n        # SC = O(1); no extra space needed; sorting was done in place.\n        \n        # sorting the array in descending order\n        nums.sort(reverse = True)\n        \n        # maximum product can only occur for:\n        # 1. positive no * positive no * positive no\n        # 2. negative no * negative no * positive no\n        \n        # one negative and two positives and all negatives wont give max product\n        # case where all numbers in the array are negative \n        # eg : [-4,-3,-2,-1] is covered in all positives \n        \n        return max(nums[0]*nums[1]*nums[2],nums[-1]*nums[-2]*nums[0])",
        "solution_js": "var maximumProduct = function(nums) {\n    nums.sort((a, b) => a-b)\n    \n    var lastNumber = nums.length - 1\n    var midNumber = nums.length - 2\n    var firstNumber = nums.length - 3\n    var total = nums[lastNumber] * nums[midNumber] * nums[firstNumber]\n    return total\n    \n};",
        "solution_java": "class Solution {\n    public int maximumProduct(int[] nums) {\n        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;\n        for (int n: nums) {\n            if (n <= min1) {\n                min2 = min1;\n                min1 = n;\n            } else if (n <= min2) { // n lies between min1 and min2\n                min2 = n;\n            }\n            if (n >= max1) { // n is greater than max1, max2 and max3\n                max3 = max2;\n                max2 = max1;\n                max1 = n;\n            } else if (n >= max2) { // n lies betweeen max1 and max2\n                max3 = max2;\n                max2 = n;\n            } else if (n >= max3) { // n lies betwen max2 and max3\n                max3 = n;\n            }\n        }\n        return Math.max(min1 * min2 * max1, max1 * max2 * max3);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumProduct(vector<int>& nums) {\n\n        int min1 = INT_MAX , min2 = INT_MAX; // Both have the maximum value that is +infinte\n        int max1 = INT_MIN, max2 = INT_MIN , max3 = INT_MIN; //All these have the minimum value that is -infinte\n\n        //now finding all these value above declared.\n        for(int i = 0 ; i < nums.size() ; i++)\n        {\n            if(nums[i] > max1 )\n            {\n                max3 = max2 ;\n                max2 = max1;\n                max1 = nums[i];\n\n            }\n            else if(nums[i] > max2)\n            {\n                max3 = max2 ;\n                max2 = nums[i] ;\n\n            }\n            else if(nums[i] > max3)\n            {\n                max3 = nums[i] ;\n\n            }\n\n            if(nums[i] < min1)\n            {\n                min2 = min1 ;\n                min1 = nums[i] ;\n\n            }\n            else if(nums[i] < min2)\n            {\n                min2 = nums[i];\n\n            }\n        }\n        return max(min1*min2*max1 , max1*max2*max3);\n    }\n};"
    },
    {
        "title": "Maximum Frequency Stack",
        "algo_input": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\n\nImplement the FreqStack class:\n\n\n\tFreqStack() constructs an empty frequency stack.\n\tvoid push(int val) pushes an integer val onto the top of the stack.\n\tint pop() removes and returns the most frequent element in the stack.\n\t\n\t\tIf there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.\n\t\n\t\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]\nOutput\n[null, null, null, null, null, null, null, 5, 7, 5, 4]\n\nExplanation\nFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop();   // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop();   // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= val &lt;= 109\n\tAt most 2 * 104 calls will be made to push and pop.\n\tIt is guaranteed that there will be at least one element in the stack before calling pop.\n\n",
        "solution_py": "class FreqStack:\n\n    def __init__(self):\n        self.cnt = {}\n        self.maxcount = 0\n        self.stack = {}\n\n    def push(self, val: int) -> None:\n        count = self.cnt.get(val,0)+1\n        self.cnt[val] = count\n        if count>self.maxcount:\n            self.maxcount = count\n            self.stack[count] = []\n        self.stack[count].append(val)\n\n    def pop(self) -> int:\n        res = self.stack[self.maxcount].pop()\n        self.cnt[res]-=1\n        if not self.stack[self.maxcount]:\n            self.maxcount-=1\n        return res\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()",
        "solution_js": "var FreqStack = function() {\n    //hashMap to keep track of the values being repeated\n    this.frequencyMap = {};\n\n    //List map to keep track of the sequence of the value being entered\n    this.listMap = {};\n\n    //Max Frequency variable to keep track of the max frequency\n    this.maxValueFrequency = 0;\n};\n\n/**\n * @param {number} val\n * @return {void}\n */\nFreqStack.prototype.push = function(val) {\n    //if the hashMap doesn't have value being pushed then make a entry to it with 1 else increament by 1\n    this.frequencyMap[val] = this.frequencyMap[val] ? this.frequencyMap[val]+1 : 1;\n\n    //get the frequency of the value being pushed\n    const currentValueFrequency = this.frequencyMap[val];\n\n    //check if the current frequency is max or itself\n    this.maxValueFrequency = Math.max(this.maxValueFrequency, currentValueFrequency);\n\n    //if current value frequency is not in the listmap then make a new entry else push it\n    if(!this.listMap[currentValueFrequency]) this.listMap[currentValueFrequency] =[val];\n    else this.listMap[currentValueFrequency].push(val);\n\n};\n\n/**\n * @return {number}\n */\nFreqStack.prototype.pop = function() {\n    //make a temporary list of the max value frequency\n    const tempList = this.listMap[this.maxValueFrequency];\n\n    //get the last element from the temporary list\n    const top = tempList[tempList.length - 1];\n\n    //remove the item from the list\n    tempList.pop();\n\n    //update the list\n    this.listMap[this.maxValueFrequency] = tempList;\n\n    //if the popped item exist in the frequecy map then decrease it by 1\n    if(this.frequencyMap[top]) this.frequencyMap[top]--;\n\n    //if the max value frequency in the listmap is blank then reduce the maxValueFrequency;\n    if(this.listMap[this.maxValueFrequency].length === 0) this.maxValueFrequency--;\n\n    //return the max value frequency with proper order if it is same\n    return top;\n\n};\n\n//Time O(Log n) // for both Push and Pop\n//Space O(n) for storing all the values in the hashMap and listMap",
        "solution_java": "class Node{\n    int data, freq, time;\n    Node(int data, int freq, int time){\n        this.data=data;\n        this.freq=freq;\n        this.time=time;\n    }\n}\n\nclass CompareNode implements Comparator<Node>{\n    @Override\n    public int compare(Node a, Node b){\n        if(a.freq-b.freq==0){\n            return b.time-a.time;\n        }\n        return b.freq-a.freq;\n    }\n}\n\nclass FreqStack {\n    PriorityQueue<Node> pq;\n    Map<Integer,Node> map;\n    int c=0;\n    public FreqStack(){\n        pq=new PriorityQueue<>(new CompareNode());\n        map=new HashMap<>();\n    }\n\n    public void push(int val){\n        c++;\n        int freq=1;\n        if(map.containsKey(val)){\n            freq+=map.get(val).freq;\n        }\n        map.put(val, new Node(val, freq, c));\n        pq.add(new Node(val,freq,c++));\n    }\n\n    public int pop() {\n        Node r=pq.remove();\n        Node a=map.get(r.data);\n        a.freq--;\n        return r.data;\n    }\n}",
        "solution_c": "class FreqStack {\npublic:\n    unordered_map<int,int> ump;\n    unordered_map<int,stack<int>> ump_st;\n    \n    int cap=1;\n    \n    FreqStack() {\n        ump.clear();\n        ump_st.clear();\n    }\n    \n    void push(int val) {\n\t\n\t\t//increasing the count\n        if(ump.find(val)!=ump.end())\n        {\n            ump[val]++;\n        }\n        else\n        {\n            ump[val]=1;\n        }\n        \n\t\t//update the highest level\n        if(cap<ump[val])\n        {\n            cap = ump[val];\n        }\n\t\t\n        //push the elements in the stack where it belongs as per height\n        ump_st[ump[val]].push(val);\n    }\n    \n    int pop() {\n        int val = ump_st[cap].top();\n        ump_st[cap].pop();\n        \n        if(ump_st[cap].size()==0)\n        {\n            cap--;\n        }\n        \n        ump[val]--;\n        \n        if(ump[val]==0)\n        {\n            ump.erase(val);\n        }\n        \n        return val;\n    }\n};"
    },
    {
        "title": "Minimum Bit Flips to Convert Number",
        "algo_input": "A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.\n\n\n\tFor example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.\n\n\nGiven two integers start and goal, return the minimum number of bit flips to convert start to goal.\n\n&nbsp;\nExample 1:\n\nInput: start = 10, goal = 7\nOutput: 3\nExplanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010 -&gt; 1011.\n- Flip the third bit from the right: 1011 -&gt; 1111.\n- Flip the fourth bit from the right: 1111 -&gt; 0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.\n\nExample 2:\n\nInput: start = 3, goal = 4\nOutput: 3\nExplanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011 -&gt; 010.\n- Flip the second bit from the right: 010 -&gt; 000.\n- Flip the third bit from the right: 000 -&gt; 100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= start, goal &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minBitFlips(self, s: int, g: int) -> int:\n        count = 0 \n        while s or g:\n            if s%2 != g%2: count+=1\n            s, g = s//2, g//2\n        return count",
        "solution_js": "var minBitFlips = function(start, goal) {\n    return (start^goal).toString(2).split(\"0\").join(\"\").length;\n};",
        "solution_java": "class Solution {\n\tpublic static int minBitFlips(int a1, int a2) {\n\t\tint n = (a1 ^ a2);\n\t\tint res = 0;\n\t\twhile (n != 0) {\n\t\t\tres++;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn res;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    int minBitFlips(int start, int goal) {\n        return __builtin_popcount(start^goal);\n    }\n};"
    },
    {
        "title": "Parallel Courses III",
        "algo_input": "You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.\n\nYou must find the minimum number of months needed to complete all the courses following these rules:\n\n\n\tYou may start taking a course at any time if the prerequisites are met.\n\tAny number of courses can be taken at the same time.\n\n\nReturn the minimum number of months needed to complete all the courses.\n\nNote: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).\n\n&nbsp;\nExample 1:\n\n\nInput: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\nOutput: 8\nExplanation: The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.\n\n\nExample 2:\n\n\nInput: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\nOutput: 12\nExplanation: The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 5 * 104\n\t0 &lt;= relations.length &lt;= min(n * (n - 1) / 2, 5 * 104)\n\trelations[j].length == 2\n\t1 &lt;= prevCoursej, nextCoursej &lt;= n\n\tprevCoursej != nextCoursej\n\tAll the pairs [prevCoursej, nextCoursej] are unique.\n\ttime.length == n\n\t1 &lt;= time[i] &lt;= 104\n\tThe given graph is a directed acyclic graph.\n\n",
        "solution_py": "class Solution:\n    def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n        in_degree=defaultdict(int)\n        graph=defaultdict(list)\n        latest=[0]*(n+1)\n        for u,v in relations:\n            graph[u].append(v)\n            in_degree[v]+=1\n        q=[]\n        for i in range(1,n+1):\n            if in_degree[i]==0:\n                latest[i]=time[i-1]\n                q.append(i)\n        while q:\n            node=q.pop()\n            t0=latest[node]\n            for nei in graph[node]:\n                t=time[nei-1]\n                latest[nei]=max(latest[nei],t0+t)\n                in_degree[nei]-=1\n                if in_degree[nei]==0:\n                    q.append(nei)\n        return max(latest)",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} relations\n * @param {number[]} time\n * @return {number}\n */\nvar minimumTime = function(n, relations, time) {\n    /*\n    Approach: We can create reverse edges for relation.\n&nbsp; &nbsp; Then longest path(by weightage of time for each node) from the node will be the minimum time to finish that course(node)\n&nbsp; &nbsp; Now we can use simple DFS to find the longest path for each node.\n&nbsp; &nbsp; The node containing the longest path will be course to finish the last.We can also use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again.&nbsp;\n    */\n    let edges={};\n    for(let i=0;i<relations.length;i++){\n        if(edges[relations[i][1]]===undefined){\n            edges[relations[i][1]] = [];\n        }\n        edges[relations[i][1]].push(relations[i][0]);\n    }\n\n    let max=0,timeRequired,memo={};\n    for(let i=1;i<=n;i++){\n        timeRequired = longestPath(i);\n        max = Math.max(max,timeRequired);\n    }\n    return max;\n     function longestPath(node){\n         if(memo[node]!==undefined){\n             return memo[node];\n         }\n        let len,max=0;\n         if(edges[node]!==undefined){\n             for(let i=0;i<edges[node].length;i++){\n                 len = longestPath(edges[node][i]);\n                 max = Math.max(max,len);\n             }\n         }\n         memo[node] = time[node-1]+max;//use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again\n         return memo[node];\n    }\n\n};",
        "solution_java": "class Solution {\n    public int minimumTime(int n, int[][] relations, int[] time) {\n        List<Integer> adj[] = new ArrayList[n];\n        int indegree[] = new int[n];\n        int completionTime[] = new int[n];\n        for(int i=0; i<n; i++) adj[i] = new ArrayList<>();\n        for(int relation[]: relations){\n            int u = relation[0]-1, v = relation[1]-1;\n            adj[u].add(v);\n            indegree[v]++;\n        }\n        Queue<Integer> q = new LinkedList<>();\n        for(int i=0; i<n; i++){\n            if(indegree[i] == 0){ // if no prerequisite add it to queue\n                completionTime[i] = time[i];\n                q.add(i);\n            }\n        }\n\n        while(!q.isEmpty()){\n            int u = q.poll();\n            for(int v: adj[u]){\n                completionTime[v] = Math.max(completionTime[v], completionTime[u] + time[v]);\n                if(--indegree[v] == 0){ // when all prerequisite are complete add the next course\n                    q.add(v);\n                }\n            }\n        }\n        int res=0;\n        for(int x: completionTime) res = Math.max(res, x);\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumTime(int n, vector<vector<int>>& relations, vector<int>& time) {\n        vector<vector<int>> adjList(n);\n        vector<int> inDegree(n),cTime(n,0);\n\n        for(auto &r:relations) { // Create adjacency list and in degree count vectors.\n            adjList[r[0]-1].push_back(r[1]-1);\n            inDegree[r[1]-1]++;\n        }\n        queue<pair<int,int>> q;\n\n        for(int i=0;i<n;i++) // Get all nodes with in-degree=0 and store add them to the queue.\n            if(!inDegree[i])\n                q.push({i,0});\n\n        while(!q.empty()) {\n            auto [node,t]=q.front(); // Process node `node`.\n            q.pop();\n\n            // Completion time of the current node the time when the processing started `t`\n            // (Max time at which prerequisutes completed) + the time taken to process it `time[node]`.\n            int completionTime=t+time[node];\n            cTime[node]=completionTime; // Store the final completion time of the node `node`.\n\n            for(int &n:adjList[node]) {\n                // Update the intermediate completion time of the child node `n`.\n                // This means that node `n` would start processing at least at `cTime[n]`.\n                cTime[n]=max(cTime[n],completionTime);\n\n                if(!--inDegree[n]) // Add the node with in-degree=0 to the queue.\n                    q.push({n,cTime[n]});\n            }\n        }\n        // Return the maximum time it took for a node/course to complete as our result.\n        return *max_element(cTime.begin(),cTime.end());\n    }\n};"
    },
    {
        "title": "Count Triplets That Can Form Two Arrays of Equal XOR",
        "algo_input": "Given an array of integers arr.\n\nWe want to select three indices i, j and k where (0 &lt;= i &lt; j &lt;= k &lt; arr.length).\n\nLet's define a and b as follows:\n\n\n\ta = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]\n\tb = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]\n\n\nNote that ^ denotes the bitwise-xor operation.\n\nReturn the number of triplets (i, j and k) Where a == b.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,3,1,6,7]\nOutput: 4\nExplanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)\n\n\nExample 2:\n\nInput: arr = [1,1,1,1,1]\nOutput: 10\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 300\n\t1 &lt;= arr[i] &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def countTriplets(self, arr: List[int]) -> int:\n        s = [0]\n        n = len(arr)\n        if n <= 1:\n            return 0 \n        for i in range(n):\n            s.append(s[-1]^arr[i])\n        # a = s[i] ^ s[j], b = s[j] ^ s[k+1]  \n        count = defaultdict(int)\n        # a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0 \n        # <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1])\n        # <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1]\n      \n        res = 0 \n        # len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k\n        for i in range(n-1):\n            for k in range(i+1, n):\n                if s[i] == s[k+1]:\n                    res += (k-i)\n        return res ",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar countTriplets = function(arr) {\n    let count = 0\n    for(let i=0;i<arr.length;i++){\n        let xor = arr[i]\n        for(let j=i+1;j<arr.length;j++){\n            xor ^= arr[j]\n            if(xor == 0){\n                count += (j-i)\n            }\n        }\n    }\n    return count\n};",
        "solution_java": "class Solution {\n    public int countTriplets(int[] arr) {\n        int count=0;\n\n        for(int i=0;i<arr.length;i++){\n            int val=0;\n            val=val^arr[i];\n            for(int k=i+1;k<arr.length;k++){\n                val=val ^ arr[k];\n                if(val==0) count+=k-i;\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class TrieNode {\npublic:\n    int numOfIndex;\n    int sumOfIndex;\n    TrieNode* child[2];\n    \n    TrieNode() : numOfIndex(0), sumOfIndex(0) {\n        child[0] = NULL;\n        child[1] = NULL;\n    }\n};\nclass Solution {\npublic:\n    void addNumber(TrieNode* root, int num, int idx){\n        for( int i = 31; i >= 0; i--){\n       \n            int bit = 1 & (num >> i) ;\n        \n            if ( root->child[bit] == NULL){\n                root->child[bit] = new TrieNode();\n            }\n            root = root->child[bit];\n        }\n        root->sumOfIndex += idx;\n        root->numOfIndex++;\n    }\n    int calculateIndexPair(TrieNode* root, int num, int idx){\n        for( int i = 31; i >= 0; i--){\n            int bit = 1 & (num >> i);\n        \n            if (root->child[bit] == NULL){\n                return 0;\n            }\n            root = root->child[bit];\n        }\n        return (((root->numOfIndex) * idx) - (root->sumOfIndex));\n    }\n    int countTriplets(vector<int>& arr) {\n        long long ans=0;\n        int XOR = 0;\n        TrieNode* root = new TrieNode();\n    \n        for ( int i = 0 ; i < arr.size(); i++){\n            addNumber(root, XOR, i);\n            XOR ^= arr[i];\n            ans = (ans + calculateIndexPair(root, XOR, i)) % 1000000007;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Baseball Game",
        "algo_input": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.\n\nAt the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:\n\n\n\tAn integer x - Record a new score of x.\n\t\"+\" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.\n\t\"D\" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.\n\t\"C\" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.\n\n\nReturn the sum of all the scores on the record. The test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput: 30\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\n\n\nExample 2:\n\nInput: ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput: 27\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n\n\nExample 3:\n\nInput: ops = [\"1\",\"C\"]\nOutput: 0\nExplanation:\n\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= ops.length &lt;= 1000\n\tops[i] is \"C\", \"D\", \"+\", or a string representing an integer in the range [-3 * 104, 3 * 104].\n\tFor operation \"+\", there will always be at least two previous scores on the record.\n\tFor operations \"C\" and \"D\", there will always be at least one previous score on the record.\n\n",
        "solution_py": "class Solution:\n    def calPoints(self, ops: List[str]) -> int:\n        temp = []\n        for i in ops:\n            if i!=\"C\" and i!=\"D\" and i!=\"+\":\n                temp.append(int(i))\n            elif i==\"C\":\n                temp.remove(temp[len(temp)-1])\n            elif i==\"D\":\n                temp.append(2*temp[len(temp)-1])\n            elif i==\"+\":\n                temp.append(temp[len(temp)-1]+temp[len(temp)-2])\n        \n        \n        return sum(temp)",
        "solution_js": "//Plus sign in the below algo confirms that the data type we are getting is integer. So, instead of adding it as a string, the data type will be  added as integer\nvar calPoints = function(ops) {\n    let stack = [];\n    for(let i = 0; i < ops.length; i++){\n        if(ops[i] === \"C\")\n            stack.pop();\n        else if(ops[i] === \"D\")\n            stack.push((+stack[stack.length - 1]) * 2);\n        //we have to take stack.length to get the element of stack. We cannot take i for getting the element of stack as i refers to ops and it wont give the index of previous element in stack\n        else if(ops[i] ===\"+\")\n            stack.push((+stack[stack.length - 1]) + (+stack[stack.length - 2]));\n        else\n        stack.push(+ops[i]);\n    }\n    let sum = 0;\n    for(let i = 0; i < stack.length; i++){\n        sum = sum + stack[i];\n    }\n    return sum;\n};",
        "solution_java": "class Solution {\n    public int calPoints(String[] ops) {\n        List<Integer> list = new ArrayList<Integer>();\n        \n        for(int i = 0; i < ops.length; i++){\n            switch(ops[i]){\n                case \"C\":\n                    list.remove(list.size() - 1);\n                    break;\n                case \"D\":\n                    list.add(list.get(list.size() - 1) * 2);\n                    break;\n                case \"+\":\n                    list.add(list.get(list.size() - 1) + list.get(list.size() - 2));\n                    break;\n                default:\n                    list.add(Integer.valueOf(ops[i]));\n                    break;\n            }\n        }\n        \n        int finalScore = 0;\n        for(Integer score: list)\n            finalScore += score;\n        \n        return finalScore;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int calPoints(vector<string>& ops) {\n        stack<int>st;\n        int n = ops.size();\n        for(int i=0;i<n;i++){\n                    if(ops[i] == \"C\"){\n                        st.pop();\n                    }\n                    else if (ops[i] ==\"D\"){\n                        st.push(st.top() * 2);\n                    }\n                    else if(ops[i] ==\"+\"){\n                        int temp = st.top();\n                        st.pop();\n                        int temp2 = st.top();\n                        st.push(temp);\n                        st.push(temp+temp2);\n                   }\n                  else{\n                      st.push(stoi(ops[i]));\n                  }\n        }\n        int res = 0;\n        while(!st.empty()){\n            res += st.top();\n            st.pop();\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Largest Number",
        "algo_input": "Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.\n\nSince the result may be very large, so you need to return a string instead of an integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,2]\nOutput: \"210\"\n\n\nExample 2:\n\nInput: nums = [3,30,34,5,9]\nOutput: \"9534330\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "from functools import cmp_to_key\nclass Solution:\n    def largestNumber(self, nums: List[int]) -> str:\n        nums = list(map(str, nums))\n        nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0))))\n        res = \"\".join(nums)\n        return res if int(res) else \"0\"",
        "solution_js": "var largestNumber = function(nums) {\n    var arr=[]\n    nums.forEach((item)=>{\n        arr.push(item.toString());\n    })\n    arr.sort((a,b)=>(b+a).localeCompare(a+b));\n    var ret=\"\"\n    if(arr[0]==\"0\") return \"0\";\n    arr.forEach((item)=>{\n        ret+=item;\n    })\n    return ret;\n};",
        "solution_java": "class Solution {\n    public String largestNumber(int[] nums) {\n        String[] arr=new String[nums.length];\n        for(int i=0;i<nums.length;i++){\n            arr[i]=Integer.toString(nums[i]);\n        }\n        Arrays.sort(arr,(a,b)->(b+a).compareTo(a+b));\n        if(arr[0].equals(\"0\")) return \"0\";\n        StringBuilder builder=new StringBuilder();\n        for(String item:arr){\n            builder.append(item);\n        }\n        return builder.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestNumber(vector<int>& nums) {\n        sort(nums.begin(),nums.end(),[&](int a,int b){\n            string order1 = to_string(a)+to_string(b);\n            string order2 = to_string(b)+to_string(a);\n            return order1>order2;\n        });\n        \n        string ans = \"\";\n        for(int i = 0;i<nums.size();i++){\n            if(nums[0]==0) return \"0\";\n            ans += to_string(nums[i]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Word Break II",
        "algo_input": "Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.\n\nNote that the same word in the dictionary may be reused multiple times in the segmentation.\n\n&nbsp;\nExample 1:\n\nInput: s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\nOutput: [\"cats and dog\",\"cat sand dog\"]\n\n\nExample 2:\n\nInput: s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\nOutput: [\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\nExplanation: Note that you are allowed to reuse a dictionary word.\n\n\nExample 3:\n\nInput: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 20\n\t1 &lt;= wordDict.length &lt;= 1000\n\t1 &lt;= wordDict[i].length &lt;= 10\n\ts and wordDict[i] consist of only lowercase English letters.\n\tAll the strings of wordDict are unique.\n\n",
        "solution_py": "class Solution(object):\n    def wordBreak(self, s, wordDict):\n        \"\"\"\n        :type s: str\n        :type wordDict: List[str]\n        :rtype: List[str]\n        \"\"\"\n\n        dic = defaultdict(list)\n        for w in wordDict:\n            dic[w[0]].append(w)\n        result = []\n        def recursion(idx , ans):\n            if idx >= len(s):\n                result.append(\" \".join(ans))\n                return\n\n            for w in dic[s[idx]]:\n                if s[idx : idx+len(w)] == w:\n                    ans.append(w)\n                    recursion(idx+len(w), ans)\n                    ans.pop()\n\n            return\n        recursion(0, [])\n        return result",
        "solution_js": "var wordBreak = function(s, wordDict) {\n    const n = s.length;\n    const result = [];\n\n    const findValidSentences = (currentString = '', remainingString = s, currentIndex = 0) => {\n        if(currentIndex === remainingString.length) {\n            if(wordDict.includes(remainingString)) {\n                result.push(`${currentString} ${remainingString}`.trim())\n            }\n            return result;\n        }\n\n        const newWord = remainingString.slice(0, currentIndex);\n        if(wordDict.includes(newWord)) {\n            const newCurrentString = `${currentString} ${newWord}`;\n            const newRemainingString = remainingString.slice(currentIndex);\n            findValidSentences(newCurrentString, newRemainingString, 0);\n        }\n\n        return findValidSentences(currentString, remainingString, currentIndex + 1);\n    }\n\n    return findValidSentences();\n};",
        "solution_java": "class Solution {\n\tList<String> res = new ArrayList<>();\n\tString s;\n\tint index = 0;\n\tSet<String> set = new HashSet<>();\n    public List<String> wordBreak(String s, List<String> wordDict) {\n        this.s = s;\n\t\tfor (String word: wordDict) set.add(word);\n\t\tbacktrack(\"\");\n\t\treturn res;\n    }\n\tpublic void backtrack(String sentence) {\n\t    if (index == s.length()) {\n\t        res.add(sentence.trim());\n\t        return;\n        }\n        int indexCopy = index;\n        for (int i = index + 1; i <= s.length(); i++) {\n\t        String str = s.substring(index, i);\n\t        if (set.contains(str)) {\n\t            index = i;\n\t            backtrack(sentence + \" \" + str);\n\t            index = indexCopy;\n            }\n        }\n        return;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void helper(string s, unordered_set<string>& dict,int start, int index,string current,vector<string>& ans){\n        if(start==s.size()){\n            ans.push_back(current);\n            return;\n        }\n        if(index==s.size()) return;\n\n        string sub=s.substr(start,index-start+1);\n\n        if(dict.count(sub)>0){\n            string recursion;\n            if(current.size()==0) recursion=sub;\n            else recursion=current+\" \"+sub; \n            helper(s,dict,index+1,index+1,recursion,ans);\n        }\n        helper(s,dict,start,index+1,current,ans);\n        return;\n    }\n    vector<string> wordBreak(string s, vector<string>& wordDict) {\n        unordered_set<string> dict;\n        for(int i=0;i<wordDict.size();i++){\n                dict.insert(wordDict[i]);\n        }\n        vector<string> ans;\n        helper(s,dict,0,0,\"\",ans);\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Number of Ways to Split Array",
        "algo_input": "You are given a 0-indexed integer array nums of length n.\n\nnums contains a valid split at index i if the following are true:\n\n\n\tThe sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.\n\tThere is at least one element to the right of i. That is, 0 &lt;= i &lt; n - 1.\n\n\nReturn the number of valid splits in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,4,-8,7]\nOutput: 2\nExplanation: \nThere are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 &gt;= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 &gt;= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 &lt; 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.\n\n\nExample 2:\n\nInput: nums = [2,3,1,0]\nOutput: 2\nExplanation: \nThere are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 &gt;= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 &gt;= 0, i = 2 is a valid split.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def waysToSplitArray(self, nums: List[int]) -> int:\n        prefix_sum = [nums[0]]\n        n = len(nums)\n        for i in range(1, n):\n            prefix_sum.append(nums[i] + prefix_sum[-1]) \n        \n        count = 0\n        for i in range(n-1):\n            if prefix_sum[i] >= prefix_sum[n-1] - prefix_sum[i]:\n                count += 1\n        return count",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar waysToSplitArray = function(nums) {\n    let result = 0;\n    let letsum = 0;\n    let rightsum = nums.reduce((a,b)=> a+b);\n    let end = nums.length-1;\n    for (let i = 0;i<end;i++) {\n        letsum+=nums[i];\n        rightsum-=nums[i];\n        if (letsum>=rightsum) {\n            result++;\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int waysToSplitArray(int[] nums) {\n        long sum = 0;\n        for(int i : nums){\n            sum+=i;\n        }\n        int sol = 0;\n        long localSum = 0;\n        for(int i=0; i<nums.length-1;i++){\n            localSum += nums[i];\n            if(localSum >= sum-localSum){\n                sol++;\n            }\n        }\n        return sol;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int waysToSplitArray(vector<int>& nums) {\n\n        long long sumFromBack(0), sumFromFront(0);\n        for (auto& i : nums) sumFromBack += i;\n\n        int n(size(nums)), res(0);\n        for (auto i=0; i<n-1; i++) {\n\n            sumFromFront += nums[i]; // sum of the first i + 1 elements\n            sumFromBack -= nums[i]; // sum of the last n - i - 1 elements.\n            if (sumFromFront >= sumFromBack) res++;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Check if All the Integers in a Range Are Covered",
        "algo_input": "You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.\n\nReturn true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.\n\nAn integer x is covered by an interval ranges[i] = [starti, endi] if starti &lt;= x &lt;= endi.\n\n&nbsp;\nExample 1:\n\nInput: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput: true\nExplanation: Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.\n\n\nExample 2:\n\nInput: ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput: false\nExplanation: 21 is not covered by any range.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= ranges.length &lt;= 50\n\t1 &lt;= starti &lt;= endi &lt;= 50\n\t1 &lt;= left &lt;= right &lt;= 50\n\n",
        "solution_py": "class Solution:\n    def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n        \n        \n        t=[0]*(60)\n        \n        for i in ranges:\n            \n            t[i[0]]+=1\n            t[i[1]+1]-=1\n            \n        for i in range(1,len(t)):\n            t[i] += t[i-1]\n            \n        return min(t[left:right+1])>=1\n        \n        \n        \n        \n        ",
        "solution_js": "var isCovered = function(ranges, left, right) {\n  var map=new Map()\n  for(let i=left;i<=right;i++){\n      map.set(i,0)\n  }\n  for(let range of ranges){\n      for(let i=range[0];i<=range[1];i++){\n          map.set(i,1)\n      }\n  }\n    // console.log(map)\n  for(let key of map.keys()){\n      if(map.get(key)===0) return false\n  }\n    return true\n};",
        "solution_java": "class Solution {\n    public boolean isCovered(int[][] ranges, int left, int right) {\n        boolean flag = false;\n        for (int i=left; i<=right; i++) {\n            for (int[] arr: ranges) {\n                if (i >= arr[0] && i <= arr[1]) {\n                    flag = true;\n                    break;\n                }\n            }\n            if (!flag) return false;\n            flag = false;\n        }\n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isCovered(vector<vector<int>>& ranges, int left, int right) {\n        int n = ranges.size();\n        \n        sort(ranges.begin(), ranges.end());\n        \n        if(left < ranges[0][0])                 //BASE CASE\n            return false;\n        \n        bool ans = false;\n        \n        for(int i = 0; i < n; i++){\n            if(left>=ranges[i][0] && left<=ranges[i][1]){\n                left = ranges[i][1]+1;\n            }\n            if(left > right){\n                ans = true;\n                break;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Reverse Integer",
        "algo_input": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.\n\nAssume the environment does not allow you to store 64-bit integers (signed or unsigned).\n\n&nbsp;\nExample 1:\n\nInput: x = 123\nOutput: 321\n\n\nExample 2:\n\nInput: x = -123\nOutput: -321\n\n\nExample 3:\n\nInput: x = 120\nOutput: 21\n\n\n&nbsp;\nConstraints:\n\n\n\t-231 &lt;= x &lt;= 231 - 1\n\n",
        "solution_py": "import bisect\nclass Solution:\n    def reverse(self, x: int) -> int:\n\n        flag = 0\n        if x<0:\n            x = abs(x)\n            flag = 1\n            \n        l = [i for i in str(x)]\n        l.reverse()\n        \n        ret = ''.join(l)\n        ret = int(ret)\n        \n        if flag == 1:\n            ret = ret*-1\n            \n        if ((ret >= (-(2**31))) and (ret<=((2**31)-1))):\n            return ret\n        else:\n            return 0",
        "solution_js": "var reverse = function(x) {\n    let val = Math.abs(x)\n    let res = 0\n    while(val !=0){\n         res = (res*10) + val %10\n         val = Math.floor(val/10)\n    }\n    if(x < 0)res = 0 - res\n    return (res > ((2**31)-1) || res < (-2)**31) ? 0 : res \n};",
        "solution_java": "class Solution {\n    public int reverse(int x) {\n        long reverse = 0;\n        while (x != 0) {\n            int digit = x % 10;\n            reverse = reverse * 10 + digit;\n            x = x / 10;\n        }\n        if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0;\n        return (int) reverse;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int reverse(int x) {\n        long res = 0;\n        while (abs(x) > 0) {\n            res = (res + x % 10) * 10;\n            x /= 10;\n        }\n        x < 0 ? res = res / 10 * -1 : res = res / 10;\n        if (res < INT32_MIN || res > INT32_MAX) {\n            res = 0;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Minimum Cost to Cut a Stick",
        "algo_input": "Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:\n\nGiven an integer array cuts where cuts[i] denotes a position you should perform a cut at.\n\nYou should perform the cuts in order, you can change the order of the cuts as you wish.\n\nThe cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\n\nReturn the minimum total cost of the cuts.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, cuts = [1,3,4,5]\nOutput: 16\nExplanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n\nThe first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n\nExample 2:\n\nInput: n = 9, cuts = [5,6,1,4,2]\nOutput: 22\nExplanation: If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost &lt;= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 106\n\t1 &lt;= cuts.length &lt;= min(n - 1, 100)\n\t1 &lt;= cuts[i] &lt;= n - 1\n\tAll the integers in cuts array are distinct.\n\n",
        "solution_py": "class Solution:\n    def minCost(self, n: int, cuts: List[int]) -> int:\n        cuts = [0] + sorted(cuts) + [n]\n        k = len(cuts)\n        dp = [[float('inf')] * k for _ in range(k)]\n        for l in range(1, k + 1):\n            for beg in range(k - l):\n                end = beg + l\n                if l == 1:\n                    dp[beg][end] = 0\n                    continue\n                for i in range(beg + 1, end):\n                    currcost = cuts[end] - cuts[beg]\n                    currcost += dp[beg][i] + dp[i][end]\n                    dp[beg][end] = min(dp[beg][end], currcost)\n        return dp[0][k - 1]",
        "solution_js": "var minCost = function(n, cuts) {\n    cuts = cuts.sort((a, b) => a - b);\n    let map = new Map();\n    // Use cutIdx to track the idx of the cut position in the cuts array\n    function dfs(start, end, cutIdx) {\n        let key = `${start}-${end}`;\n        if (map.has(key)) return map.get(key);\n        let min = Infinity\n        for (let i = cutIdx; i < cuts.length; i++) {\n            let cut = cuts[i];\n            if (cut <= start) continue;\n            if (cut < end) {\n                let len = end - start;\n                let left = dfs(start, cut, 0);\n                let right = dfs(cut, end, i + 1);\n                min = Math.min(min, len + left + right);\n            } else break;\n        }\n        if (min === Infinity) {\n            map.set(key, 0);\n            return 0;\n        }\n        else {\n            map.set(key, min);\n            return min;\n        }\n    }\n    return dfs(0, n, 0);\n};",
        "solution_java": "class Solution {\n    public int minCost(int n, int[] cuts) {\n        \n        int len = cuts.length;\n        \n        Arrays.sort(cuts);\n        \n        int[] arr = new int[len+2];\n        for(int i = 1 ; i <= len ; i++)\n            arr[i] = cuts[i-1];\n        \n        arr[0] = 0;\n        arr[len+1] = n;\n        int[][] dp = new int[len+1][len+1];\n        for(int i = 0 ; i <= len ; i++)\n            for(int j = 0 ; j <= len ; j++)\n                dp[i][j] = -1;\n        return cut(arr , 1 , len , dp);\n    }\n    \n    int cut(int[] cuts , int i , int j , int[][] dp){\n        if(i > j)\n            return 0;\n        \n        if(dp[i][j] != -1)\n            return dp[i][j];\n        \n        int mini = Integer.MAX_VALUE;\n        for(int k = i ; k <= j ; k++){\n            int cost = cuts[j+1]-cuts[i-1] + cut(cuts , i , k-1 , dp) + cut(cuts , k+1 , j , dp);\n            mini = Math.min(cost , mini);\n        }\n        \n        return dp[i][j] = mini;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long cutMin(int i, int j, vector<int>&c, vector<vector<int>>&dp)\n    {\n        if(i>j) return 0;\n        if(dp[i][j]!=-1) return dp[i][j];\n        long mini = INT_MAX;\n        for(int ind=i;ind<=j;ind++)\n        {\n            long cost = c[j+1]-c[i-1]+cutMin(i,ind-1,c,dp)+cutMin(ind+1,j,c,dp);\n            mini = min(mini,cost);\n        }\n        return dp[i][j] = mini;\n    }\n    int minCost(int n, vector<int>& cuts) {\n        int c = cuts.size();\n        cuts.push_back(0);\n        cuts.push_back(n);\n        sort(cuts.begin(),cuts.end());\n        vector<vector<int>>dp(c+1,vector<int>(c+1,-1));\n        return cutMin(1,c,cuts,dp);\n    }\n};"
    },
    {
        "title": "Diameter of Binary Tree",
        "algo_input": "Given the root of a binary tree, return the length of the diameter of the tree.\n\nThe diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.\n\nThe length of a path between two nodes is represented by the number of edges between them.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n\n\nExample 2:\n\nInput: root = [1,2]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-100 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    \"\"\"\n    Top Down recursion approach: it is sub optimal\n    \"\"\"\n    def __init__(self):\n        self.max_diameter = 0\n    def diameter(self, root):\n        if root is None:\n            return 0\n        return self.max_depth(root.left) + self.max_depth(root.right)\n\n    def max_depth(self, root):\n        if root is None:\n            return 0\n        return 1 + max(self.max_depth(root.left), self.max_depth(root.right))\n\n    def func(self, root):\n        if root is not None:\n            diameter = self.diameter(root)\n            if self.max_diameter < diameter:\n                self.max_diameter = diameter\n            self.diameterOfBinaryTree(root.left)\n            self.diameterOfBinaryTree(root.right)\n\n    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n        self.func(root)\n        return self.max_diameter\n\n    \"\"\"\n    Better Approach: I can try to approach this problem using bottom up recursion\n    \"\"\"\n    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n        self.diameter = 0\n        def fun(root):\n            if root is None:\n                return 0\n            left = fun(root.left)\n            right = fun(root.right)\n            if left + right > self.diameter:\n                self.diameter = left + right\n            return max(left, right) + 1\n        fun(root)\n        return self.diameter",
        "solution_js": "function fastDiameter(node) {\n    if(node == null) {\n        let pair = new Array(2).fill(0)\n        pair[0] = 0\n        pair[1] = 0\n        return pair\n    }\n    \n    let leftPair = fastDiameter(node.left)\n    let rightPair = fastDiameter(node.right)\n    \n    let leftDiameter = leftPair[0]\n    let rightDiameter = rightPair[0]\n    \n    let height = leftPair[1] + rightPair[1] + 1\n    \n    let maxDiameter = Math.max(leftDiameter,rightDiameter,height)\n    \n    let maxHeight = Math.max(leftPair[1],rightPair[1]) + 1\n    \n    return [maxDiameter,maxHeight]\n}\n\n// diameter --> number of edges between two end nodes\nvar diameterOfBinaryTree = function(root) {\n    \n    let pair = fastDiameter(root)\n    \n    return pair[0]-1\n};",
        "solution_java": "class Solution {\n    // Declare Global Variable ans to 0\n    int ans = 0;\n    // Depth First Search Function\n    public int dfs(TreeNode root) {\n        if(root == null) return 0;\n        // recursive call for left height\n        int lh = dfs(root.left);\n        // recursive call for right height\n        int rh = dfs(root.right);\n\n        // update ans\n        ans = Math.max(ans, lh + rh);\n\n        // return max value\n        return Math.max(lh, rh) + 1;\n    }\n\n    // Diameter of Binary Tree Function\n    public int diameterOfBinaryTree(TreeNode root) {\n        // Call dfs Function\n        dfs(root);\n        return ans;\n    }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(n)\n*/",
        "solution_c": "class Solution {\npublic:\n    int diameterOfBinaryTree(TreeNode* root) {\n        int diameter = 0;\n        height(root, diameter);\n        return diameter;\n    }\nprivate:\n    int height(TreeNode* node, int& diameter) {\n        if (!node) {\n            return 0;\n        }\n        int lh = height(node->left, diameter);\n        int rh = height(node->right, diameter);\n        diameter = max(diameter, lh + rh);\n        return 1 + max(lh, rh);\n    }\n};"
    },
    {
        "title": "Sort Characters By Frequency",
        "algo_input": "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.\n\nReturn the sorted string. If there are multiple answers, return any of them.\n\n&nbsp;\nExample 1:\n\nInput: s = \"tree\"\nOutput: \"eert\"\nExplanation: 'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.\n\n\nExample 2:\n\nInput: s = \"cccaaa\"\nOutput: \"aaaccc\"\nExplanation: Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.\n\n\nExample 3:\n\nInput: s = \"Aabb\"\nOutput: \"bbAa\"\nExplanation: \"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 105\n\ts consists of uppercase and lowercase English letters and digits.\n\n",
        "solution_py": "class Solution:\n    def frequencySort(self, s: str) -> str:\n        di = Counter(s)\n        #it wont strike immediately that this is a heap kind of question.\n        heap = []\n        heapq.heapify(heap)\n        for key,val in di.items():\n            heapq.heappush(heap,(-1*val,key))\n        # n = len(s)\n        res = \"\"\n        # print(heap)\n        while(len(heap)):\n            val,ch = heapq.heappop(heap)\n            res+=(ch*(-1*val))\n        return res",
        "solution_js": "var frequencySort = function(s) {\n    let obj = {}\n    for(const i of s){\n        obj[i] = (obj[i] || 0) +1\n    }\n    let sorted = Object.entries(obj).sort((a,b)=> b[1]-a[1])\n    return sorted.map((e)=> e[0].repeat(e[1])).join('')\n};",
        "solution_java": "class Solution {\n    public String frequencySort(String s) {\n      HashMap<Character,Integer> hm1=new HashMap<>();\n      TreeMap<Integer,ArrayList<Character>> hm2=new TreeMap<>(Collections.reverseOrder());\n        for(int i=0;i<s.length();i++)\n        {\n            char c=s.charAt(i);\n            if(hm1.containsKey(c))\n            { \n                hm1.put(c,hm1.get(c) + 1);\n            }\n            else\n            {\n                hm1.put(c,1);\n            }\n        }\n        for(char c : hm1.keySet())\n        {\n            if(hm2.containsKey(hm1.get(c)))\n            {\n                ArrayList<Character> temp=hm2.get(hm1.get(c));\n                temp.add(c);\n                hm2.put(hm1.get(c),temp);\n            }\n            else\n            {\n                ArrayList<Character> temp=new ArrayList<>();\n                temp.add(c);\n                hm2.put(hm1.get(c),temp);\n            }\n        }\n        StringBuilder sb=new StringBuilder(\"\");\n        for(int x :hm2.keySet())\n        {\n            ArrayList<Character> temp=hm2.get(x);\n            for(char c: temp)\n            {\n                for(int i=0;i<x;i++){\n                sb.append(c);\n                }\n            }\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string frequencySort(string s)\n    {\n        unordered_map<char,int>mp;\n        for(int i=0;i<s.length();i++) //get the frequency of every char of the string\n        {\n            mp[s[i]]++;\n        }\n\n        priority_queue<pair<int,char>>pq; //store the freq and char pair in max heap\n        for(auto it=mp.begin();it!=mp.end();it++)\n        {\n            pq.push({it->second,it->first});\n        }\n        string str=\"\";\n        int val;\n        while(!pq.empty())\n        {\n            val=pq.top().first; //append the char frequency times\n            while(val--)\n            {\n                str.push_back(pq.top().second);\n            }\n            pq.pop();\n        }\n        return str;\n\n    }\n};"
    },
    {
        "title": "Edit Distance",
        "algo_input": "Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.\n\nYou have the following three operations permitted on a word:\n\n\n\tInsert a character\n\tDelete a character\n\tReplace a character\n\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"horse\", word2 = \"ros\"\nOutput: 3\nExplanation: \nhorse -&gt; rorse (replace 'h' with 'r')\nrorse -&gt; rose (remove 'r')\nrose -&gt; ros (remove 'e')\n\n\nExample 2:\n\nInput: word1 = \"intention\", word2 = \"execution\"\nOutput: 5\nExplanation: \nintention -&gt; inention (remove 't')\ninention -&gt; enention (replace 'i' with 'e')\nenention -&gt; exention (replace 'n' with 'x')\nexention -&gt; exection (replace 'n' with 'c')\nexection -&gt; execution (insert 'u')\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= word1.length, word2.length &lt;= 500\n\tword1 and word2 consist of lowercase English letters.\n\n",
        "solution_py": "from functools import cache\n\n\nclass Solution:\n    def minDistance(self, word1: str, word2: str) -> int:\n        m, n = len(word1), len(word2)\n        \n        @cache\n        def dp(i, j):\n            if i == 0:\n                return j\n            if j == 0:\n                return i\n            \n            l1, l2 = word1[i - 1], word2[j - 1]\n            if l1 != l2:\n                return 1 + min(\n                    dp(i, j - 1),     # Delete / insert j\n                    dp(i - 1, j),     # Delete / insert i\n                    dp(i - 1, j - 1)  # Replace i or j\n                )\n            return dp(i - 1, j - 1)         \n                    \n        return dp(m, n)",
        "solution_js": "var minDistance = function(word1, word2) {\n    const m = word1.length;\n    const n = word2.length;\n\n    const memo = new Array(m).fill().map(() => new Array(n));\n    const dfs = (i = m - 1, j = n - 1) => {\n        if(i < 0 && j < 0) return 0;\n        if(i < 0 && j >= 0) return j + 1;\n        if(i >= 0 && j < 0) return i + 1;\n        if(memo[i][j] !== undefined) return memo[i][j];\n\n        if(word1[i] === word2[j]) {\n            return memo[i][j] = dfs(i - 1, j - 1);\n        }\n\n        return memo[i][j] = 1 + Math.min(...[\n            dfs(i, j - 1),\n            dfs(i - 1, j),\n            dfs(i - 1, j - 1)\n        ]);\n    }\n\n    return dfs();\n};",
        "solution_java": "class Solution {\n    \n    public int minDistance(String word1, String word2) {\n        int m = word1.length();\n        int n = word2.length();\n        int dp[][] = new int[m][n];\n        for(int i=0 ; i<m ; i++){\n            for(int j=0 ; j<n ; j++){\n                dp[i][j] = -1;\n            }\n        }\n        return solve(word1, word2 , m-1, n-1 ,dp);\n    }\n    \n    public int solve(String str1, String str2, int m , int  n , int dp[][]){\n        if(m<0){\n            return n+1;\n        }\n        if(n<0){\n            return m+1;\n        }\n        if(dp[m][n] != -1){\n            return dp[m][n];\n        }\n        if(str1.charAt(m) == str2.charAt(n)){\n            return solve(str1, str2 , m-1, n-1 ,dp);\n        }\n        else{\n            int min = Math.min(solve(str1, str2, m-1 ,n ,dp), solve(str1, str2, m ,n-1 , dp));\n            dp[m][n] = 1+Math.min(min, solve(str1, str2, m-1, n-1, dp));\n        }\n        return dp[m][n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minDistance(string word1, string word2) {\n        int m = word1.size(), n = word2.size();\n        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));\n        for (int i = 1; i <= m; i++) {\n            dp[i][0] = i;\n        }\n        for (int j = 1; j <= n; j++) {\n            dp[0][j] = j;\n        }\n        for (int i = 1; i <= m; i++) {\n            for (int j = 1; j <= n; j++) {\n                if (word1[i - 1] == word2[j - 1]) {\n                    dp[i][j] = dp[i - 1][j - 1];\n                } else {\n                    dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;\n                }\n            }\n        }\n        return dp[m][n];\n    }\n};"
    },
    {
        "title": "Matrix Diagonal Sum",
        "algo_input": "Given a&nbsp;square&nbsp;matrix&nbsp;mat, return the sum of the matrix diagonals.\n\nOnly include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,2,3],\n&nbsp;             [4,5,6],\n&nbsp;             [7,8,9]]\nOutput: 25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.\n\n\nExample 2:\n\nInput: mat = [[1,1,1,1],\n&nbsp;             [1,1,1,1],\n&nbsp;             [1,1,1,1],\n&nbsp;             [1,1,1,1]]\nOutput: 8\n\n\nExample 3:\n\nInput: mat = [[5]]\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\tn == mat.length == mat[i].length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= mat[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def diagonalSum(self, mat: List[List[int]]) -> int:\n        \n        n = len(mat)\n        \n        mid = n // 2\n        \n        summation = 0\n        \n        for i in range(n):\n            \n            # primary diagonal\n            summation += mat[i][i]\n            \n            # secondary diagonal\n            summation += mat[n-1-i][i]\n            \n            \n        if n % 2 == 1:\n            # remove center element (repeated) on odd side-length case\n            summation -= mat[mid][mid]\n            \n            \n        return summation",
        "solution_js": "var diagonalSum = function(mat) {\n    return mat.reduce((acc, matrix, i)=>{\n      const matrixlength = matrix.length-1;\n       return acc += (i !== matrixlength-i) ? matrix[i]+ matrix[matrixlength-i] : matrix[i];\n    },0)\n};\n\n/*\n*/",
        "solution_java": "class Solution {\n    public int diagonalSum(int[][] mat) {\n        int sum1 = 0;\n        int sum2 = 0;\n        int n = mat.length;\n        for(int i = 0 ; i < n ; i++)\n        {\n            sum1 += mat[i][i];\n            sum2 += mat[i][n-i-1];\n        }\n        int res = sum1 + sum2;\n        if(n%2 != 0)\n        {\n            res -= mat[n/2][n/2];\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int diagonalSum(vector<vector<int>>& mat) {\n     int n = mat.size() ;\n     int ans = 0 ;\n\n     for(int i = 0 ; i < n ; i++){\n        ans = ans + mat[i][i] + mat[i][n - i - 1] ;\n      }\n      ans = (n & 1) ? ans - mat[n/2][n/2] : ans ;//if n is odd then we have to subtract mat[n/2][n/2] from the ans because we add it twice earlier.\n      return ans ;\n    }\n};"
    },
    {
        "title": "Find Peak Element",
        "algo_input": "A peak element is an element that is strictly greater than its neighbors.\n\nGiven a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.\n\nYou may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.\n\nYou must write an algorithm that runs in O(log n) time.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\n\nExample 2:\n\nInput: nums = [1,2,1,3,5,6,4]\nOutput: 5\nExplanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\tnums[i] != nums[i + 1] for all valid i.\n\n",
        "solution_py": "class Solution(object):\n    def findPeakElement(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        nums = [-2**32]+nums+[-2**32]\n        l,r = 0,len(nums)-1\n        while l <=r:\n            m = (l+r)//2\n\t\t\t# we find the target:\n            if nums[m] > nums[m-1] and nums[m] > nums[m+1]:\n                return m -1\n            else:\n                if nums[m] <nums[m+1]:\n                    l = m + 1\n                else:\n                    r = m - 1\n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findPeakElement = function(nums) {\n  if(nums.length === 1) return 0;\n\n  const recursion = (startIndex, endIndex) => {\n     const midIndex = Math.floor((startIndex + endIndex)/2);\n\n     if (startIndex === endIndex) return startIndex;\n     if (startIndex + 1 === endIndex) {\n        return nums[endIndex] >= nums [startIndex] ? endIndex : startIndex;\n     }\n\n     if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return midIndex;\n     if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] < nums[midIndex+1]) return recursion(midIndex + 1, endIndex);\n     if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return recursion(startIndex, midIndex - 1);\n     if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] < nums[midIndex+1])\n        return nums[midIndex-1] > nums[midIndex+1] ? recursion(startIndex, midIndex - 1) : recursion(midIndex + 1, endIndex);\n\n  }\n\n  return recursion(0, nums.length - 1);\n};",
        "solution_java": "class Solution {\n    public int findPeakElement(int[] nums) {\n       int start = 0;\n       int end = nums.length - 1;\n        \n        while(start < end){\n            int mid = start + (end - start) / 2;\n            if(nums[mid] > nums[mid + 1]){\n                //It means that we are in decreasing part of the array\n                end = mid;\n            }\n            else{\n                //It means that we are in increasing part of the array\n                start = mid + 1;\n            }\n        }\n        return start;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findPeakElement(vector<int>& nums) {\n        int peak = 0;\n        for(int i=1; i<nums.size(); i++) {\n            if(nums[i]>nums[i-1])\n                peak = i;\n        }\n        return peak;\n    }\n};"
    },
    {
        "title": "Number of Good Ways to Split a String",
        "algo_input": "You are given a string s.\n\nA split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.\n\nReturn the number of good splits you can make in s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aacaba\"\nOutput: 2\nExplanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\n\n\nExample 2:\n\nInput: s = \"abcd\"\nOutput: 1\nExplanation: Split the string as follows (\"ab\", \"cd\").\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numSplits(self, s: str) -> int:\n        one = set()\n        two = set()\n        dic = {}\n        \n        for i in s:\n            dic[i] = dic.get(i, 0) + 1\n            two.add(i)\n        tot = 0\n        \n        for i in s:\n            one.add(i)\n            dic[i] -= 1\n            if dic[i] == 0:\n                two.remove(i)\n            \n            if len(one) == len(two):\n                tot += 1\n        return tot",
        "solution_js": "var numSplits = function(s) {\n        let n = s.length;\n        let preFix = new Array(n) , suFix = new Array(n);\n        let preSet = new Set();\n        let suSet = new Set();\n\n        for(let i=0; i<n ; i++){\n            preSet.add(s[i]);\n            suSet.add(s[n-1-i]);\n            preFix[i]= preSet.size;\n            suFix[n-1-i]= suSet.size;\n        }\n\n        let goodWays=0;\n\n        for(let i=0; i<n-1; i++){\n            if(preFix[i]===suFix[i+1]) goodWays++;\n        }\n\n        return goodWays;\n};",
        "solution_java": "class Solution {\n    public int numSplits(String s) {\n        int a[] = new int[26];\n        int b[] = new int[26];\n        int ds1=0,ds2=0;\n        int count=0;\n        for(int i=0;i<s.length();i++)\n        {\n            b[s.charAt(i)-97]++;\n            if(b[s.charAt(i)-97] == 1)\n                ds2++;\n        }\n        for(int i=0;i<s.length();i++)\n        {\n            a[s.charAt(i)-97]++;\n            b[s.charAt(i)-97]--;\n            if(b[s.charAt(i)-97] == 0)\n                ds2--;\n            if(a[s.charAt(i)-97] == 1)\n                ds1++;\n            if(ds1 == ds2)\n                count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numSplits(string s) {\n        int n=s.size();\n        vector<int>left(26,0);\n        vector<int>right(26,0);\n        int left_count=0,right_count=0;\n        int splits=0;\n        for(auto &it:s){\n            right[it-'a']++;\n            if(right[it-'a']==1)right_count++;\n        }\n        for(auto &it:s){\n            left[it-'a']++;\n            right[it-'a']--;\n            if(left[it-'a']==1)left_count++;\n            if(right[it-'a']==0)right_count--;\n            if(left_count==right_count)\n                splits++;\n        }\n        return splits;\n    }\n};"
    },
    {
        "title": "Count Pairs With XOR in a Range",
        "algo_input": "Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.\n\nA nice pair is a pair (i, j) where 0 &lt;= i &lt; j &lt; nums.length and low &lt;= (nums[i] XOR nums[j]) &lt;= high.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,4,2,7], low = 2, high = 6\nOutput: 6\nExplanation: All nice pairs (i, j) are as follows:\n    - (0, 1): nums[0] XOR nums[1] = 5 \n    - (0, 2): nums[0] XOR nums[2] = 3\n    - (0, 3): nums[0] XOR nums[3] = 6\n    - (1, 2): nums[1] XOR nums[2] = 6\n    - (1, 3): nums[1] XOR nums[3] = 3\n    - (2, 3): nums[2] XOR nums[3] = 5\n\n\nExample 2:\n\nInput: nums = [9,8,4,2,1], low = 5, high = 14\nOutput: 8\nExplanation: All nice pairs (i, j) are as follows:\n​​​​​    - (0, 2): nums[0] XOR nums[2] = 13\n&nbsp;   - (0, 3): nums[0] XOR nums[3] = 11\n&nbsp;   - (0, 4): nums[0] XOR nums[4] = 8\n&nbsp;   - (1, 2): nums[1] XOR nums[2] = 12\n&nbsp;   - (1, 3): nums[1] XOR nums[3] = 10\n&nbsp;   - (1, 4): nums[1] XOR nums[4] = 9\n&nbsp;   - (2, 3): nums[2] XOR nums[3] = 6\n&nbsp;   - (2, 4): nums[2] XOR nums[4] = 5\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t1 &lt;= nums[i] &lt;= 2 * 104\n\t1 &lt;= low &lt;= high &lt;= 2 * 104\n",
        "solution_py": "from collections import defaultdict\n\nclass TrieNode:\n    def __init__(self):\n        self.nodes = defaultdict(TrieNode)\n        self.cnt = 0\n\nclass Trie:\n\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, val):\n        cur = self.root\n        for i in reversed(range(15)):\n            bit = val >> i & 1\n            cur.nodes[bit].cnt += 1\n            cur = cur.nodes[bit]\n\n    def count(self, val, high):\n        res = 0\n        cur = self.root\n        for i in reversed(range(15)):\n            if not cur:\n                break\n            bit = val >> i & 1\n            cmp = high >> i & 1\n            if cmp:\n                res += cur.nodes[bit].cnt\n                cur = cur.nodes[1^bit]\n            else:\n                cur = cur.nodes[bit]\n        return res\n\nclass Solution:\n    def countPairs(self, nums: List[int], low: int, high: int) -> int:\n        trie = Trie()\n        res = 0\n        for num in nums:\n            res += trie.count(num, high + 1) - trie.count(num, low)\n            trie.insert(num)\n\n        return res",
        "solution_js": "var countPairs = function(nums, low, high) {\n    function insert(num){\n        var node = root;\n        for(i = 14; i>=0; i--)\n        {\n            var bit = (num >> i) & 1;\n            if(!node.children[bit])\n            {\n                node.children[bit] = new TrieNode();\n            }\n            node.children[bit].cnt += 1;\n            node = node.children[bit];\n        }\n    }\n    function countSmallerNums(num, limit)\n    {\n        var cnt = 0;\n        // count pairs with num strictly smaller than limit\n        var node = root;\n        for(i = 14; i>=0 && node; i--)\n        {\n            var lbit = (limit>>i) & 1;\n            var nbit = (num >> i) & 1;\n            if(lbit===1)\n            {\n                // we can decrease on 1 bit\n                if(node.children[nbit])\n                {\n                     cnt += node.children[nbit].cnt;\n                }\n                // go to another way to find next bit count\n                node = node.children[1-nbit];\n            }\n            else\n            {\n                // cannot increase the lbit === 0,\n                // find the same Nbit to XOR to be '0'\n                node = node.children[nbit];\n            }\n        }\n        return cnt;\n    }\n    // starts here\n    var root = new TrieNode();\n    var res =0;\n    for(var num of nums)\n    {\n        res += countSmallerNums(num, high+1) -  countSmallerNums(num, low);\n        insert(num);\n    }\n    return res;\n};\n\nclass TrieNode{\n    constructor()\n    {\n        this.cnt = 0;\n        this.children = new Array(2).fill(null);\n    }\n}",
        "solution_java": "class Solution {\n    public int countPairs(int[] nums, int low, int high) {\n        Trie trie=new Trie();\n        int cnt=0;\n        for(int i=nums.length-1;i>=0;i--){\n            // count all the element whose xor is less the low\n            int cnt1=trie.maxXor(nums[i],low);\n            // count all the element whose xor is less the high+1\n            int cnt2=trie.maxXor(nums[i],high+1);\n            trie.add(nums[i]);\n            cnt+=cnt2-cnt1;\n        }\n        return cnt;\n    }\n}\nclass Trie{\n    private Node root;\n    Trie(){\n        root=new Node();\n    }\n    public void add(int x){\n        Node cur=root;\n        for(int i=31;i>=0;i--){\n            int bit=(x>>i)&1;\n            if(!cur.contains(bit)){\n                cur.put(bit);\n            }\n            cur.inc(bit);\n            cur=cur.get(bit);\n        }\n    }\n    public int maxXor(int x,int limit){\n        int low_cnt=0;\n        Node cur=root;\n        for(int i=31;i>=0 && cur!=null;i--){\n            int bit=(x>>i)&(1);\n            int req=(limit>>i)&1;\n            if(req==1){\n                if(cur.contains(bit)){\n                    low_cnt+=cur.get(bit).cnt;\n                }\n                cur=cur.get(1-bit);\n            }else{\n                cur=cur.get(bit);\n            }\n\n        }\n        return low_cnt;\n\n    }\n}\nclass Node{\n    private Node links[];\n    int cnt;\n    Node(){\n        links=new Node[2];\n        cnt=0;\n    }\n    public void put(int bit){\n        links[bit]=new Node();\n    }\n    public Node get(int bit){\n        return links[bit];\n    }\n    public boolean contains(int bit){\n        return links[bit]!=null;\n    }\n    public void inc(int bit){\n        links[bit].cnt++;\n    }\n}",
        "solution_c": "struct Node {\n    Node* arr[2];\n    int count = 0;\n\n    bool contains(int bitNo) {\n        return arr[bitNo] != NULL;\n    }\n\n    void put(int bitNo, Node* newNode) {\n        arr[bitNo] = newNode;\n    }\n\n    Node* getNext(int bitNo) {\n        return arr[bitNo];\n    }\n\n    int getCount(int bitNo) {\n        return arr[bitNo]->count;\n    }\n\n    void setCount(int bitNo) {\n        arr[bitNo]->count++;\n    }\n};\n\nclass Solution {\npublic:\n\n    Node* root = new Node();\n\n    void insert(int num) {\n        Node* temp = root;\n\n        for(int bit=15; bit>=0; bit--) {\n            int bitVal = (bool)(num & (1<<bit));\n\n            if(!temp->contains(bitVal)) {\n                temp->put(bitVal, new Node());\n            }\n            temp->setCount(bitVal);\n            temp = temp->getNext(bitVal);\n        }\n    }\n\n    int getPairs(int num, int k) {\n        Node* temp = root;\n\n        int cntPairs = 0;\n\n        for(int bit=15; bit>=0 && temp; bit--) {\n            int bit_num = (bool)(num & (1<<bit));\n            int bit_k = (bool)(k & (1<<bit));\n\n            if(bit_k) {\n                if(temp->contains(bit_num)) {\n                    cntPairs += temp->getCount(bit_num);\n                }\n                if(temp->contains(1 - bit_num)) {\n                    temp = temp->getNext(1 - bit_num);\n                }\n                else break;\n            }\n            else if(temp->contains(bit_num)) {\n                temp = temp->getNext(bit_num);\n            }\n            else {\n                break;\n            }\n        }\n        return cntPairs;\n    }\n\n    int countPairs(vector<int>& nums, int low, int high) {\n\n        int n = nums.size();\n        int cnt = 0;\n        for(int i=0; i<n; i++) {\n            cnt += getPairs(nums[i], high+1) - getPairs(nums[i], low);\n            insert(nums[i]);\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Maximum Binary Tree II",
        "algo_input": "A maximum tree is a tree where every node has a value greater than any other value in its subtree.\n\nYou are given the root of a maximum binary tree and an integer val.\n\nJust as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:\n\n\n\tIf a is empty, return null.\n\tOtherwise, let a[i] be the largest element of a. Create a root node with the value a[i].\n\tThe left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).\n\tThe right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).\n\tReturn root.\n\n\nNote that we were not given a directly, only a root node root = Construct(a).\n\nSuppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.\n\nReturn Construct(b).\n\n&nbsp;\nExample 1:\n\nInput: root = [4,1,3,null,null,2], val = 5\nOutput: [5,4,null,1,3,null,null,2]\nExplanation: a = [1,4,2,3], b = [1,4,2,3,5]\n\n\nExample 2:\n\nInput: root = [5,2,4,null,1], val = 3\nOutput: [5,2,4,null,1,null,3]\nExplanation: a = [2,1,5,4], b = [2,1,5,4,3]\n\n\nExample 3:\n\nInput: root = [5,2,3,null,1], val = 4\nOutput: [5,2,4,null,1,3]\nExplanation: a = [2,1,5,3], b = [2,1,5,3,4]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t1 &lt;= Node.val &lt;= 100\n\tAll the values of the tree are unique.\n\t1 &lt;= val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    \"\"\"\n    approach:\n    given a, we can get the inorder traversal of it, then append val to it and\n    then construct the tree back\n    \"\"\"\n    def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n        inorder_list = []\n        def inorder(root):\n            if not root:\n                return\n            inorder(root.left)\n            inorder_list.append(root.val)\n            inorder(root.right)\n            \n        inorder(root)\n        inorder_list.append(val)\n        \n        def get_maximum(val_list):\n            max_index = -1\n            max_val = -1\n            for i, val in enumerate(val_list):\n                if val > max_val:\n                    max_val = val\n                    max_index = i\n            return max_index, max_val\n                \n        def create_tree(val_list):\n            if not len(val_list):\n                return None\n            index, val = get_maximum(val_list)\n            node = TreeNode(val)\n            node.left = create_tree(val_list[:index])\n            node.right = create_tree(val_list[index+1:])\n            return node\n        \n        b = create_tree(inorder_list)\n        return b",
        "solution_js": "/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nvar insertIntoMaxTree = function(root, val) {\n    // get new node\n    var node = new TreeNode(val);\n\n    // no root\n    if(!root) {\n        return node;\n    }\n\n    // upward derivation if val larger then root\n    if(val > root.val) {\n        return node.left = root, node;\n    }\n\n    // downward derivation\n    root.right = insertIntoMaxTree(root.right, val);\n\n    // root construct\n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode insertIntoMaxTree(TreeNode root, int val) {\n        if (root==null) return new TreeNode(val);\n        if (val > root.val) {\n            TreeNode newRoot = new TreeNode(val);\n            newRoot.left = root;\n            return newRoot;\n        }\n        root.right = insertIntoMaxTree(root.right, val);\n        return root;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n\n    void insertIntoMaxTreeRec(TreeNode* root,TreeNode* newNode)//o(logn)\n    {\n\n        if(!root)\n            return;\n        if(root->right&&root->right->val<newNode->val)\n        {\n            newNode->left=root->right;\n            root->right=newNode;\n\n            return;\n\n        }\n        if(!root->right)\n        {root->right=newNode;\n\n        return;}\n\n         insertIntoMaxTreeRec( root->right, newNode);\n\n    }\n    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {\n         TreeNode* curr=new TreeNode(val);\n\n        if(root->val<val)\n        {\n            curr->left=root;\n            root=curr;\n        }else\n        {\n              insertIntoMaxTreeRec( root, curr);\n\n        }\n        return root;\n\n    }\n};"
    },
    {
        "title": "Find Kth Bit in Nth Binary String",
        "algo_input": "Given two positive integers n and k, the binary string Sn is formed as follows:\n\n\n\tS1 = \"0\"\n\tSi = Si - 1 + \"1\" + reverse(invert(Si - 1)) for i &gt; 1\n\n\nWhere + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).\n\nFor example, the first four strings in the above sequence are:\n\n\n\tS1 = \"0\"\n\tS2 = \"011\"\n\tS3 = \"0111001\"\n\tS4 = \"011100110110001\"\n\n\nReturn the kth bit in Sn. It is guaranteed that k is valid for the given n.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, k = 1\nOutput: \"0\"\nExplanation: S3 is \"0111001\".\nThe 1st bit is \"0\".\n\n\nExample 2:\n\nInput: n = 4, k = 11\nOutput: \"1\"\nExplanation: S4 is \"011100110110001\".\nThe 11th bit is \"1\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 20\n\t1 &lt;= k &lt;= 2n - 1\n\n",
        "solution_py": "class Solution:\n    def findKthBit(self, n: int, k: int) -> str:\n        i, s, hash_map = 1, '0', {'1': '0', '0': '1'}\n        for i in range(1, n):\n            s = s + '1' + ''.join((hash_map[i] for i in s))[::-1]\n        return s[k-1]",
        "solution_js": "var findKthBit = function(n, k) {\n    return recursivelyGenerate(n-1)[k-1];\n}\n\nfunction recursivelyGenerate(bitLength, memo=new Array(bitLength+1)){\n    if(bitLength===0) return \"0\";\n    if(memo[bitLength]) return memo[bitLength];\n    const save = recursivelyGenerate(bitLength-1);\n    memo[bitLength] = save + '1' + reverseInvert(save);\n    return memo[bitLength];\n}\n\nfunction reverseInvert(s){\n    return s.split(\"\").map(a=>a==='0'?'1':'0').reverse().join(\"\");\n}",
        "solution_java": "class Solution {\n   private String invert(String s){\n        char [] array=s.toCharArray();\n        for(int i=0;i<s.length();i++){\n            if(array[i]=='1'){\n                array[i]='0';\n            }\n            else{\n                array[i]='1';\n            }\n        }\n        return new String(array);\n    }\n    private String reverse(String s){\n        StringBuilder str=new StringBuilder(s);\n        return str.reverse().toString();\n    }\n    private String func(int i){\n        if(i==0){\n            return \"0\";\n        }\n        return func(i-1)+\"1\"+reverse(invert(func(i-1)));\n    }\n    public char findKthBit(int n, int k) {\n        String s=func(n-1);\n        return s.charAt(k-1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string Reverse(string s){\n        for(int i=0;i<s.length()/2;i++){\n            swap(s[i],s[s.length()-1-i]);\n        }\n        return s;\n    }\n\n    string invert(string s){\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='1') s[i]='0';\n            else s[i]='1';\n        }\n        return s;\n    }\n\n    string S(int n) {\n        if(n==1){\n            return \"0\";\n        }\n        return S(n-1) + \"1\" + Reverse(invert(S(n-1)));\n    }\n\n    char findKthBit(int n, int k) {\n        if(n==1) return '0';\n        string s = S(n-1) + \"1\" + Reverse(invert(S(n-1)));\n        return s[k-1];\n    }\n};"
    },
    {
        "title": "Minimum Time Visiting All Points",
        "algo_input": "On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.\n\nYou can move according to these rules:\n\n\n\tIn 1 second, you can either:\n\n\t\n\t\tmove vertically by one&nbsp;unit,\n\t\tmove horizontally by one unit, or\n\t\tmove diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).\n\t\n\t\n\tYou have to visit the points in the same order as they appear in the array.\n\tYou are allowed to pass through points that appear later in the order, but these do not count as visits.\n\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,1],[3,4],[-1,0]]\nOutput: 7\nExplanation: One optimal path is [1,1] -&gt; [2,2] -&gt; [3,3] -&gt; [3,4] -&gt; [2,3] -&gt; [1,2] -&gt; [0,1] -&gt; [-1,0]   \nTime from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds\n\nExample 2:\n\nInput: points = [[3,2],[-2,2]]\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\tpoints.length == n\n\t1 &lt;= n&nbsp;&lt;= 100\n\tpoints[i].length == 2\n\t-1000&nbsp;&lt;= points[i][0], points[i][1]&nbsp;&lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def minTimeToVisitAllPoints(self, points):\n        res = 0\n        n = len(points)\n        for i in range(n-1):\n            dx = abs(points[i+1][0]-points[i][0])\n            dy = abs(points[i+1][1]-points[i][1])\n            res+= max(dx,dy)\n        return res\n\n            \nobj = Solution()\nprint(obj.minTimeToVisitAllPoints([[1,1],[3,4],[-1,0]]))",
        "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\nvar minTimeToVisitAllPoints = function(points) {\n    let sum = 0;\n    for(let i=1; i<points.length; i++){\n        sum += Math.max(Math.abs(points[i][0] - points[i-1][0]) , Math.abs(points[i][1] - points[i-1][1]));\n    }\n    return sum;\n};",
        "solution_java": "class Solution {\n    public int minTimeToVisitAllPoints(int[][] points) {\n        int max = 0, x, y;\n        for(int i = 0; i < points.length - 1; i++){\n            for(int j = 0; j < points[i].length - 1; j++){\n                x = Math.abs(points[i][j] - points[i+1][j]);\n                y = Math.abs(points[i][j+1] - points[i+1][j+1]);\n                max += Math.max(x,y);\n            }\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minTimeToVisitAllPoints(vector<vector<int>>& points) {\n        vector<int>sk;\n        int x,y,maxy=0;\n        for(int i=0;i<points.size()-1;i++){\n            for(int j=0;j<points[i].size()-1;j++){\n                x=abs(points[i][j]-points[i+1][j]);\n                y=abs(points[i][j+1]-points[i+1][j+1]);\n                maxy+=std::max(x,y);\n            }\n        }\n        return maxy;\n    }\n};"
    },
    {
        "title": "Number of Distinct Roll Sequences",
        "algo_input": "You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:\n\n\n\tThe greatest common divisor of any adjacent values in the sequence is equal to 1.\n\tThere is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) &gt; 2.\n\n\nReturn the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.\n\nTwo sequences are considered distinct if at least one element is different.\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: 184\nExplanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\nSome invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).\n(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).\n(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.\nThere are a total of 184 distinct sequences possible, so we return 184.\n\nExample 2:\n\nInput: n = 2\nOutput: 22\nExplanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).\nSome invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\nThere are a total of 22 distinct sequences possible, so we return 22.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "mod=1000000007\n@cache\ndef func(n,prev,pp):\n    if n==0:\n        return 1\n    ans=0\n    for i in range(1,7):\n        if prev==-1:\n            ans+=func(n-1,i,prev)\n            ans=ans%mod\n        elif pp==-1:\n            if(math.gcd(i,prev)==1 and i!=prev):\n                ans+=func(n-1,i,prev)\n                ans=ans%mod\n        else:\n            if(math.gcd(i,prev)==1 and i!=prev and i!=pp):\n                ans+=func(n-1,i,prev)\n                ans=ans%mod\n    return ans;\nclass Solution:\n    \n            \n    def distinctSequences(self, n: int) -> int:\n        return func(n,-1,-1)",
        "solution_js": "var distinctSequences = function(n) {\n    // 3D DP [n + 1][7][7] => rollIdx, prev, prevPrev\n    const dp = Array.from({ length: n + 1}, () => {\n        return new Array(7).fill(0).map(() => new Array(7).fill(0));\n    });\n\n    const gcd = (a, b) => {\n        if(a < b) [b, a] = [a, b];\n        while(b) {\n            let temp = b;\n            b = a % b;\n            a = temp;\n        }\n        return a;\n    }\n\n    const ds = (n, p = 0, pp = 0) => {\n        if(n == 0) return 1;\n        if(dp[n][p][pp] == 0) {\n            for(let i = 1; i <= 6; i++) {\n                if((i != p && i != pp) && (p == 0 || gcd(p, i) == 1)) {\n                    dp[n][p][pp] = (dp[n][p][pp] + ds(n - 1, i, p)) % 1000000007;\n                }\n            }\n        }\n        return dp[n][p][pp];\n    }\n    return ds(n);\n};",
        "solution_java": "class Solution {\n    static long[][] dp;\n    public int distinctSequences(int n) {\n        if(n==1) return 6;\n        int mod = 1_000_000_007;\n        dp =new long[][]\n                {\n                    {0,1,1,1,1,1},\n                    {1,0,1,0,1,0},\n                    {1,1,0,1,1,0},\n                    {1,0,1,0,1,0},\n                    {1,1,1,1,0,1},\n                    {1,0,0,0,1,0}\n                };\n        for(int i=2;i<n;i++){\n            long[][] temp = new long[6][6];\n            for(int j=0;j<6;j++){\n                for(int k=0;k<6;k++){\n                    long total = 0;\n                    if(dp[j][k] == 0) continue;\n                    for(int l=0;l<6;l++){\n                        total = (total + ((l==k)?0:dp[l][j]))%mod;\n                    }\n                    temp[j][k] = total;\n                }\n            }\n            dp = temp;\n        }\n        long result = 0;\n        for(int i=0;i<6;i++){\n            for(int j=0;j<6;j++){\n                result = (result + dp[i][j])%mod;\n            }\n        }\n        return (int)(result);\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n\tint mod = 1e9+7;\n\n\tint f(int ind,int prev1,int prev2,int n){\n\t\t//Base Case\n\t\tif(ind == n) return 1;\n\n\t\tint ans = 0;\n\t\tfor(int i = 1;i <= 6;i++) //Exploring all possible values\n\t\t\tif(prev1 != i && prev2 != i && (prev1 == 0 || __gcd(prev1,i) == 1))\n\t\t\t\tans = (ans + f(ind+1,i,prev1,n))%mod;\n\n\t\treturn ans;\n\t}\npublic:\n\tint distinctSequences(int n) {\n\t\treturn f(0,0,0,n);\n\t}\n};"
    },
    {
        "title": "Number of Ways to Paint N × 3 Grid",
        "algo_input": "You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\n\nGiven n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 12\nExplanation: There are 12 possible way to paint the grid as shown.\n\n\nExample 2:\n\nInput: n = 5000\nOutput: 30228214\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\t1 &lt;= n &lt;= 5000\n\n",
        "solution_py": "class Solution:\n    def numOfWays(self, n: int) -> int:\n        two_c_options = 6\n        tot_options = 12\n        for i in range(n-1):\n            temp = tot_options\n            tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4)\n            two_c_options = (two_c_options * 3) + ((temp - two_c_options) * 2)\n            tot_options = tot_options % (1000000007)\n        return tot_options",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar numOfWays = function(n) {\n  const mod = Math.pow(10, 9) + 7;\n  const dp212 = [6];\n  const dp123 = [6];\n  for (let i = 1; i < n; i++) {\n    // two sides same\n    dp212[i] = (dp212[i - 1] * (5 - 2) + dp123[i - 1] * (6 - 2 - 1 - 1)) % mod;\n    // three different colors\n    dp123[i] = (dp123[i - 1] * (5 - 1 - 1 - 1) + dp212[i - 1] * (6 - 2 - 2)) % mod;\n  }\n  return (dp212[n - 1] + dp123[n - 1]) % mod;\n};",
        "solution_java": "class Solution {\n    int MOD = 1000000007;\n    int[][] states = {{0,1,0},{1,0,1},{2,0,1},\n                      {0,1,2},{1,0,2},{2,0,2},\n                      {0,2,0},{1,2,0},{2,1,0},\n                      {0,2,1},{1,2,1},{2,1,2}};\n    \n    HashMap<Integer, List<Integer>> nextMap = new HashMap<>();\n    Long[][] memo;\n    \n    public int numOfWays(int n) {\n        if(n == 0)\n            return 0;\n        \n\t\t// Graph\n        for(int prev = 0; prev < 12; prev++){\n            List<Integer> nexts = new ArrayList<>();\n            for(int next = 0; next < 12; next++){\n                if(next == prev) continue;\n            \n                boolean flag = true;\n                for(int i = 0; i < 3; i++){\n                    if(states[prev][i] == states[next][i]){\n                        flag = false;\n                        break;\n                    }\n                }\n                if(flag)\n                    nexts.add(next);\n            }\n            nextMap.put(prev, nexts);\n        }\n\t\t\n\t\t//DFS\n        memo = new Long[12][n];\n        long ways = 0;\n        for(int i = 0; i < 12; i++){\n            ways += dfs(i, n-1);\n            ways %= MOD;\n        }\n        \n        return (int)(ways);\n    }\n    \n    long dfs(int prev, int n){\n        if(n == 0)\n            return 1;\n        \n        if(memo[prev][n] != null)\n            return memo[prev][n];\n        \n        long ways = 0;\n        \n        List<Integer> nexts = nextMap.get(prev);\n        for(int next : nexts){\n            ways += dfs(next, n-1);\n            ways %= MOD;\n        }\n        \n        memo[prev][n] = ways;\n        return ways;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numOfWays(int n) {\n        int mod=1e9+7;\n        long long c2=6,c3=6;\n        for(int i=2;i<=n;i++){\n            long long temp=c3;\n            c3=(2*c3+2*c2)%mod;\n            c2=(2*temp+3*c2)%mod;\n        }\n        return (c2+c3)%mod;\n    }\n};"
    },
    {
        "title": "Network Delay Time",
        "algo_input": "You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.\n\nWe will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.\n\n&nbsp;\nExample 1:\n\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput: 2\n\n\nExample 2:\n\nInput: times = [[1,2,1]], n = 2, k = 1\nOutput: 1\n\n\nExample 3:\n\nInput: times = [[1,2,1]], n = 2, k = 2\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= n &lt;= 100\n\t1 &lt;= times.length &lt;= 6000\n\ttimes[i].length == 3\n\t1 &lt;= ui, vi &lt;= n\n\tui != vi\n\t0 &lt;= wi &lt;= 100\n\tAll the pairs (ui, vi) are unique. (i.e., no multiple edges.)\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n        \n        adjlist = [[] for _ in range(n+1)]\n        \n        for src, dst, weight in times:\n            adjlist[src].append((dst, weight))\n        \n        visited = [-1]*(n+1)\n        captured =[-1]*(n+1)\n\n        priority_queue = [(0,k)]\n    \n        nums = 0\n        total_dist = 0\n        \n        while priority_queue:\n\n            dst, node = heapq.heappop(priority_queue)\n\n            if captured[node] != -1:\n                continue\n            captured[node] = dst\n            \n            nums += 1\n            total_dist = dst\n            \n            for nbr,wt in adjlist[node]:\n                if captured[nbr] == -1:\n                    heapq.heappush(priority_queue,(captured[node]+wt, nbr))\n        if nums == n:\n            return total_dist\n        else:\n            return -1",
        "solution_js": "/**\n * @param {number[][]} times\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\n\nlet visited,edges,dijkastra_arr,min_heap\nconst MAX_VALUE=Math.pow(10,6);\n\nconst dijkastra=(source)=>{\n    visited[source]=true;\n    min_heap.pop();\n    let nei=edges[source]||[];\n    // if(!nei.length)return;\n    for(let i=0;i<nei.length;i++){\n        let[src,dst,t]=nei[i];\n        if(visited[dst])continue;\n        let time_till_src=dijkastra_arr[src];\n        if(time_till_src>=MAX_VALUE)continue;\n        let time_till_dst=time_till_src+t;\n        dijkastra_arr[dst]=Math.min(dijkastra_arr[dst],time_till_dst);\n    }\n    min_heap.sort((a,b)=>{\n        return dijkastra_arr[b]-dijkastra_arr[a];\n    });\n    if(min_heap.length && dijkastra_arr[min_heap[min_heap.length-1]]<MAX_VALUE)\n    dijkastra(min_heap[min_heap.length-1]);\n\n}\nvar networkDelayTime = function(times, n, k) {\n    visited=[];\n    edges={};\n    dijkastra_arr=[];\n    min_heap=[];\n\n    for(let i=0;i<times.length;i++){\n        if(!edges[times[i][0]])edges[times[i][0]]=[];\n        edges[times[i][0]].push(times[i]);\n    }\n    // console.log(edges,\"edges\")\n    for(let i=0;i<=n;i++){\n        if(i===0){//cz numbes are starting from One\n            visited[i]=true;\n            dijkastra_arr[i]=-1;\n            min_heap[i]=i;\n        }else{\n                  min_heap[i]=i;\n        dijkastra_arr[i]=MAX_VALUE;\n        visited[i]=false;\n        }\n\n    }\n\n    dijkastra_arr[k]=0;\n    min_heap.sort((a,b)=>{\n        return dijkastra_arr[b]-dijkastra_arr[a];\n    });\n    min_heap.pop();//For removing zeroth entry;\n    dijkastra(k);\n    let max_time=0;\n    if(min_heap.length)return -1;\n        for(let i=0;i<dijkastra_arr.length;i++){\n            max_time=Math.max(dijkastra_arr[i],max_time);\n    }\n    return max_time;\n};",
        "solution_java": "class Solution {\n    HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>();\n    public int networkDelayTime(int[][] times, int n, int k) {\n        for (int i = 1; i <= n; i++) {\n            map.put(i, new HashMap<>());\n        }\n        for (int i = 0; i < times.length; i++) {\n            map.get(times[i][0]).put(times[i][1], times[i][2]);\n        }\n        int ans = BFS(k, n);\n\n        return ans == 1000 ? -1 : ans;\n    }\n    public int BFS(int k, int n) {\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        int[] timeReach = new int[n + 1];\n        Arrays.fill(timeReach, 1000);\n        timeReach[0] = 0;\n\n        timeReach[k] = 0;\n\n        queue.add(k);\n\n        while (!queue.isEmpty()) {\n            int rv = queue.remove();\n            for (int nbrs : map.get(rv).keySet()) {\n                int t = map.get(rv).get(nbrs) + timeReach[rv];\n                if (t < timeReach[nbrs]) {\n                    timeReach[nbrs] = t;\n                    queue.add(nbrs);\n                }\n            }\n        }\n\n        int time = 0;\n\n        for (int i : timeReach) {\n            time = Math.max(i, time);\n        }\n\n        return time;\n    }\n}",
        "solution_c": "class cmp{\n  public:\n    bool operator()(pair<int,int> &a,pair<int,int> &b)\n    {\n        return a.second>b.second;\n    }\n};\n\nclass Solution {\npublic:\n    int networkDelayTime(vector<vector<int>>& times, int n, int k) {\n        vector<pair<int,int>> a[n];\n        for(auto it:times)\n        {\n            a[it[0]-1].push_back({it[1]-1,it[2]});\n        }\n\n        priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> pq;\n        vector<int> dist(n,1e7);\n\n        pq.push({k-1,0});\n\n        vector<int> vis(n,0);\n        while(pq.size())\n        {\n            auto curr = pq.top();\n            pq.pop();\n\n            int v = curr.first;\n            int w = curr.second;\n\n            if(vis[v])continue;\n\n            vis[v] = 1;\n            dist[v] = w;\n            for(auto it:a[v])\n            {\n                if(vis[it.first]==0)\n                {\n                    pq.push({it.first,it.second + w});\n                }\n            }\n        }\n\n        int mx = INT_MIN;\n        for(auto it:dist)\n            mx = max(mx,it);\n\n        if(mx>=1e7)return -1;\n        return mx;\n\n    }\n};"
    },
    {
        "title": "Remove Duplicates from Sorted List II",
        "algo_input": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,3,4,4,5]\nOutput: [1,2,5]\n\n\nExample 2:\n\nInput: head = [1,1,1,2,3]\nOutput: [2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 300].\n\t-100 &lt;= Node.val &lt;= 100\n\tThe list is guaranteed to be sorted in ascending order.\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if (not head):\n            return None\n\n        result = tail = ListNode(-1)\n\n        while(head):\n            curr = head\n            head = head.next\n            hasDup = False\n            while(head) and (curr.val == head.val):\n                hasDup = True\n                headNext = head.next\n                head = None\n                head = headNext\n\n            if (hasDup == False):\n                tail.next = curr\n                tail = tail.next\n                tail.next = None\n\n        return result.next",
        "solution_js": "var deleteDuplicates = function(head) {\n    \n    let map = new Map()\n    let result = new ListNode(-1)\n    \n    let newCurr = result\n    let curr = head\n    \n    while(head){\n        if(map.has(head.val)){\n            map.set(head.val, 2)\n        }else{\n            newArr.push(head.val)\n            map.set(head.val, 1)\n        }\n        head = head.next\n    }\n    \n    while(curr){\n        if(map.get(curr.val) !== 2){\n            newCurr.next = new ListNode(curr.val)\n            newCurr = newCurr.next\n        }\n        curr = curr.next\n    }\n    \n    return result.next\n};",
        "solution_java": "class Solution {\n    public ListNode deleteDuplicates(ListNode head) {\n        if (head == null) return head;\n        ListNode temp = head;\n        int last = -1;\n        int[]array = new int[201];\n        // zero == index 100\n        // one == index 101;\n        // -100 == index 0;\n\n        while (temp != null){\n            array[temp.val + 100]++;\n            temp = temp.next;\n        }\n        for (int i = 0; i < 201; i++){\n            if (array[i] == 1){\n                last = i;\n            }\n        }\n        if (last == -1) return null;\n        temp = head;\n\n        for (int i = 0; i < 201; i++){\n            if (array[i] == 1){\n                temp.val = i - 100;\n                if (i == last){\n                    temp.next = null;\n                    break;\n                }\n                temp=temp.next;\n            }\n        }\n        temp.next = null;\n\n        return head;\n    }\n}```",
        "solution_c": "class Solution {\npublic:\n    ListNode* deleteDuplicates(ListNode* head) {\n        ListNode* k=new ListNode();\n        ListNode *root=k,*cur=head;\n        while(cur!=NULL)\n        {\n            ListNode *t=cur;\n            while(t->next!=NULL && t->next->val==t->val)\n                t=t->next;\n            if(t==cur)\n            {\n            if(root==NULL)\n                root->val=t->val;\n            else\n            {\n                ListNode* p=new ListNode(t->val);\n                root->next=p;\n                root=root->next;\n            }\n            }\n            cur=t->next;\n        }\n        return k->next;\n    }\n};"
    },
    {
        "title": "Shortest Path Visiting All Nodes",
        "algo_input": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.\n\nReturn the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n\n&nbsp;\nExample 1:\n\nInput: graph = [[1,2,3],[0],[0],[0]]\nOutput: 4\nExplanation: One possible path is [1,0,2,0,3]\n\n\nExample 2:\n\nInput: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput: 4\nExplanation: One possible path is [0,1,4,2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == graph.length\n\t1 &lt;= n &lt;= 12\n\t0 &lt;= graph[i].length &lt;&nbsp;n\n\tgraph[i] does not contain i.\n\tIf graph[a] contains b, then graph[b] contains a.\n\tThe input graph is always connected.\n\n",
        "solution_py": "class Solution:\n    def shortestPathLength(self, graph: List[List[int]]) -> int:\n        n = len(graph)\n        dist = [[inf]*n for _ in range(n)]\n        \n        for i, x in enumerate(graph): \n            dist[i][i] = 0\n            for ii in x: dist[i][ii] = 1\n        \n        # floyd-warshall \n        for k in range(n): \n            for i in range(n): \n                for j in range(n): \n                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n        \n        @cache \n        def fn(x, mask): \n            if mask == 0: return 0 \n            ans = inf \n            for i in range(n): \n                if mask & (1 << i): \n                    ans = min(ans, dist[x][i] + fn(i, mask ^ (1<<i)))\n            return ans \n        \n        return min(fn(x, (1 << n)-1) for x in range(n))",
        "solution_js": "/**\n * @param {number[][]} graph\n * @return {number}\n */\nvar shortestPathLength = function(graph) {\n    const n = graph.length;\n    const allVisited = (1 << n) - 1;\n    const queue = [];\n    const visited = new Set();\n\n    for (let i = 0; i < n; i++) {\n        queue.push([1 << i, i, 0]);\n        visited.add((1 << i) * 16 + i);\n    }\n\n    while (queue.length > 0) {\n        const [mask, node, dist] = queue.shift();\n\n        if (mask === allVisited) {\n            return dist;\n        }\n\n        for (const neighbor of graph[node]) {\n            const newMask = mask | (1 << neighbor);\n            const hashValue = newMask * 16 + neighbor;\n\n            if (!visited.has(hashValue)) {\n                visited.add(hashValue);\n                queue.push([newMask, neighbor, dist + 1]);\n            }\n        }\n    }\n\n    return -1;\n}",
        "solution_java": "class Solution {\n    class Pair {\n        int i;\n        int path;\n        public Pair(int i, int path) {\n            this.i = i;\n            this.path = path;\n        }\n    }\n    public int shortestPathLength(int[][] graph) {\n        /*\n        For each node currentNode, steps as key, visited as value\n        boolean[currentNode][steps]\n        */\n        int n = graph.length;\n\n        // 111....1, 1<< n - 1\n        int allVisited = (1 << n) - 1;\n\n        boolean[][] visited = new boolean[n][1 << n];\n        Queue<Pair> q = new LinkedList<>();\n        for (int i = 0; i < n; i++) {\n            if (1 << i == allVisited) return 0;\n            visited[i][1 << i] = true;\n            q.offer(new Pair(i, 1 << i));\n        }\n        int step = 0;\n        while (!q.isEmpty()) {\n            int size = q.size();\n            for (int i = 0; i < size; i++) {\n                Pair p = q.poll();\n                int[] edges = graph[p.i];\n\n                for(int t: edges) {\n                    int path = p.path | (1 << t);\n                    if (path == allVisited) return step + 1;\n                    if (!visited[t][path]) {\n                        visited[t][path] = true;\n                        q.offer(new Pair(t, path));\n                    }\n                }\n            }\n            step++;\n        }\n        return step;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int shortestPathLength(vector<vector<int>>& graph) {\n        int n = graph.size();\n        string mask = \"\";\n        string eq = \"\";\n        for(int i=0; i<n; i++){\n            mask += '0';\n            eq += '1';\n        }\n        queue<pair<int,string>>q;\n        set<pair<int,string>>s;\n        for(int i=0; i<n; i++){\n            string temp = mask;\n            temp[i] = '1';\n            q.push({i,temp});\n            s.insert({i,temp});\n        }\n        int c = 0;\n        int flag = 0;\n        while(!q.empty()){\n            int size = q.size();\n            for(int i=0; i<size; i++){\n                auto top = q.front();\n                q.pop();\n                if(top.second == eq) return c;\n                for(auto p: graph[top.first]){\n                    string temp1 = top.second;\n                    temp1[p] = '1';\n                    if(s.count({p,temp1}) == 0){\n                        q.push({p,temp1});\n                        s.insert({p,temp1});\n                    }\n                }\n            }\n            c++;\n            cout<<\"c is \"<<c;\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Maximum Length of Repeated Subarray",
        "algo_input": "Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\nOutput: 3\nExplanation: The repeated subarray with maximum length is [3,2,1].\n\n\nExample 2:\n\nInput: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 1000\n\t0 &lt;= nums1[i], nums2[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n        dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)]\n        max_len = 0\n        for row in range(len(nums2)):\n            for col in range(len(nums1)):\n                if nums2[row] == nums1[col]:\n                    dp[row][col] = 1 + dp[row - 1][col - 1]\n                    max_len = max(max_len,dp[row][col])\n                else:\n                    dp[row][col] = 0\n        return max_len\n    ",
        "solution_js": "var findLength = function(nums1, nums2) {\n    let dp = new Array(nums1.length+1).fill(0).map(\n        () => new Array(nums2.length+1).fill(0)\n    )\n    let max = 0;\n    for (let i = 0; i < nums1.length; i++) {\n        for (let j = 0; j < nums2.length; j++) {\n            if (nums1[i] != nums2[j]) {\n                continue;\n            }\n            dp[i+1][j+1] = dp[i][j]+1;\n            max = Math.max(max, dp[i+1][j+1]);\n        }\n    }\n\n    return max;\n};",
        "solution_java": "class Solution {\n    public int findLength(int[] nums1, int[] nums2) {\n        int n=  nums1.length , m = nums2.length;\n        int[][] dp = new int [n+1][m+1];\n        // for(int [] d: dp)Arrays.fill(d,-1);\n        int ans =0;\n            for(int i =n-1;i>=0;i--){\n                for(int j = m-1 ;j>=0;j--){\n                    if(nums1[i]==nums2[j]){\n                        dp[i][j] = dp[i+1][j+1]+1;\n                        if(ans<dp[i][j])ans = dp[i][j];\n                    }\n                }\n            } \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLength(vector<int>& nums1, vector<int>& nums2) {\n        \n        \n        int n1 = nums1.size();\n        int n2 = nums2.size();\n\n        //moving num2 on num1\n        \n        int ptr2 = 0;\n        \n        int cnt = 0;\n        \n        int largest  = INT_MIN;\n        \n        for(int i=0;i<n1;i++)\n        {\n            cnt = 0;\n            for(int j=i,ptr2=0;j<n1 && ptr2<n2;j++,ptr2++)\n            {\n                if(nums1[j]==nums2[ptr2])\n                {\n                    cnt++;\n                    \n                }\n                else\n                {\n                    cnt = 0;\n                }\n                largest = max(largest,cnt);\n            }\n        }\n        \n        //moving num1 on num2\n        ptr2 = 0;\n        cnt = 0;\n        for(int i=0;i<n2;i++)\n        {\n            cnt = 0;\n            for(int j=i,ptr2=0;j<n2 && ptr2<n1;j++,ptr2++)\n            {\n                if(nums2[j]==nums1[ptr2])\n                {\n                    cnt++;\n                }\n                else\n                {\n                    cnt = 0;\n                }\n                largest = max(largest,cnt);\n            }\n        }\n        \n        return largest;\n        \n    }\n};"
    },
    {
        "title": "Stone Game III",
        "algo_input": "Alice and Bob continue their games with piles of stones. 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\nAlice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.\n\nThe score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.\n\nThe objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\n\nAssume Alice and Bob play optimally.\n\nReturn \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score.\n\n&nbsp;\nExample 1:\n\nInput: values = [1,2,3,7]\nOutput: \"Bob\"\nExplanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n\n\nExample 2:\n\nInput: values = [1,2,3,-9]\nOutput: \"Alice\"\nExplanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.\n\n\nExample 3:\n\nInput: values = [1,2,3,6]\nOutput: \"Tie\"\nExplanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= stoneValue.length &lt;= 5 * 104\n\t-1000 &lt;= stoneValue[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def stoneGameIII(self, stoneValue):\n        \"\"\"\n        :type stoneValue: List[int]\n        :rtype: str\n        \"\"\"\n        n = len(stoneValue)\n        suffixSum = [0 for _ in range(n+1)]\n        dp = [0 for _ in range(n+1)]\n        for i in range(n-1, -1, -1):\n            suffixSum[i] = suffixSum[i+1] + stoneValue[i]\n        for i in range(n-1, -1, -1):\n            dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1]\n            for k in range(i+1, min(n, i+3)):\n                dp[i] = max(dp[i], suffixSum[i] - dp[k+1])\n        if dp[0]*2 == suffixSum[0]:\n            return \"Tie\"\n        elif dp[0]*2 > suffixSum[0]:\n            return \"Alice\"\n        else:\n            return \"Bob\"",
        "solution_js": "var stoneGameIII = function(stoneValue) {\n    let len = stoneValue.length-1\n    let bestMoves = [0,0,0]\n    bestMoves[len%3] = stoneValue[len]\n    for(let i = len-1; i >= 0 ; i--){\n        let turn = stoneValue[i]\n        let option1 = turn - bestMoves[(i+1)%3]\n        turn += stoneValue[i+1] ||0\n        let option2 = turn - bestMoves[(i+2)%3]\n        turn += stoneValue[i+2] || 0\n        let option3 = turn - bestMoves[i %3]\n        let best = Math.max(option1,option2,option3)\n        bestMoves[i%3] = best\n    }\n    return bestMoves[0] > 0\n        ? \"Alice\"\n        : bestMoves[0] !== 0\n            ? \"Bob\"\n            : \"Tie\"\n};",
        "solution_java": "class Solution {\n\tInteger[] dp;\n\n\tpublic String stoneGameIII(int[] stoneValue) {\n\t\tdp = new Integer[stoneValue.length + 1];\n\t\n\t\t\tArrays.fill(dp, null);\n\t\t\n\t\tint ans = stoneGameIII(0, stoneValue);\n\t\tif (ans == 0)\n\t\t\treturn \"Tie\";\n\t\telse if (ans > 0)\n\t\t\treturn \"Alice\";\n\t\telse\n\t\t\treturn \"Bob\";\n\t}\n\n\tpublic int stoneGameIII(int l, int[] s) {\n\t\tif (l >= s.length)\n\t\t\treturn 0;\n\t\tif (dp[l] != null)\n\t\t\treturn dp[l];\n\t\tint ans;\n\t\t\tans = Integer.MIN_VALUE;\n\t\t\tif (l < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] - stoneGameIII(l + 1, s));\n\t\t\t}\n\t\t\tif (l + 1 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] -stoneGameIII(l + 2, s));\n\t\t\t}\n\t\t\tif (l + 2 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] +s[l + 2] -stoneGameIII(l + 3, s));\n\t\t\t}\n\t\t \n\t\treturn dp[l] = ans;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n\n    int dp[50001][2][2];\n\n    int playGame(vector<int>& stones, bool alice, bool bob, int i) {\n\n        if (i >= stones.size()) return 0;\n\n        int ans;\n        int sum = 0;\n\n        if (dp[i][alice][bob] != -1) return dp[i][alice][bob];\n\n        if (alice) {\n            ans = INT_MIN;\n            for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) {\n                sum += stones[idx];\n                ans = max(ans, sum + playGame(stones, false, true, idx + 1));\n            }\n        }\n\n        if (bob) {\n            ans = INT_MAX;\n            for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) {\n                sum += stones[idx];\n                ans = min(ans, playGame(stones, true, false, idx + 1));\n            }\n        }\n\n        return dp[i][alice][bob] = ans;\n    }\n\n    string stoneGameIII(vector<int>& stoneValue) {\n        memset(dp, -1, sizeof dp);\n        int totalScore = 0;\n        for (auto i : stoneValue) totalScore += i;\n        int aliceScore = playGame(stoneValue, true, false, 0);\n        if (totalScore - aliceScore > aliceScore)\n            return \"Bob\";\n        else if (totalScore - aliceScore < aliceScore)\n            return \"Alice\";\n        else return \"Tie\";\n    }\n};"
    },
    {
        "title": "Largest Odd Number in String",
        "algo_input": "You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string \"\" if no odd integer exists.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: num = \"52\"\nOutput: \"5\"\nExplanation: The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.\n\n\nExample 2:\n\nInput: num = \"4206\"\nOutput: \"\"\nExplanation: There are no odd numbers in \"4206\".\n\n\nExample 3:\n\nInput: num = \"35427\"\nOutput: \"35427\"\nExplanation: \"35427\" is already an odd number.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 105\n\tnum only consists of digits and does not contain any leading zeros.\n\n",
        "solution_py": "class Solution:\n    def largestOddNumber(self, num: str) -> str:\n        indx = -1\n        n = len(num)\n        for i in range(n):\n            if int(num[i])%2 == 1:\n                indx = i\n        \n        if indx == -1:\n            return \"\"\n        return num[:indx+1]",
        "solution_js": "var largestOddNumber = function(num) {\n    for (let i = num.length - 1; i >= 0; i--) {\n\t    // +num[i] converts string into number like parseInt(num[i])\n        if ((+num[i]) % 2) {\n            return num.slice(0, i + 1);\n        }\n    }\n    return '';\n};",
        "solution_java": "class Solution {\n    public String largestOddNumber(String num) {\n        for (int i = num.length() - 1; i > -1; i--) {\n            if (num.charAt(i) % 2 == 1) return num.substring(0,i+1);\n        }\n        return \"\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestOddNumber(string num) {\n        // Length of the given string\n        int len = num.size();\n        // We initialize an empty string for the result\n        string res = \"\";\n        // We start searching digits from the very right to left because we want to find the first odd digit\n        // Which will be the last digit of our biggest odd number\n        for (int i = len - 1; i >= 0; i--) {\n            // Here we just convert char to an integer in C++\n            // We can also do the reverse operation by adding '0' to an int to get char from an int\n            int isOdd = num[i] - '0';\n            // We check if the current digit is odd, if so this is the position we want to find\n            if (isOdd % 2 == 1) {\n                // Since we have found the correct spot, let's create our result string\n                // We can basically extract the part starting from 0th index to right most odd digit's index\n                // Like this:\n                // 0123456 -> indices\n                // 1246878 -> digits\n                // ^....^ -> The part we extracted [0 to 5]\n                res = num.substr(0, i + 1); // i+1 is length of substring\n                // Because we know this would be the largest substring as we are starting from last\n                // We can terminate the loop and return the result\n                break;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Submatrices That Sum to Target",
        "algo_input": "Given a matrix&nbsp;and a target, return the number of non-empty submatrices that sum to target.\n\nA submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 &lt;= x &lt;= x2 and y1 &lt;= y &lt;= y2.\n\nTwo submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate&nbsp;that is different: for example, if x1 != x1'.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\n\n\nExample 2:\n\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n\n\nExample 3:\n\nInput: matrix = [[904]], target = 0\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= matrix.length &lt;= 100\n\t1 &lt;= matrix[0].length &lt;= 100\n\t-1000 &lt;= matrix[i] &lt;= 1000\n\t-10^8 &lt;= target &lt;= 10^8\n\n",
        "solution_py": "class Solution:\n    def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n        m, n = len(matrix), len(matrix[0])\n        matrix_sums = [[0 for _ in range(n)] for _ in range(m)]\n        \n        # Calculate all the submatrices sum with the transition formula we found\n        for row in range(m):\n            for col in range(n):\n                # first cell\n                if row == 0 and col == 0:\n                    matrix_sums[row][col] = matrix[row][col]\n                # Rows and columns are like prefix sums, without intersection\n                elif row == 0:\n                    matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col-1]\n                elif col == 0:\n                    matrix_sums[row][col] = matrix[row][col] + matrix_sums[row-1][col]\n                \n                # current sum is the sum of the matrix above, to the left and subtract the intersection\n                else:\n                    matrix_sums[row][col] = matrix[row][col] \\\n                    + (matrix_sums[row][col-1]) \\\n                    + (matrix_sums[row-1][col]) \\\n                    - (matrix_sums[row-1][col-1])\n\n                \n        ans = 0\n        # Generate all submatrices\n        for y1 in range(m):\n            for x1 in range(n):\n                for y2 in range(y1, m):\n                    for x2 in range(x1, n):\n                        # calculate sum in O(1)\n                        submatrix_total = matrix_sums[y2][x2] \\\n                        - (matrix_sums[y2][x1-1] if x1-1 >= 0 else 0) \\\n                        - (matrix_sums[y1-1][x2] if y1-1 >= 0 else 0) \\\n                        + (matrix_sums[y1-1][x1-1] if y1-1 >= 0 and x1-1 >= 0 else 0)\n                        \n                        if submatrix_total == target:\n                            ans += 1\n        return ans",
        "solution_js": "var numSubmatrixSumTarget = function(matrix, target) {\n    let result = 0;\n    \n    for (let i = 0; i < matrix.length; i++) {\n        for (let j = 1; j < matrix[0].length; j++) {\n            matrix[i][j] = matrix[i][j] + matrix[i][j-1]\n        }\n    }\n    \n    for (let i = 0; i < matrix[0].length; i++) {\n        for (let j = i; j < matrix[0].length; j++) {\n            let dict = {};\n            let cur = 0;\n            dict[0] = 1;\n            \n            for (let k = 0; k < matrix.length; k++) {\n                cur += matrix[k][j] - ((i > 0)?(matrix[k][i - 1]):0);\n                result += ((dict[cur - target] == undefined)?0:dict[cur - target]);\n                dict[cur] = ((dict[cur] == undefined)?0:dict[cur])+1;\n            } \n        }\n    }\n    \n    return result;\n};",
        "solution_java": "class Solution {\npublic int numSubmatrixSumTarget(int[][] matrix, int target) {\n    int m = matrix.length, n = matrix[0].length;\n\n    int[] summedArray = new int[n];\n    int ans = 0;\n    for(int i = 0; i < m; i++){ //starting row\n        Arrays.fill(summedArray, 0);\n        for(int j = i; j < m; j++){ //ending row\n            for(int k = 0; k < n; k++){ // column\n                summedArray[k] += matrix[j][k];\n            }\n            ans += subarraySum(summedArray, target);\n        }\n    }\n    return ans;\n}\n\n public int subarraySum(int[] nums, int k) {\n    //map<sum, freq>\n    Map<Integer, Integer> map = new HashMap<>();\n    int count = 0;\n    map.put(0,1);\n    int sum = 0;\n    for(int num : nums){\n        sum += num;\n        int diff = sum - k;\n        if(map.containsKey(diff)){\n            count += map.get(diff);\n        }\n        map.put(sum, map.getOrDefault(sum, 0) + 1);\n    }\n    return count;\n}\n}",
        "solution_c": "class Solution {\npublic:\n    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n        int n=matrix.size(),m=matrix[0].size(),count=0;\n        vector<vector<int>>temp(n+1,vector<int>(m));\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                temp[i+1][j]=temp[i][j]+matrix[i][j];\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=i+1;j<=n;j++){\n                for(int k=0;k<m;k++){\n                    int sum=0;\n                    for(int l=k;l<m;l++){\n                        sum+=temp[j][l]-temp[i][l];\n                        if(sum==target){\n                            // cout<<j<<\" \"<<i<<\" \"<<k<<endl;\n                            count++;\n                        }\n                    }\n                }\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Course Schedule II",
        "algo_input": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.\n\n\n\tFor example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\n\n\nReturn the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.\n\n&nbsp;\nExample 1:\n\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: [0,1]\nExplanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].\n\n\nExample 2:\n\nInput: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput: [0,2,1,3]\nExplanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].\n\n\nExample 3:\n\nInput: numCourses = 1, prerequisites = []\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= numCourses &lt;= 2000\n\t0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)\n\tprerequisites[i].length == 2\n\t0 &lt;= ai, bi &lt; numCourses\n\tai != bi\n\tAll the pairs [ai, bi] are distinct.\n\n",
        "solution_py": "class Solution:\n    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n        d = {i:[] for i in range(numCourses)}\n        \n        for crs, prereq in prerequisites:\n            d[crs].append(prereq)\n         \n        visit, cycle = set(), set()\n        output = []\n        def dfs(crs):\n            if crs in cycle:\n                return False\n            if crs in visit:\n                return True\n            \n            cycle.add(crs)\n            for nei in d[crs]:\n                if not dfs(nei):\n                    return False\n            cycle.remove(crs)\n            visit.add(crs)\n            output.append(crs)\n            return True\n        \n        for crs in range(numCourses):\n            if not dfs(crs):\n                return []\n        return output\n            ",
        "solution_js": "/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nvar findOrder = function(numCourses, prerequisites) {\n    let visiting = new Set();\n    const visited = new Set();\n    const adjList = new Map();\n    const result = [];\n    \n\t// Generate scaffold of adjacency list\n\t// initialized with no prereqs\n    for (let i = 0; i < numCourses; i++) {\n        adjList.set(i, []);\n    }\n    \n\t// Fill adjacency list with course prereqs\n\t// Key is the course\n\t// Value is any course prereqs\n    for (const item of prerequisites) {\n        const [course, prereq] = item;\n        adjList.get(course).push(prereq);\n    }\n    \n    const dfs = (node) => {\n\t    // We've already traversed down this path before\n\t\t// and determined that it isn't cyclical\n        if (visited.has(node)) return true;\n\t\t\n\t\t// Visiting keeps track of what we've seen\n\t\t// during this current traversal and determines\n\t\t// if we have a cycle.\n        if (visiting.has(node)) return false;\n  \n\t\t// Mark this node as part of the current traversal\n        visiting.add(node);\n        \n\t\t// Get all adjacent nodes to traverse\n\t\t// traverse them in a loop looking for cycles\n        const children = adjList.get(node);\n        for (const child of children) {\n            if (!dfs(child)) return false;\n        }\n\t\t\n\t\t// Ensures we don't re-traverse already traversed nodes since\n\t\t// we've already determined they contain no cycles.\n        visited.add(node);\n\t\t\n\t\t// Add this node to the result stack to return at the end\n        result.push(node);\n        return true;\n    }\n    \n    for (const node of adjList.keys()) {\n        if(!dfs(node)) return [];\n    }\n    \n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] findOrder(int numCourses, int[][] prerequisites) {\n        Map<Integer, Set<Integer>> graph = new HashMap<>();\n        int[] inDegree = new int[numCourses];\n        for (int i = 0; i < numCourses; i++) {\n            graph.put(i, new HashSet<Integer>());\n        }\n        \n        for (int[] pair : prerequisites) {\n            graph.get(pair[1]).add(pair[0]);\n            inDegree[pair[0]]++;\n        }\n        \n        // BFS - Kahn's Algorithm - Topological Sort\n        Queue<Integer> bfsContainer = new LinkedList<>();\n        for (int i = 0; i < numCourses; i++) {\n            if (inDegree[i] == 0) {\n                bfsContainer.add(i);    \n            }\n        }\n        \n        int count = 0;\n        int[] ans = new int[numCourses];\n        while (!bfsContainer.isEmpty()) {\n            int curr = bfsContainer.poll();\n            ans[count++] = curr;\n            for (Integer num : graph.get(curr)) {\n                inDegree[num]--;\n                if (inDegree[num] == 0) {\n                    bfsContainer.add(num);\n                }\n            }\n        }\n        \n        if (count < numCourses) {\n            return new int[] {};\n        } else {\n            return ans;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {\n        map<int, vector<int>>adj;\n        vector<int> indegree(numCourses,0);\n        vector<int>res;\n        for(int i=0;i<prerequisites.size();i++){\n            adj[prerequisites[i][1]].push_back(prerequisites[i][0]);\n            indegree[prerequisites[i][0]]++;\n        }\n        queue<int> q;\n        for(int i=0;i<numCourses;i++){\n            if(indegree[i]==0)\n                q.push(i);\n        }\n        while(!q.empty()){\n            int x=q.front();\n            q.pop();\n            res.push_back(x);\n            for(auto u:adj[x]){\n                indegree[u]--;\n                if(indegree[u]==0){\n                    q.push(u);\n                }\n            }\n        }\n        if(res.size()==numCourses)\n            return res;\n        return {};\n\n    }\n};"
    },
    {
        "title": "Interval List Intersections",
        "algo_input": "You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.\n\nReturn the intersection of these two interval lists.\n\nA closed interval [a, b] (with a &lt;= b) denotes the set of real numbers x with a &lt;= x &lt;= b.\n\nThe intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].\n\n&nbsp;\nExample 1:\n\nInput: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\n\n\nExample 2:\n\nInput: firstList = [[1,3],[5,9]], secondList = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= firstList.length, secondList.length &lt;= 1000\n\tfirstList.length + secondList.length &gt;= 1\n\t0 &lt;= starti &lt; endi &lt;= 109\n\tendi &lt; starti+1\n\t0 &lt;= startj &lt; endj &lt;= 109 \n\tendj &lt; startj+1\n\n",
        "solution_py": "from collections import deque\n\nclass Solution:\n    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\n        answer = []\n\n        if len(firstList) == 0 or len(secondList) == 0:\n            return answer\n\n        first_queue= deque(firstList)\n        second_queue = deque(secondList )\n\n        first = first_queue.popleft()\n        second = second_queue.popleft()\n\n        while first_queue or second_queue:\n\n            if first[1] < second[0]:\n                if len(first_queue):\n                    first = first_queue.popleft()\n                    continue\n                break\n            if second[1] < first[0]:\n                if len(second_queue) > 0:\n                    second = second_queue.popleft()\n                    continue\n                break\n\n            if first[0] <= second[0] and second[0] <= first[1]:\n                if first[1] <= second[1]:\n                    answer.append([second[0], first[1]])\n                    if len(first_queue) > 0:\n                        first = first_queue.popleft()\n                        continue\n                    break\n\n                else:\n                    answer.append(second)\n                    if len(second_queue) > 0:\n                        second = second_queue.popleft()\n                        continue\n                    break\n            if second[0] <= first[0] and first[0] <= second[1]:\n                if second[1] <= first[1]:\n                    answer.append([first[0], second[1]])\n                    if len(second_queue) > 0:\n                        second = second_queue.popleft()\n                        continue\n                    break\n\n                else:\n                    answer.append(first)\n                    if len(first_queue) > 0:\n                        first = first_queue.popleft()\n                        continue\n                    break\n\n        if first[0] <= second[0] and second[0] <= first[1]:\n            if first[1] <= second[1]:\n\n                if len(answer) > 0:\n\n                    if answer[-1] != [second[0], first[1]]:\n                        answer.append([second[0], first[1]])\n                elif not answer:\n                    answer.append([second[0], first[1]])\n            else:\n                if len(answer) > 0:\n                    if answer[-1] != second:\n                        answer.append(second)\n                elif not answer:\n                    answer.append(second)\n        elif second[0] <= first[0] and first[0] <= second[1]:\n            if second[1] <= first[1]:\n                if len(answer) > 0:\n                    if answer[-1] != [first[0], second[1]]:\n                        answer.append([first[0], second[1]])\n                elif not answer:\n                    answer.append([first[0], second[1]])\n            else:\n                if len(answer) > 0:\n                    if answer[-1] != first:\n                        answer.append(first)\n                elif not answer:\n\n                    answer.append(first)\n\n        return answer",
        "solution_js": "var intervalIntersection = function(firstList, secondList) {\n    //if a overlap b - a.start >= b.start && a.start <= b.end\n    //if b overlap a - b.start >= a.start && b.start <= a.end\n\n    //handle empty edge cases\n    if(firstList.length === 0 || secondList.length === 0){\n        return [];\n    }\n\n    let merged = [];\n    let i =0;\n    let j = 0;\n    while(i<firstList.length && j < secondList.length){\n        let a_overlap_b = firstList[i][0] >= secondList[j][0] && firstList[i][0] <= secondList[j][1];\n        let b_overlap_a = secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1];\n\n        if(a_overlap_b || b_overlap_a){\n            let start = Math.max(firstList[i][0], secondList[j][0]);\n            let end = Math.min(firstList[i][1], secondList[j][1]);\n            merged.push([start, end]);\n        }\n\n        if(firstList[i][1] < secondList[j][1]){\n            i++;\n        }else {\n            j++;\n        }\n    }\n\n    return merged;\n\n};",
        "solution_java": "class Solution {\n    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {\n        int i = 0;\n        int j = 0;\n        \n        List<int[]> ans = new ArrayList<>();\n        \n        while(i<firstList.length && j<secondList.length){\n            int a[] = firstList[i];\n            int b[] = secondList[j];\n            \n            if(b[0]<=a[1] && b[0]>=a[0])\n                ans.add(new int[]{b[0], Math.min(a[1], b[1])});\n            else if(a[0]<=b[1] && a[0]>=b[0])\n                ans.add(new int[]{a[0], Math.min(a[1], b[1])});\n            \n            if(a[1]<=b[1])\n                i++;\n            else\n                j++;\n        }\n        \n        int res[][] = new int[ans.size()][2];\n        \n        for(i=0;i<ans.size();i++){\n            res[i] = ans.get(i);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {\n        vector<vector<int>> result;\n        int i = 0;\n        int j = 0;\n        while(i < firstList.size() && j < secondList.size()){\n            if((firstList[i][0] >= secondList[j][0] && firstList[i][0] <= secondList[j][1])||(secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1]) ){\n                //there is an overlap\n                result.push_back( {max(firstList[i][0], secondList[j][0]), min(firstList[i][1], secondList[j][1])});\n            }\n            if(firstList[i][1] < secondList[j][1]){\n                i++;\n            }\n            else{\n                j++;\n            }\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Maximum Product of Splitted Binary Tree",
        "algo_input": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.\n\nReturn the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.\n\nNote that you need to maximize the answer before taking the mod and not after taking it.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,6]\nOutput: 110\nExplanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n\n\nExample 2:\n\nInput: root = [1,null,2,3,4,null,null,5,6]\nOutput: 90\nExplanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 5 * 104].\n\t1 &lt;= Node.val &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def maxProduct(self, root: Optional[TreeNode]) -> int:\n        def findTotalSum(node, totalSum):\n            if node is None:\n                return totalSum\n            totalSum = findTotalSum(node.left,totalSum)\n            totalSum += node.val\n            totalSum = findTotalSum(node.right,totalSum)\n            return totalSum\n        \n        def dfs(node,maxProd,totalSum):\n            if node is None:\n                return maxProd,0\n            if not node.left and not node.right:\n                return maxProd,node.val\n            maxProd, lSum = dfs(node.left,maxProd,totalSum)\n            maxProd, rSum = dfs(node.right,maxProd,totalSum)\n            subTreeSum = lSum+rSum+node.val\n            maxProd = max(maxProd,(totalSum-lSum)*lSum,(totalSum-rSum)*rSum,(totalSum-subTreeSum)*subTreeSum)\n            return maxProd, subTreeSum\n        \n        totalSum = findTotalSum(root, 0)\n        product,_ = dfs(root,1,totalSum)\n        return product % (pow(10,9)+7)",
        "solution_js": "var maxProduct = function(root) {\n    const lefteRightSumMap = new Map();\n    \n    function getLeftRightSumMap(node) {\n        if (node === null)\n            return 0;\n\n        let leftSum = getLeftRightSumMap(node.left);\n        let rightSum = getLeftRightSumMap(node.right);\n        \n        lefteRightSumMap.set(node, {leftSum, rightSum});\n        \n        return leftSum + rightSum + node.val;\n    }\n    \n    getLeftRightSumMap(root);\n    \n    let maxProduct = -Infinity;\n\n    function getMaxProductDFS(node, parentSum) {\n        if (node === null) return;\n        \n        const {leftSum, rightSum} = lefteRightSumMap.get(node);\n        \n        // cut left edge\n        maxProduct = Math.max(maxProduct, leftSum * (parentSum + node.val + rightSum));\n        \n        // cut right edge\n        maxProduct = Math.max(maxProduct, rightSum * (parentSum + node.val + leftSum));\n\n        getMaxProductDFS(node.left, parentSum + node.val + rightSum);\n        getMaxProductDFS(node.right, parentSum + node.val + leftSum);\n    }\n    \n    getMaxProductDFS(root, 0);\n    \n    return maxProduct % (Math.pow(10, 9) + 7);\n};",
        "solution_java": "class Solution {\n    public void findMaxSum(TreeNode node,long sum[]){\n        if(node==null) return ;\n\n        findMaxSum(node.left,sum);\n        findMaxSum(node.right,sum);\n\n        sum[0]+=node.val;\n\n    }\n\n    public long findProd(TreeNode node,long sum[],long []max){\n        if(node==null) return 0;\n\n        long left=findProd(node.left, sum, max);\n        long right=findProd(node.right,sum,max);\n\n        long val=left+right+node.val;\n\n        max[0]=Math.max(max[0],val*(sum[0]-val));\n\n        return val;\n    }\n    public int maxProduct(TreeNode root) {\n\n        long max[]=new long[1];\n        long sum[]=new long[1];\n\n        findMaxSum(root,sum);\n\n       long n= findProd(root,sum,max);\n\n        return (int)(max[0]%((int)1e9+7));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = 1e9+7;\n    unordered_map<TreeNode*,pair<long long int,long long int>> mp;\n    long long int helper(TreeNode* root){\n        if(!root)\n            return 0;\n        long long int ls = 0,rs = 0;\n        if(root->left)\n            ls = helper(root->left);\n        if(root->right)\n            rs = helper(root->right);\n        mp[root] = {ls,rs};\n        return ls+rs+root->val;\n    }\n    long long int ans = 0;\n    void helper2(TreeNode* root,long long int adon){\n        if(root == NULL)\n            return;\n        long long int x = root->val + adon;\n        ans = max(ans,max((x+mp[root].first)*mp[root].second,(x+mp[root].second)*mp[root].first));\n        helper2(root->left,x+mp[root].second);\n        helper2(root->right,x+mp[root].first);\n    }\n    int maxProduct(TreeNode* root) {\n        long long int x = helper(root);\n        helper2(root,0);\n        return ans%mod;\n    }\n};"
    },
    {
        "title": "Convert Binary Number in a Linked List to Integer",
        "algo_input": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.\n\nReturn the decimal value of the number in the linked list.\n\nThe most significant bit is at the head of the linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,0,1]\nOutput: 5\nExplanation: (101) in base 2 = (5) in base 10\n\n\nExample 2:\n\nInput: head = [0]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tThe Linked List is not empty.\n\tNumber of nodes will not exceed 30.\n\tEach node's value is either 0 or 1.\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def getDecimalValue(self, head: ListNode) -> int:\n        res = 0\n        po = 0\n        stack = []\n        node = head\n        while node:\n            stack.append(node.val)\n            node = node.next\n        res = 0\n        for i in reversed(stack):\n            res += i*(2**po)\n            po += 1\n        return res",
        "solution_js": "var getDecimalValue = function(head) {\n    let str = \"\"\n    while(head){\n        str += head.val\n        head = head.next\n    }\n    return parseInt(str,2)    //To convert binary into Integer",
        "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public int getDecimalValue(ListNode head) {\n        head = reverse(head);\n        int ans = 0;\n        int pow = 0;\n        ListNode temp = head;\n        while(temp != null){\n            ans = ans + temp.val * (int) Math.pow(2,pow++);\n            temp = temp.next;\n        }\n\n        return ans;\n    }\n    public ListNode reverse(ListNode head){\n        ListNode prev = null;\n        ListNode pres = head;\n        ListNode Next = pres.next;\n\n        while(pres != null){\n            pres.next = prev;\n            prev = pres;\n            pres = Next;\n            if(Next != null){\n                Next = Next.next;\n            }\n        }\n\n        head = prev;\n        return head;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getDecimalValue(ListNode* head) {\n        ListNode* temp = head;\n        int count = 0;\n        while(temp->next != NULL){\n            count++;\n            temp = temp->next;\n        }\n        temp = head;\n        int ans = 0;\n        while(count != -1){\n            ans += temp->val * pow(2,count);\n            count--;\n            temp = temp->next;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Subarray of 1's After Deleting One Element",
        "algo_input": "Given a binary array nums, you should delete one element from it.\n\nReturn the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n\n\nExample 2:\n\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n\n\nExample 3:\n\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\tnums[i] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def longestSubarray(self, nums: List[int]) -> int:\n        n = len(nums)\n        pre, suf = [1]*n, [1]*n\n        if nums[0] == 0:pre[0] = 0\n        if nums[-1] == 0:suf[-1] = 0\n        \n        for i in range(1, n):\n            if nums[i] == 1 and nums[i-1] == 1:\n                pre[i] = pre[i-1] + 1\n            elif nums[i] == 0:\n                pre[i] = 0\n        \n        for i in range(n-2, -1, -1):\n            if nums[i] == 1 and nums[i+1] == 1:\n                suf[i] = suf[i+1] + 1\n            elif nums[i] == 0:\n                suf[i] = 0\n        \n        ans = 0\n        for i in range(n):\n            if i == 0:\n                ans = max(ans, suf[i+1])\n            elif i == n-1:\n                ans = max(ans, pre[i-1])\n            else:\n                ans = max(ans, pre[i-1] + suf[i+1])\n        \n        return ans",
        "solution_js": "var longestSubarray = function(nums) {\n    let l = 0, r = 0;\n    let longest = 0;\n    // Keep track of the idx where the last zero was seen\n    let zeroIdx = null;\n    while (r < nums.length) {\n        // If we encounter a zero\n        if (nums[r] === 0) {\n            // If this is the first zero encountered, then set the zeroIdx to the current r index\n            if (zeroIdx === null) zeroIdx = r;\n            else {\n                // If we've already encountered a zero, then set the l index to the zeroIdx + 1,\n\t\t\t\t// effectively removing that zero from the subarray\n                l = zeroIdx + 1;\n                // Then update the zeroIdx to the current r index\n                // This way there will be, at most, one zero in the subarray at all times\n                zeroIdx = r;\n            }\n        }\n        longest = Math.max(longest, r - l);\n        r++;\n    }\n    return longest;\n};",
        "solution_java": "class Solution {\n    public int longestSubarray(int[] nums) {\n        List<Integer> groups = new ArrayList<>();\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] == 0)\n                groups.add(nums[i]);\n            if (nums[i] == 1) {\n                int count = 0;\n                while (i < nums.length && nums[i] == 1) {\n                    count++;\n                    i++;\n                }\n                groups.add(count);\n                if (i < nums.length && nums[i] == 0)\n                    groups.add(0);\n            }\n        }\n        int max = 0;\n        if (groups.size() == 1) {\n            return groups.get(0) - 1;\n        }\n        for (int i = 0; i < groups.size(); i++) {\n            if (i < groups.size() - 2) {\n                max = Math.max(max, groups.get(i) + groups.get(i+2));\n            } else {\n                max = Math.max(max, groups.get(i));\n            }\n        }\n        \n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestSubarray(vector<int>& nums) {\n        int x=0,y=0,cnt=0;\n        for(int i=0;i<nums.size();i++){\n            if(nums[i]==1){\n                x++;\n            }\n            else if(nums[i]==0){\n               cnt=max(cnt,x+y);\n                y=x;\n                x=0;\n            }\n            if(i==nums.size()-1){\n                cnt=max(cnt,x+y);\n            }\n        }\n        if(cnt==nums.size())return cnt-1;\n        return cnt;\n    }\n};"
    },
    {
        "title": "Longest Arithmetic Subsequence",
        "algo_input": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.\n\nRecall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 &lt;= i1 &lt; i2 &lt; ... &lt; ik &lt;= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 &lt;= i &lt; seq.length - 1).\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,6,9,12]\nOutput: 4\nExplanation: \nThe whole array is an arithmetic sequence with steps of length = 3.\n\n\nExample 2:\n\nInput: nums = [9,4,7,2,10]\nOutput: 3\nExplanation: \nThe longest arithmetic subsequence is [4,7,10].\n\n\nExample 3:\n\nInput: nums = [20,1,15,3,10,5,8]\nOutput: 4\nExplanation: \nThe longest arithmetic subsequence is [20,15,10,5].\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 500\n\n",
        "solution_py": "class Solution:\n    def longestArithSeqLength(self, nums: List[int]) -> int:\n        dp = [[1]*1001 for i in range(len(nums))]\n        for i in range(len(nums)):\n            for j in range(i+1,len(nums)):\n                d = nums[j] - nums[i] + 500\n                dp[j][d] = max(dp[i][d]+1,dp[j][d])\n        return max([max(i) for i in dp])",
        "solution_js": "var longestArithSeqLength = function(nums) {\n    if (nums === null || nums.length === 0) {\n        return 0;\n    }\n    let diffMap = new Array(nums.length).fill(0).map(() => new Map());\n    let maxLen = 1;\n    for (let i = 0; i < nums.length; i++) {\n        for (let j = 0; j < i; j++) {\n            let diff = nums[i] - nums[j];\n            // if prev element has an ongoing arithmetic sequence with the same common difference\n            // we simply add 1 to the length of that ongoing sequence, hence diffMap[j].get(diff) + 1\n            // else, we start a new arithmetic sequence, initial length is 2\n            diffMap[i].set(diff, diffMap[j].get(diff) + 1 || 2);\n            maxLen = Math.max(maxLen, diffMap[i].get(diff));\n        }\n    }\n    return maxLen;\n    // T.C: O(N^2)\n    // S.C: O(N^2)\n};",
        "solution_java": "class Solution \n{\n    public int longestArithSeqLength(int[] nums) \n    {\n        int n = nums.length;\n        int longest = 0;\n        Map<Integer, Integer>[] dp = new HashMap[n];\n        \n        for (int i = 0; i < n; i++) \n        {\n            dp[i] = new HashMap<>();\n            \n            for (int j = 0; j < i; j++) \n            {\n                int diff = nums[i] - nums[j];\n                dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1);\n                longest = Math.max(longest, dp[i].get(diff));\n            }\n        }\n        \n        return longest;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestArithSeqLength(vector<int>& nums) {\n        \n        int n=size(nums);\n        int ans=1;\n        vector<vector<int>>  dp(n,vector<int>(1005,1));\n        \n        for(int i=1;i<n;i++) \n            for(int j=0;j<i;j++)\n                ans=max(ans, dp[i][nums[i]-nums[j]+500]= 1+dp[j][nums[i]-nums[j] +500]);\n             \n        \n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Set Intersection Size At Least Two",
        "algo_input": "An integer interval [a, b] (for integers a &lt; b) is a set of all consecutive integers from a to b, including a and b.\n\nFind the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput: 3\nExplanation: Consider the set S = {2, 3, 4}.  For each interval, there are at least 2 elements from S in the interval.\nAlso, there isn't a smaller size set that fulfills the above condition.\nThus, we output the size of this set, which is 3.\n\n\nExample 2:\n\nInput: intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput: 5\nExplanation: An example of a minimum sized set is {1, 2, 3, 4, 5}.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= intervals.length &lt;= 3000\n\tintervals[i].length == 2\n\t0 &lt;= ai &lt;&nbsp;bi &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n        ans = []\n        for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n            if not ans or ans[-2] < x: \n                if ans and x <= ans[-1]: ans.append(y)\n                else: ans.extend([y-1, y])\n        return len(ans)",
        "solution_js": "/**\n * @param {number[][]} intervals\n * @return {number}\n */\nvar intersectionSizeTwo = function(intervals) {\n    const sortedIntervals = intervals.sort(sortEndsThenStarts)\n    let currentTail = []\n    let answer = 0\n    sortedIntervals.forEach(interval => {\n        const start = interval[0]\n        const end = interval[1]\n        const startPoint = currentTail[0]\n        const lastPoint = currentTail[1]\n        \n        if (!currentTail.length || lastPoint < start){\n            currentTail = [end -1, end]\n            answer += 2\n        } else if ( startPoint < start){\n            currentTail = [currentTail[1], end]\n            answer += 1\n        }\n\n    })\n    return answer\n\n};\n\nfunction sortEndsThenStarts(intervalA, intervalB){\n    return intervalA[1] < intervalB[1] ? -1 : 1\n}",
        "solution_java": "//Time Complexity O(Nlog(N)) - N is the number of intervals\n//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed\nclass Solution {\n    public int intersectionSizeTwo(int[][] intervals) {\n        //corner case: can intervals be null or empty? No\n\n        //First, sort the intervals by end, then by reverse order start\n        Arrays.sort(intervals, new Comparator<int[]>() {\n            @Override\n            public int compare(int[] a, int[] b) {\n                if (a[1] == b[1]) {\n                    return b[0] - a[0];\n                }\n                return a[1] - b[1];\n            }\n        });\n\n        //Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request\n        List<Integer> list = new ArrayList<>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition\n\n        //add last two nums within the range\n        list.add(intervals[0][1] - 1);\n        list.add(intervals[0][1]);\n\n        for (int i = 1; i < intervals.length; i++) {\n            int lastOne = list.get(list.size() - 1);\n            int lastTwo = list.get(list.size() - 2);\n\n            int[] interval = intervals[i];\n            int start = interval[0];\n            int end = interval[1];\n\n            //if overlaps at least 2\n            if (lastOne >= start && lastTwo >= start) {\n                continue;\n            } else if (lastOne >= start) { //if overlaps 1\n                list.add(end);\n            } else { //if not overlapping\n                list.add(end - 1);\n                list.add(end);\n            }\n        }\n\n        return list.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // sort wrt. end value\n\n    static bool compare(vector<int>& a, vector<int>& b)\n    {\n        if(a[1] == b[1])\n            return a[0] < b[0];\n        else\n            return a[1] < b[1];\n    }\n\n    int intersectionSizeTwo(vector<vector<int>>& intervals) {\n\n        int n = intervals.size();\n\n        // sort the array\n\n        sort(intervals.begin(), intervals.end(), compare);\n\n        vector<int> res;\n\n        res.push_back(intervals[0][1] - 1);\n\n        res.push_back(intervals[0][1]);\n\n        for(int i = 1; i < n; i++)\n        {\n            int start = intervals[i][0];\n\n            int end = intervals[i][1];\n\n            if(start > res.back())\n            {\n                res.push_back(end - 1);\n\n                res.push_back(end);\n            }\n            else if(start == res.back())\n            {\n                res.push_back(end);\n            }\n            else if(start > res[res.size() - 2])\n            {\n                res.push_back(end);\n            }\n        }\n\n        return res.size();\n    }\n};"
    },
    {
        "title": "Binary Tree Tilt",
        "algo_input": "Given the root of a binary tree, return the sum of every tree node's tilt.\n\nThe tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3]\nOutput: 1\nExplanation: \nTilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1\n\n\nExample 2:\n\nInput: root = [4,2,9,3,5,null,7]\nOutput: 15\nExplanation: \nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\n\n\nExample 3:\n\nInput: root = [21,7,14,1,1,2,2,3,3]\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n    def findTilt(self, root: Optional[TreeNode]) -> int:\n        res = [0]\n        def tilt_helper(root,res):\n            if not root:\n                return 0\n\n            left = tilt_helper(root.left,res)\n            right = tilt_helper(root.right,res)\n\n            res[0] += abs(left-right)\n\n            return left + right + root.val\n\n        tilt_helper(root,res)\n        return res[0]",
        "solution_js": "var findTilt = function(root) {\n    function helper(node, acc) {\n        if (node === null) {\n            return 0;\n        }\n\n        const left = helper(node.left, acc);\n        const right = helper(node.right, acc);\n\n        acc.sum += Math.abs(left - right);\n\n        return left + node.val + right;\n    }\n\n    let acc = { sum: 0 };\n    helper(root, acc);\n\n    return acc.sum;\n};",
        "solution_java": "class Solution {\n    int max = 0;\n    public int findTilt(TreeNode root) {\n        loop(root);\n        return max;\n    }\n    public int loop(TreeNode root){\n        if(root==null) return 0;\n        int left = loop(root.left);\n        int right = loop(root.right);\n        max+= Math.abs(left-right);\n        return root.val+left+right;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    \n    /*  We will take help of recursion\n        Each function call will return the sum of subtree with root as current root\n        and the tilt sum will be updated in the variable passed as reference\n    */\n    \n    int getTiltSum(TreeNode* root, int &tiltSum){\n        if(root == NULL){\n            return 0;\n        }\n        if(root->left == NULL and root->right == NULL){     // If we have a leaf\n            tiltSum+=0;         // Add nothing to tilt sum\n            return root->val;   // return its value as sum\n        }\n        \n        int leftSubTreeSum = getTiltSum(root->left, tiltSum);   // Sum of all nodes in left\n        int rightSubTreeSum = getTiltSum(root->right, tiltSum); // and right subtrees\n        \n        tiltSum += abs(leftSubTreeSum - rightSubTreeSum);   // Update the tilt sum\n        \n        // return the sum of left Subtree + right subtree + current node as the sum of the \n        return (root->val + leftSubTreeSum + rightSubTreeSum);  // subtree with root as current node.\n        \n    }\n    \n    \n    int findTilt(TreeNode* root) {\n        // variable to be passed as refrence and store the result\n        int tiltSum = 0;\n        \n        getTiltSum(root, tiltSum);\n        \n        return tiltSum;\n    }\n};"
    },
    {
        "title": "Swim in Rising Water",
        "algo_input": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).\n\nThe rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.\n\nReturn the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,2],[1,3]]\nOutput: 3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.\n\n\nExample 2:\n\nInput: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\nOutput: 16\nExplanation: The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 &lt;= n &lt;= 50\n\t0 &lt;= grid[i][j] &lt;&nbsp;n2\n\tEach value grid[i][j] is unique.\n\n",
        "solution_py": "class DSU(object):\n    def __init__(self, N):\n        self.par = list(range(N))\n        self.rnk = [0] * N\n\n    def find(self, x):\n        if self.par[x] != x:\n            self.par[x] = self.find(self.par[x])\n        return self.par[x]\n\n    def union(self, x, y):\n        xr, yr = self.find(x), self.find(y)\n        if xr == yr:\n            return False\n        elif self.rnk[xr] < self.rnk[yr]:\n            self.par[xr] = yr\n        elif self.rnk[xr] > self.rnk[yr]:\n            self.par[yr] = xr\n        else:\n            self.par[yr] = xr\n            self.rnk[xr] += 1\n        return True\n\nclass Solution:\n    def swimInWater(self, grid):\n        d, N = {}, len(grid)\n        for i,j in product(range(N), range(N)):\n            d[grid[i][j]] = (i, j)\n        \n        dsu = DSU(N*N)\n        grid = [[0] * N for _ in range(N)] \n        neib_list = [[0,1],[0,-1],[1,0],[-1,0]]\n        \n        for i in range(N*N):\n            x, y = d[i]\n            grid[x][y] = 1\n            for dx, dy in neib_list:\n                if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1:\n                    dsu.union((x+dx)*N + y + dy, x*N + y)\n                    \n            if dsu.find(0) == dsu.find(N*N-1): return i",
        "solution_js": "const moves = [[1,0],[0,1],[-1,0],[0,-1]]\n\nvar swimInWater = function(grid) {\n    let pq = new MinPriorityQueue(),\n        N = grid.length - 1, ans = grid[0][0], i = 0, j = 0\n    while (i < N || j < N) {\n        for (let [a,b] of moves) {\n            let ia = i + a, jb = j + b\n            if (ia < 0 || ia > N || jb < 0 || jb > N || grid[ia][jb] > 2500) continue\n            pq.enqueue((grid[ia][jb] << 12) + (ia << 6) + jb)\n            grid[ia][jb] = 3000\n        }\n        let next = pq.dequeue().element\n        ans = Math.max(ans, next >> 12)\n        i = (next >> 6) & ((1 << 6) - 1)\n        j = next & ((1 << 6) - 1)\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public int swimInWater(int[][] grid) {\n        int len = grid.length;\n        Map<Integer, int[]> reverseMap = new HashMap<>();\n        for (int i = 0; i < len; i++) {\n            for (int j = 0; j < len; j++) {\n                reverseMap.put(grid[i][j], new int[] { i, j });\n            }\n        }\n        \n        int left = grid[0][0]; // answer cannot be less than value of starting position\n        int right = len * len - 1;\n        \n        int ans = right;\n        \n        while (left <= right) {\n            int mid = left + (right - left) / 2;\n            if (canSwim(grid, reverseMap, mid, len)) {\n                ans = mid;\n                right = mid - 1;\n            } else {\n                left = mid + 1;\n            }\n        }\n        \n        return ans;\n    }\n    \n    boolean canSwim(int[][] grid, Map<Integer, int[]> reverseIndex, int ans, int len) {\n        int[] x_diff = { 1, -1, 0, 0 };\n        int[] y_diff = { 0, 0, 1, -1 };\n        \n        // BFS\n        Queue<int[]> container = new LinkedList<>();\n        container.add(new int[] { 0, 0 });\n        \n        boolean[][] visited = new boolean[grid.length][grid[0].length];\n        visited[0][0] = true;\n            \n        while (!container.isEmpty()) {\n            int[] curr = container.poll();\n            int currVal = grid[curr[0]][curr[1]];\n            for (int i = 0; i < 4; i++) {\n                int newX = curr[0] + x_diff[i];\n                int newY = curr[1] + y_diff[i];\n                if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) {\n                    if (newX == grid.length-1 && newY == grid[0].length-1) {\n                        return true;\n                    }\n                    visited[newX][newY] = true;\n                    container.add(new int[] { newX, newY });\n                }\n            }   \n        }\n        \n        return false;\n    }\n    \n    boolean isValidCell(int[][] grid, int x, int y, int ans) {\n\t    // check boundary and if grid elevation is greater than evaluated answer\n        return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};\n    bool valid(int x,int y,int n)\n    {\n        return ((x>=0&&x<n)&&(y>=0&&y<n));\n    }\n    int swimInWater(vector<vector<int>>& grid) {\n        int n=grid.size();\n        int time[n][n];\n        bool vis[n][n];\n        for(int i=0;i<n;++i)\n        {\n            for(int j=0;j<n;++j)\n            {\n                time[i][j]=1e9;\n                vis[i][j]=false;\n            }\n        }\n        time[0][0]=grid[0][0];\n        priority_queue<tuple<int,int,int>> q;\n        q.push({-time[0][0],0,0});\n        while(!q.empty())\n        {\n            tuple<int,int,int> node=q.top();\n            q.pop();\n            int x=get<1>(node),y=get<2>(node);\n            if(vis[x][y])continue;\n            vis[x][y]=true;\n            for(int i=0;i<4;++i)\n            {\n                int xc=x+dir[i][0],yc=y+dir[i][1];\n                if(!valid(xc,yc,n))continue;\n                if(time[x][y]<grid[xc][yc])\n                {\n                    time[xc][yc]=grid[xc][yc];\n                    q.push({-time[xc][yc],xc,yc});\n                }\n                else\n                {\n                    if(time[xc][yc]>time[x][y])\n                    {\n                        time[xc][yc]=time[x][y];\n                        q.push({-time[xc][yc],xc,yc});\n                    }\n                }\n            }\n        }\n        return time[n-1][n-1];\n    }\n};\n// Time: O(N*N+N*NLOG(N*N))\n// Space: O(N*N)"
    },
    {
        "title": "Unique Substrings in Wraparound String",
        "algo_input": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\", so s will look like this:\n\n\n\t\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\".\n\n\nGiven a string p, return the number of unique non-empty substrings of p are present in s.\n\n&nbsp;\nExample 1:\n\nInput: p = \"a\"\nOutput: 1\nExplanation: Only the substring \"a\" of p is in s.\n\n\nExample 2:\n\nInput: p = \"cac\"\nOutput: 2\nExplanation: There are two substrings (\"a\", \"c\") of p in s.\n\n\nExample 3:\n\nInput: p = \"zab\"\nOutput: 6\nExplanation: There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= p.length &lt;= 105\n\tp consists of lowercase English letters.\n\n",
        "solution_py": "def get_next(char):\n    x = ord(char)-ord('a')\n    x = (x+1)%26\n    return chr(ord('a') + x)\nclass Solution:\n    def findSubstringInWraproundString(self, p: str) -> int:\n        i = 0\n        n = len(p)\n        map_ = collections.defaultdict(int)\n        while i<n:\n            start = i\n            prev_val = p[i]\n            while i+1<n and get_next(prev_val) == p[i+1]:\n                prev_val = p[i+1]\n                i+=1\n            while start <= i:\n                curr_val = i-start+1\n                map_[p[start]] = max(map_[p[start]], curr_val)\n                start += 1\n            i+=1\n        return sum(map_.values())",
        "solution_js": "var findSubstringInWraproundString = function(p) {\n\tconst dp = Array(26).fill(0);\n\tconst origin = 'a'.charCodeAt(0);\n\tlet count = 0;\n\n\tfor (let index = 0; index < p.length; index++) {\n\t\tconst code = p.charCodeAt(index);\n\t\tconst preCode = p.charCodeAt(index - 1);\n\t\tconst pos = code - origin;\n\n\t\tcount = code - preCode === 1 || preCode - code === 25\n\t\t\t? count + 1\n\t\t\t: 1;\n\n\t\tdp[pos] = Math.max(count, dp[pos]);\n\t}\n\n\treturn dp.reduce((total, count) => total + count);\n};",
        "solution_java": "// One Pass Counting Solution\n// 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring.\n// 2. counts to track the longest continuos subtring starting with current character.\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n    public int findSubstringInWraproundString(String p) {\n        final int N = p.length();\n        int res = 0, len = 1;\n        int[] counts = new int[26];\n        for (int i = 0; i < N; i++) {\n            char ch = p.charAt(i);\n            if (i > 0 && (ch - p.charAt(i-1) == 1 || ch - p.charAt(i-1) == -25)) {\n                len++;\n            } else {\n                len = 1;\n            }\n            int idx = ch - 'a';\n            counts[idx] = Math.max(counts[idx], len);\n        }\n        for (int count : counts) {\n            res += count;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int findSubstringInWraproundString(string p) {\n        unordered_map<char, int> mp;\n\n        // if the characters are not contiguous and also check whether after 'z' I am getting 'a'. If so, reset the streak to 1\n        // else streak++\n\n        int streak = 0;\n\n        for (int i = 0; i < p.size(); i++) {\n\n            // contiguous\n            if (i and (p[i] - p[i - 1] == 1)) streak++;\n\n            // z...a case\n            else if (i and (p[i] == 'a' and p[i - 1] == 'z')) streak++;\n\n            else streak = 1;\n\n            mp[p[i]] = max(mp[p[i]], streak);\n        }\n\n        // why sum? cuz there might be multiple substrings when the streak's broken for one\n\n        int ans = 0;\n        for (auto x : mp) {\n            ans += x.second;\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "LRU Cache",
        "algo_input": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.\n\nImplement the LRUCache class:\n\n\n\tLRUCache(int capacity) Initialize the LRU cache with positive size capacity.\n\tint get(int key) Return the value of the key if the key exists, otherwise return -1.\n\tvoid put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.\n\n\nThe functions get and put must each run in O(1) average time complexity.\n\n&nbsp;\nExample 1:\n\nInput\n[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\nExplanation\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1);    // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2);    // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1);    // return -1 (not found)\nlRUCache.get(3);    // return 3\nlRUCache.get(4);    // return 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= capacity &lt;= 3000\n\t0 &lt;= key &lt;= 104\n\t0 &lt;= value &lt;= 105\n\tAt most 2 * 105 calls will be made to get and put.\n\n",
        "solution_py": "class LRUCache {\n    int N;\n    list<int> pages;\n    unordered_map<int, pair<int, list<int>::iterator>> cache;\npublic:\n    LRUCache(int capacity) : N(capacity) {\n        \n    }\n    \n    int get(int key) {\n        if (cache.find(key) != cache.end()) {\n            pages.erase(cache[key].second);\n            pages.push_front(key);\n            cache[key].second = pages.begin();\n            return cache[key].first;\n        }\n        \n        return -1;\n    }\n    \n    void put(int key, int value) {\n        if (cache.find(key) != cache.end()) {\n            pages.erase(cache[key].second);\n        } else {\n            if (pages.size() == N) {\n                int lru = pages.back();\n                cache.erase(lru);\n                pages.pop_back();\n            }\n        }\n        \n        pages.push_front(key);\n        cache[key] = {value, pages.begin()};\n    }\n};",
        "solution_js": "/**\n * @param {number} capacity\n */\nvar LRUCache = function(capacity) {\n    this.capacity = capacity;\n    this.cache = new Map();\n};\n\n/** \n * @param {number} key\n * @return {number}\n */\nLRUCache.prototype.get = function(key) {\n    if(!this.cache.has(key)){\n        return -1\n    }\n    \n    let val = this.cache.get(key);\n    this.cache.delete(key);\n    this.cache.set(key, val)\n    return val\n};\n\n/** \n * @param {number} key \n * @param {number} value\n * @return {void}\n */\nLRUCache.prototype.put = function(key, value) {\n    if(this.cache.has(key)){\n        this.cache.delete(key);\n    }else{\n        if(this.cache.size >= this.capacity){\n            let [lastElm] = this.cache.keys()\n            this.cache.delete(lastElm)\n        }\n    }\n    this.cache.set(key, value)\n    \n};\n\n/** \n * Your LRUCache object will be instantiated and called as such:\n * var obj = new LRUCache(capacity)\n * var param_1 = obj.get(key)\n * obj.put(key,value)\n */",
        "solution_java": "class LRUCache {\n    // Declare Node class for Doubly Linked List \n    class Node{\n        int key,value;// to store key and value \n        Node next,prev; // Next and Previous Pointers\n        Node(int k, int v){\n            key=k;\n            value=v;\n        }\n    }\n    Node head=new Node(-1,-1); // Default values \n    Node tail=new Node(-1,-1);\n    Map<Integer,Node>mp;  // to store key and Node\n    int cap;\n    public LRUCache(int capacity) {\n        // initializing in constructor\n        cap=capacity;\n        head.next=tail;\n        tail.prev=head;\n        mp=new HashMap<Integer,Node>();\n    }\n    \n    public int get(int key) {\n        // if map contains the specific key \n        if(mp.containsKey(key)){\n            Node existing=mp.get(key);\n            del(existing);\n            ins(existing);// reinserting to keep key after the head pointer and to update LRU list\n            return existing.value;\n        }\n        //otherwise\n        return -1;\n    }\n    \n    public void put(int key, int value) {\n        // if map contains the key\n        if(mp.containsKey(key)){\n            Node existing=mp.get(key);\n            // remove from the map and delete from the LRU list\n            mp.remove(key);\n            del(existing);\n        }\n        // if map size is equal to spcified capacity of the LRU list\n        if(mp.size()==cap){\n            // remove from the map and delete from the LRU list\n            mp.remove(tail.prev.key);\n            del(tail.prev);\n        }\n        Node newNode = new Node(key,value);\n        ins(newNode); \n        mp.put(key,head.next); \n    }\n    public void ins(Node newNode){\n        //Insert always after the head of the linkedList\n        Node temp=head.next;\n        head.next=newNode;\n        newNode.prev=head;\n        newNode.next=temp;\n        temp.prev=newNode;\n    }\n    public void del(Node newNode){\n        //Remove the specified node using previous and next pointers\n        Node pr=newNode.prev;\n        Node nx=newNode.next;\n        pr.next=nx;\n        nx.prev=pr;\n        \n    }\n}",
        "solution_c": "class LRUCache {\npublic:\n    int mx;\n    class node{\n        public:\n        node *prev,*next;\n        int key,val;\n        node(int k,int v){\n            key=k,val=v;\n        }\n    };\n    unordered_map<int,node*> mp;\n        node *head=new node(-1,-1);\n        node *tail=new node(-1,-1);\n    LRUCache(int capacity) {\n        mx=capacity;\n        mp.reserve(1024);\n        mp.max_load_factor(0.25);\n\n        head->next=tail;tail->prev=head;\n    }\n    \n    void addnode(node *temp){\n        node *temp1=head->next;\n        head->next=temp;temp->prev=head;\n        temp->next=temp1;temp1->prev=temp;\n    }\n    \n    void deletenode(node *temp){\n        node *temp1=temp->prev;\n        node *temp2=temp->next;\n        temp1->next=temp2;\n        temp2->prev=temp1;\n    }\n    \n    int get(int key) {\n        if(mp.find(key)!=mp.end()){\n            node *temp=mp[key];\n            int res=temp->val;\n            mp.erase(key);\n            deletenode(temp);\n            addnode(temp);\n            mp[key]=head->next;\n            return res;\n        }\n        return -1;\n    }\n    \n    void put(int key, int value) {\n        if(mp.find(key)!=mp.end()){\n            node *temp=mp[key];\n            mp.erase(key);\n            deletenode(temp);\n        }\n        if(mp.size()==mx){\n            mp.erase(tail->prev->key);\n            deletenode(tail->prev);\n        }\n        addnode(new node(key,value));\n        mp[key]=head->next;\n    }\n};"
    },
    {
        "title": "Largest Time for Given Digits",
        "algo_input": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.\n\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\n\nReturn the latest 24-hour time in \"HH:MM\" format. If no valid time can be made, return an empty string.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,4]\nOutput: \"23:41\"\nExplanation: The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.\n\n\nExample 2:\n\nInput: arr = [5,5,5,5]\nOutput: \"\"\nExplanation: There are no valid 24-hour times as \"55:55\" is not valid.\n\n\n&nbsp;\nConstraints:\n\n\n\tarr.length == 4\n\t0 &lt;= arr[i] &lt;= 9\n\n",
        "solution_py": "class Solution:\n    def largestTimeFromDigits(self, arr: List[int]) -> str:\n        res = \"\"\n        digit_freq = collections.Counter(arr)\n        # first digit\n        \n        \n        if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2:\n            res += \"2\"\n            arr.remove(2)\n        else:\n            for digit in [1,0]:\n                if digit in arr:\n                    res += str(digit)\n                    arr.remove(digit)\n                    break\n        # can't make 24-hour time\n        if len(res) == 0:\n            return \"\"\n        \n        # second digit 0-3\n        if res == \"2\":\n            for digit in [3,2,1,0]:\n                if digit in arr:\n                    res += str(digit)\n                    arr.remove(digit)\n                    break\n            # no 0-3 left in arr\n            if len(res) == 1:\n                return \"\"\n        # second digit 0-9\n        else:\n            for digit in range(9,-1,-1):\n                if digit in arr:\n                    res += str(digit)\n                    arr.remove(digit)\n                    break\n        \n        res += \":\"\n        \n        for digit in range(5, -1, -1):\n            if digit in arr:\n                res += str(digit)\n                arr.remove(digit)\n                break\n            \n        if len(res) == 3:\n            return \"\"\n        \n        for digit in range(9,-1,-1):\n            if digit in arr:\n                res += str(digit)\n                return res\n                ",
        "solution_js": "var largestTimeFromDigits = function(arr) {\n    let max=-1;\n    for(let A=0; A<4; A++){\n        for(let B=0; B<4; B++){\n\t\t\tif(B==A){continue};\n            for(let C=0; C<4; C++){\n\t\t\t\tif(C==A||C==B||arr[C]>=6){continue};\n                for(let D=0; D<4; D++){\n\t\t\t\t\tif(D==A||D==B||D==C){continue};\n                    let time=arr[A]*1000+arr[B]*100+arr[C]*10+arr[D];\n                    if(time<2400){max=Math.max(max, time));\n                }\n            }\n        }\n    }\n\t// Case1: max<0, which means NOTHING VALID -> return \"\"\n\t// Case2: max isn't 4 digits. i.e.[0,0,0,0] -> padStart to make \"0000\"\n    let output=max.toString().padStart(4,0);\n    return max<0? \"\": output.substr(0,2)+\":\"+output.substr(2);\n};",
        "solution_java": "class Solution {\n    public String largestTimeFromDigits(int[] arr) {\n        int[] count = new int[10];\n        for (int num: arr) {\n            count[num]++;\n        }\n        StringBuilder sb = backTrack(count, new StringBuilder());\n        if (sb.length() == 4) sb.insert(2, ':');\n        return sb.toString();\n        \n    }\n    private StringBuilder backTrack(int[] count, StringBuilder sb) {\n        int size = sb.length();\n        int start = 0;\n        if (size == 0) {\n            start = 2;\n        }\n        if (size == 1) {\n            start = sb.charAt(0) == '2' ? 3 : 9;\n        }\n        if (size == 2) {\n            start = 5;\n        }\n        if (size == 3) {\n            start = 9;\n        }\n        for (int i = start; i >= 0; i--) {\n            if (count[i] == 0) continue;\n            count[i]--;\n            sb.append(i);\n            backTrack(count, sb);\n            if (sb.length() == 4) {\n                return sb;\n            }\n            else {\n                count[Character.getNumericValue(sb.charAt(sb.length() - 1))]++;\n                sb.deleteCharAt(sb.length() - 1);\n            }\n        }\n        return sb;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestTimeFromDigits(vector<int>& arr) {\n        sort(arr.rbegin(), arr.rend());\n        used.resize(4);\n        \n        string ret = \"\";\n        if(!dfs(arr,0,0)) return ret;\n        else\n        {\n            for(int i=0;i<2;i++)\n                ret.push_back(ans[i] + '0');\n            \n            ret.push_back(':');\n            \n            for(int i=2;i<4;i++)\n                ret.push_back(ans[i] + '0');\n        }\n        return ret;\n    }\n    \nprivate:\n    vector<int> min = {600, 60, 10, 1};\n    vector<int> ans;\n    vector<int> used;\n    bool dfs(const vector<int>& arr, int totalhour,int totalmin)\n    {\n        if(totalhour >= 24 * 60) return false;\n        if(totalmin >= 60) return false;\n        if(ans.size() == 4) return true;\n        \n        for(int i=0;i<4;i++)\n        {\n            if(used[i]) continue;\n            used[i] = 1;\n            \n            int pos = ans.size();\n            if(pos<2) totalhour += arr[i] * min[pos];\n            else totalmin += arr[i] * min[pos];\n            \n            ans.push_back(arr[i]);\n            \n            if(dfs(arr,totalhour,totalmin)) return true;\n            \n            if(pos<2) totalhour -= arr[i] * min[pos];\n            else totalmin -= arr[i] * min[pos];\n            \n            ans.pop_back();\n            used[i] = 0;\n        }\n        \n        return false;\n    }\n};"
    },
    {
        "title": "Group Anagrams",
        "algo_input": "Given an array of strings strs, group the anagrams together. You can return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\n&nbsp;\nExample 1:\nInput: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nOutput: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\nExample 2:\nInput: strs = [\"\"]\nOutput: [[\"\"]]\nExample 3:\nInput: strs = [\"a\"]\nOutput: [[\"a\"]]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= strs.length &lt;= 104\n\t0 &lt;= strs[i].length &lt;= 100\n\tstrs[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n        strs_table = {}\n\n        for string in strs:\n            sorted_string = ''.join(sorted(string))\n\n            if sorted_string not in strs_table:\n                strs_table[sorted_string] = []\n\n            strs_table[sorted_string].append(string)\n\n        return list(strs_table.values())",
        "solution_js": "var groupAnagrams = function(strs) {\n    let totalResults = [];\n    let grouped = new Map();\n\n    for (let i=0; i < strs.length; i++) {\n        let results = [];\n        let res = strs[i];\n\n        let sortedStr = strs[i].split('').sort().join('');\n        let value = grouped.get(sortedStr);\n\n        if (value !== undefined) {\n            grouped.set(sortedStr, [...value, strs[i]]);\n        } else {\n            grouped.set(sortedStr, [strs[i]]);\n        }\n    }\n\n    for (let [key, value] of grouped) {\n        totalResults.push(grouped.get(key));\n    }\n\n    return totalResults;\n};",
        "solution_java": "class Solution {\n    public List<List<String>> groupAnagrams(String[] strs) {\n        HashMap<String,ArrayList<String>> hm=new HashMap<>();\n        for(String s : strs)\n        {\n            char ch[]=s.toCharArray();\n            Arrays.sort(ch);\n            StringBuilder sb=new StringBuilder(\"\");\n            for(char c: ch)\n            {\n                sb.append(c);\n            }\n            String str=sb.toString();\n            if(hm.containsKey(str))\n            {\n              ArrayList<String> temp=hm.get(str);\n              temp.add(s);\n              hm.put(str,temp);\n            }\n            else\n            {\n                ArrayList<String> temp=new ArrayList<>();\n                temp.add(s);\n                hm.put(str,temp);\n            }\n        }\n        System.out.println(hm);\n        List<List<String>> res=new ArrayList<>();\n        for(ArrayList<String> arr : hm.values())\n        {\n            res.add(arr);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<string>> groupAnagrams(vector<string>& strs) {\n\n        map<string,vector<int>> mp;\n        for(int i=0;i<strs.size();i++)\n        {\n            string t=strs[i];\n            sort(t.begin(),t.end());\n            mp[t].push_back(i);\n        }\n        vector<vector<string>> ans;\n        for(auto it:mp)\n        {\n            vector<string> flag;\n            for(auto each:it.second)\n            {\n                flag.push_back(strs[each]);\n            }\n            ans.push_back(flag);\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Valid Parentheses",
        "algo_input": "Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.\n\n&nbsp;\nExample 1:\n\nInput: s = \"(()\"\nOutput: 2\nExplanation: The longest valid parentheses substring is \"()\".\n\n\nExample 2:\n\nInput: s = \")()())\"\nOutput: 4\nExplanation: The longest valid parentheses substring is \"()()\".\n\n\nExample 3:\n\nInput: s = \"\"\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 3 * 104\n\ts[i] is '(', or ')'.\n\n",
        "solution_py": "class Solution:\n    def longestValidParentheses(self, s: str) -> int:\n\n        maxi = 0\n        stack = [-1]\n\n        for i in range(len(s)) :\n            if s[i] == \"(\" : stack.append(i)\n            else :\n                stack.pop()\n                if len(stack) == 0 : stack.append(i)\n                else : maxi = max(maxi, i - stack[-1])\n\n        return maxi",
        "solution_js": "var longestValidParentheses = function(s) {\n    let indexStack=[-1]\n    let characterStack=[];\n    let maxLength=0;\n    for(let i=0;i<s.length;i++){\n        if(s[i]=='('){\n            indexStack.push(i);\n            characterStack.push(s[i]);\n        }else{\n            if(characterStack[characterStack.length-1]=='('){\n                indexStack.pop();\n                characterStack.pop();\n                if(maxLength<i-indexStack[indexStack.length-1]){\n                    maxLength=i-indexStack[indexStack.length-1];\n                }\n            }else{\n                indexStack.push(i);\n            }\n        }\n    }\n    return maxLength;\n};",
        "solution_java": "class Solution {\n    public int longestValidParentheses(String s) {\n        int i=0;\n        int len=0;\n        while(i<s.length()){\n            int j=i;\n            int open=0;\n            int closed=0;\n            while(j<s.length()){\n                char ch = s.charAt(j);\n                if(ch=='(') open++;\n                if(ch==')') closed++;\n                if(closed>open) break;\n                if(open==closed) len=Math.max(len,j-i+1);\n\n                j++;\n            }\n            i++;\n        }\n        return len;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int n = s.length(), i = 0, ans = 0, k = 0;\n        for(int j = 0; j < n; j++) {\n            if(s[j] == '(') k++;\n            else if(s[j] == ')') {\n                k--;\n                if(k == 0)\n                    ans = max(ans, j - i + 1);\n            }\n            if(k < 0) {\n                k = 0;\n                i = j + 1;\n            }\n        }\n        k = 0, i = n - 1;\n        for(int j = n - 1; j >= 0; j--) {\n            if(s[j] == ')') {\n                k++;\n            }\n            else if(s[j] == '(') {\n                k--;\n                if(k == 0)\n                    ans = max(ans, i - j + 1);\n            }\n            if(k < 0) {\n                k = 0;\n                i = j - 1;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Word Search II",
        "algo_input": "Given an m x n board&nbsp;of characters and a list of strings words, return all words on the board.\n\nEach word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\nOutput: [\"eat\",\"oath\"]\n\n\nExample 2:\n\nInput: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m, n &lt;= 12\n\tboard[i][j] is a lowercase English letter.\n\t1 &lt;= words.length &lt;= 3 * 104\n\t1 &lt;= words[i].length &lt;= 10\n\twords[i] consists of lowercase English letters.\n\tAll the strings of words are unique.\n\n",
        "solution_py": "class Solution:\n    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n        solution = set()\n        trie = self.make_trie(words)\n        visited = set()\n        for i in range(len(board)):\n            for j in range(len(board[0])):\n                self.dfs(i,j,board,trie,visited,\"\",solution)\n        return solution\n    \n    def dfs(self,i,j,board,trie,visited,word,solution):\n        if \"*\" in trie:\n            if len(trie.keys()) == 0:\n                return\n            else:\n                solution.add(word)\n                del trie[\"*\"]\n        if (i,j) in visited:\n            return\n        if (i < 0 or i == len(board) or j < 0 or j == len(board[0])):\n            return\n        if board[i][j] not in trie:\n            return\n        if len(trie[board[i][j]]) == 0:\n            del trie[board[i][j]]\n            return\n        visited.add((i,j))\n        neighbours = [(i,j-1),(i-1,j),(i,j+1),(i+1,j)]\n        for n_x,n_y in neighbours:\n            self.dfs(n_x,n_y,board,trie[board[i][j]],visited,word+board[i][j],solution)    \n        visited.remove((i,j))\n        \n    def make_trie(self,words):\n        trie = {}\n        for word in words:\n            current = trie\n            for char in word:\n                if char not in current:\n                    current[char] = {}\n                current = current[char]\n            current[\"*\"] = \"*\"\n        return trie",
        "solution_js": "const buildTrie = (words) => {\n    const trie = {};\n    const addToTrie = (word, index = 0, node = trie) => {\n        const char = word[index];\n        if(!node[char]) {\n            node[char] = {};\n        }\n\n        if(index === word.length - 1) {\n            node[char].word = word;\n            return word;\n        }\n\n        return addToTrie(word, index + 1, node[char]);\n    };\n\n    words.map((word) => addToTrie(word));\n    return trie;\n};\n\nconst dfs = (i, j, board, node, wordsFound = []) => {\n    if(i < 0 || i >= board.length) return wordsFound;\n    if(j < 0 || j >= board[board.length - 1].length) return wordsFound;\n\n    const char = board[i][j];\n    if(char === '#') return wordsFound;\n\n    if(node[char]) {\n        if(node[char].word) {\n            wordsFound.push(node[char].word);\n            node[char].word = null;\n        }\n\n        board[i][j] = '#';\n        dfs(i + 1, j, board, node[char], wordsFound);\n        dfs(i, j + 1, board, node[char], wordsFound);\n        dfs(i - 1, j, board, node[char], wordsFound);\n        dfs(i, j - 1, board, node[char], wordsFound);\n        board[i][j] = char;\n    }\n\n    return wordsFound;\n};\n\nvar findWords = function(board, words) {\n    const m = board.length;\n    const n = board[m - 1].length;\n    const trie = buildTrie(words);\n\n    let result = [];\n    for(let i = 0; i < m; i += 1) {\n        for(let j = 0; j < n; j += 1) {\n            result = result.concat(dfs(i, j, board, trie));\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    class TrieNode {\n        Map<Character, TrieNode> children = new HashMap();\n        boolean word = false;\n        public TrieNode() {}\n    }\n    \n    int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};\n    \n    public List<String> findWords(char[][] board, String[] words) {\n        Set<String> res = new HashSet<>();\n        TrieNode root = new TrieNode();\n        int m = board.length;\n        int n = board[0].length;\n        \n        for(String word : words){\n            char[] cArr = word.toCharArray();\n            TrieNode dummy = root;\n            \n            for(char c : cArr){\n                if(!dummy.children.containsKey(c)){\n                    dummy.children.put(c, new TrieNode());\n                }\n                dummy = dummy.children.get(c);\n            }\n            \n            dummy.word = true;\n        }\n        \n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                char nextChar = board[i][j];\n                boolean[][] visited = new boolean[m][n];\n                if(root.children.containsKey(nextChar)){\n                    res.addAll(dfs(board, root.children.get(nextChar), i, j, visited, \"\"+nextChar));\n                }\n            }\n        }\n        \n        return new ArrayList<>(res);\n    }\n    \n    Set<String> dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word){\n        Set<String> res = new HashSet<>();\n        \n        if(root.word){\n            res.add(word);\n            root.word = false;\n        }\n        \n        visited[i][j] = true;\n        \n        for(int[] dir : dirs){\n            int newI = i + dir[0];\n            int newJ = j + dir[1];\n            \n            if(newI>=0 && newI<board.length && newJ>=0 && newJ<board[0].length && !visited[newI][newJ]){\n                char nextChar = board[newI][newJ];\n                if(root.children.containsKey(nextChar)){\n                   \n                    res.addAll(dfs(board, root.children.get(nextChar), newI, newJ, visited, word+nextChar));\n                    \n                }\n            }\n        }\n        \n        visited[i][j] = false;\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> result;\n\n    struct Trie {\n        Trie *child[26];\n        bool isEndOfWord;\n        string str;\n\n        Trie(){\n            isEndOfWord = false;\n            str = \"\";\n            for(int i=0; i<26; i++)\n                child[i] = NULL;\n        }\n    };\n\n    Trie *root = new Trie();\n\n    void insert(string &word) {\n\n        Trie *curr = root;\n\n        for(int i=0; i<word.size(); i++) {\n            int index = word[i]-'a';\n\n            if(!curr->child[index])\n                curr->child[index] = new Trie();\n\n            curr = curr->child[index];\n        }\n\n        curr->isEndOfWord = true;\n        curr->str = word;\n    }\n\n    void trieSearchDFS(vector<vector<char>>& board, Trie *curr, int i, int j, int row, int col) {\n\n        if(i<0 || i>row || j<0 || j>col || board[i][j] == '@')\n            return;\n\n        //int index = board[i][j]-'a';\n        curr = curr->child[board[i][j]-'a'];\n\n        if(curr == NULL)\n            return;\n\n        if(curr->isEndOfWord){\n            result.push_back(curr->str);\n            curr->isEndOfWord = false;\n        }\n\n        char ch = board[i][j];\n        board[i][j] = '@';\n\n        if(i-1>=0)\n            trieSearchDFS(board,curr,i-1,j,row,col);\n        if(j+1<col)\n            trieSearchDFS(board,curr,i,j+1,row,col);\n        if(i+1<row)\n            trieSearchDFS(board,curr,i+1,j,row,col);\n        if(j-1>=0)\n            trieSearchDFS(board,curr,i,j-1,row,col);\n\n        board[i][j] = ch;\n\n    }\n\n    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {\n        int row = board.size();\n        int col = board[0].size();\n\n        for(int i=0; i<words.size(); i++)\n            insert(words[i]);\n\n        for(int i=0; i<row; i++){\n            for(int j=0; j<col; j++){\n                trieSearchDFS(board,root,i,j,row,col);\n            }\n        }\n       return result;\n    }\n};"
    },
    {
        "title": "Count Primes",
        "algo_input": "Given an integer n, return the number of prime numbers that are strictly less than n.\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n\n\nExample 2:\n\nInput: n = 0\nOutput: 0\n\n\nExample 3:\n\nInput: n = 1\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 5 * 106\n\n",
        "solution_py": "class Solution:\n    def countPrimes(self, n: int) -> int:\n        # Prerequisite:\n        # What is prime number. What are they just the starting. \n        \n        truth = [True]*n # making a list of lenght n. And keep all the values as True.\n        if n<2: # as 0 & 1 are not prime numbers. \n            return 0\n        truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.\n        \n        i=2 # As we know 0 & 1 are not prime.\n        while i*i<n: # why we are doing it as i*i here is bcz lets say 5*2 = 10 is divisble by 2 as well as 5 so if 10 is already removed why to traverse a value which is already travered once. so in case of n=5 - 5<5. CONCLUSION : i<sqrt(n)\n#why we are running the loop till n is bcz question says \" prime numbers that are strictly less than n\".\n            if truth[i] == True:\n                for j in range(i*i,n,i): # if we have mutiple of a number in the range of n, we have to remove them as they can be prime. i.e 2 is prime, but its multiple in n = 10 are 4,6,8 they cant be prime. So we will make them false(means not a prime).\n                    truth[j]=False\n            i += 1 # increasing our iterator.\n        return truth.count(True) # will count true value \n        ",
        "solution_js": "function makeSieve(n) {\n    let arr = new Array(n+1)\n    arr[0] = false;\n    arr[1] = false;\n    arr.fill(true,2,arr.length);\n\n    for( let i = 2; i*i<n; i++) {\n        if(arr[i] === true) {\n            for( let j = i*i ; j<=n ;j+=i){\n                arr[j] = false;\n            }\n        }\n    }\n\n    let count = 0;\n\n    for(let i = 0; i<n;i++) {\n        if(arr[i] == true) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvar countPrimes = function(n) {\n    let numberOfPrimes = makeSieve(n)\n    return numberOfPrimes;\n};",
        "solution_java": "class Solution {\n    public int countPrimes(int n) {\n      boolean check[]=new boolean[n];int count=0;\n        for(int i=2;i<n;i++){\n            if(check[i]==false){\n                count++;\n                for(int j=i;j<n;j+=i){\n                    check[j]=true;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPrimes(int n) {\n        if(n == 0 || n == 1) return 0;\n        vector<bool>prime(n,true);\n        for(int i = 2; i*i < n; i++){\n            if(prime[i]){\n                for(int j = i*i; j < n; j += i){\n                    prime[j] = false;\n                }\n            }\n        }\n        int cnt = 0;\n        for(int i = 2; i < n; i++){\n            if(prime[i]) cnt++;\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Decoded String at Index",
        "algo_input": "You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:\n\n\n\tIf the character read is a letter, that letter is written onto the tape.\n\tIf the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.\n\n\nGiven an integer k, return the kth letter (1-indexed) in the decoded string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leet2code3\", k = 10\nOutput: \"o\"\nExplanation: The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10th letter in the string is \"o\".\n\n\nExample 2:\n\nInput: s = \"ha22\", k = 5\nOutput: \"h\"\nExplanation: The decoded string is \"hahahaha\".\nThe 5th letter is \"h\".\n\n\nExample 3:\n\nInput: s = \"a2345678999999999999999\", k = 1\nOutput: \"a\"\nExplanation: The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1st letter is \"a\".\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 100\n\ts consists of lowercase English letters and digits 2 through 9.\n\ts starts with a letter.\n\t1 &lt;= k &lt;= 109\n\tIt is guaranteed that k is less than or equal to the length of the decoded string.\n\tThe decoded string is guaranteed to have less than 263 letters.\n\n",
        "solution_py": "class Solution:\n    def decodeAtIndex(self, S: str, K: int) -> str:\n        idx = {}\n        acclens = [0]\n        prevd = 1\n        j = 0\n        for i, c in enumerate(S + '1'):\n            if c.isalpha():\n                idx[acclens[-1] * prevd + j] = i\n                j += 1\n            else:\n                acclens.append(acclens[-1] * prevd + j)\n                prevd = int(c)\n                j = 0\n        k = K - 1\n        for al in reversed(acclens[1:]):\n            k %= al\n            if k in idx:\n                return S[idx[k]]\n        return None  # should never reach this",
        "solution_js": "var decodeAtIndex = function(s, k) {\n    let len=0;\n    let isDigit=false\n\n    for(let v of s){\n        if(v>='0'&&v<='9'){\n            len*=+v\n            isDigit=true\n        }else{\n            len++\n            if(len===k&&!isDigit){\n                return s[k-1]\n            }\n        }\n    }\n\n    for(let i=s.length-1;i>=0;i--){\n        const v=s[i]\n        if(v>='0'&&v<='9'){\n            len=Math.ceil(len/+v) // Math.floor() wont work because we endup leaving few strings\n            k%=len\n        }else{\n            if(k===0||k===len){\n                    return v\n               }\n            len--\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public String decodeAtIndex(String s, int k) {\n        long sz = 0;\n        for (char ch : s.toCharArray()){ // total length\n            sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;\n        }\n        --k; // make it 0 index based.\n        for (int i = s.length() - 1; true; i--){\n            if (Character.isLetter(s.charAt(i)) && --sz == k){ // found!\n                return \"\"+s.charAt(i);\n            }else if(Character.isDigit(s.charAt(i))){\n                sz /= (s.charAt(i) - '0');\n                k %= sz; // we are at the end of a multplied string, we can mod k with sz.\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string decodeAtIndex(string s, int k) {\n        k--;\n        struct op { string s; size_t mult; size_t total; };\n        vector<op> v;\n        size_t total = 0;\n        for (auto c : s) {\n            if (isalpha(c)) {\n                if (v.empty() || v.back().mult > 1)\n                    v.push_back({\"\", 1, total});\n                v.back().s += c;\n                v.back().total = ++total;\n            } else {\n                size_t m = c-'0';\n                v.back().mult *= m;\n                v.back().total = total *= m;\n            }\n            if (total > k) break;\n        }\n        while (!v.empty()) {\n            auto [s, mult, total] = v.back();\n            v.pop_back();\n            size_t part = total / mult;\n            k %= part;\n            if (size_t i = k-part+s.size(); i < s.size())\n                return {s[i]};\n        }\n        return \"#\";\n    }\n};"
    },
    {
        "title": "Compare Strings by Frequency of the Smallest Character",
        "algo_input": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.\n\nYou are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) &lt; f(W) for each W in words.\n\nReturn an integer array answer, where each answer[i] is the answer to the ith query.\n\n&nbsp;\nExample 1:\n\nInput: queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput: [1]\nExplanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") &lt; f(\"zaaaz\").\n\n\nExample 2:\n\nInput: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: [1,2]\nExplanation: On the first query only f(\"bbb\") &lt; f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both &gt; f(\"cc\").\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= queries.length &lt;= 2000\n\t1 &lt;= words.length &lt;= 2000\n\t1 &lt;= queries[i].length, words[i].length &lt;= 10\n\tqueries[i][j], words[i][j] consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n        def _f(s):\n            d = Counter(s)\n            d =dict(sorted(d.items(), key=lambda item: item[0]))\n            for x in d:\n                return d[x]\n        \n        freq = []\n        for w in words:\n            n1 = _f(w)\n            freq.append(n1)\n        \n        freq.sort(reverse=True)\n\n        res = []\n        for q in queries:\n            n = _f(q)\n            c=0\n            for n1 in freq:\n                if n < n1:\n                    c+=1\n                else:\n                    break\n            res.append(c)\n        \n        return res",
        "solution_js": "/**\n * @param {string[]} queries\n * @param {string[]} words\n * @return {number[]}\n */\nvar numSmallerByFrequency = function(queries, words) {\n    let res=[]\n    queries=queries.map(q=>countFrequency(q))//[3,2]\n    words=words.map(w=>countFrequency(w))//[1,2,3,4]\n  words = words.sort((a, b) => a - b)\n    for(let i=0;i<queries.length;i++){\n      let start=0,end=words.length-1\n      while(start<=end){\n          let mid=start+Math.floor((end-start)/2)\n          if(queries[i]<words[mid]){\n              end=mid-1\n          }else{\n              start=mid+1\n          }\n      }\n      res.push(words.length-1-end)\n  }\n    return res\n};\n\nfunction countFrequency(str){\n    let freq={}\n    str.split('').forEach(key=>{\n        freq[key]=(freq[key]||0)+1\n    })\n    return freq[Object.keys(freq).sort()[0]]\n}",
        "solution_java": "class Solution {\n    public int[] numSmallerByFrequency(String[] queries, String[] words) {\n        int[] ans = new int[queries.length];\n        int[] freq = new int[words.length];\n        for (int i = 0; i < words.length; i++) {\n            freq[i] = freqOfSmallest(words[i]);\n        }\n        Arrays.sort(freq);\n        int k = 0;\n        for (String query : queries) {\n            int target = freqOfSmallest(query);\n            ans[k++] = binarySearch(freq, target);\n        }\n        return ans;\n    }\n    public int freqOfSmallest(String s) {\n        int[] freq = new int[26];\n        char min = 'z';\n        for (int i = 0; i < s.length(); i++) {\n            char c = s.charAt(i);\n            freq[c - 'a'] += 1;\n            if (c < min) {\n                min = c;\n            }\n        }\n        return freq[min - 'a'];\n    }\n    public int binarySearch(int[] arr, int target) {\n        int idx = arr.length;\n        int lo = 0;\n        int hi = idx - 1;\n        int mid;\n        while (lo <= hi) {\n            mid = (lo + hi) / 2;\n            if (arr[mid] <= target) {\n                lo = mid + 1;\n            } else {\n                idx = mid;\n                hi = mid - 1;\n            }\n        }\n        return arr.length - idx;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    int countFreq(const string &s) {\n        char c = *min_element(begin(s), end(s));\n        return count(begin(s), end(s), c);\n    }\npublic:\n    vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {\n        vector<int> freqs(11, 0);\n        for (const auto &word : words) {\n            freqs[countFreq(word)]++;\n        }\n        vector<int> prefSum(12, 0);\n        for (int i = 0; i < freqs.size(); i++) {\n            prefSum[i+1] = prefSum[i] + freqs[i];\n        }\n        vector<int> ans;\n        for (const auto &q : queries) {\n            int cnt = countFreq(q);\n            ans.push_back(prefSum.back() - prefSum[cnt + 1]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Sum of Absolute Differences in a Sorted Array",
        "algo_input": "You are given an integer array nums sorted in non-decreasing order.\n\nBuild and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.\n\nIn other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 &lt;= j &lt; nums.length and j != i (0-indexed).\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,5]\nOutput: [4,3,5]\nExplanation: Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\n\n\nExample 2:\n\nInput: nums = [1,4,6,8,10]\nOutput: [24,15,13,15,21]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= nums[i + 1] &lt;= 104\n\n",
        "solution_py": "from itertools import accumulate \n\nclass Solution(object):\n    def getSumAbsoluteDifferences(self, nums):\n        total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)\n        return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumerate(nums), list(accumulate(nums)))]\n        ",
        "solution_js": "var getSumAbsoluteDifferences = function(nums) {\n    const N = nums.length;\n    const ans = new Array(N);\n    ans[0] = nums.reduce((a, b) => a + b, 0) - (N * nums[0]);\n    for (let i = 1; i < N; i++)\n        ans[i] = ans[i - 1] + (nums[i] - nums[i - 1]) * i - (nums[i] - nums[i - 1]) * (N - i); \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int[] getSumAbsoluteDifferences(int[] nums) {\n        int n = nums.length;\n        int[] res = new int[n];\n        int sumBelow = 0;\n        int sumTotal = Arrays.stream(nums).sum();\n\n        for (int i = 0; i < n; i++) {\n            int num = nums[i];\n            sumTotal -= num;\n            res[i] = sumTotal - (n - i - 1) * num + i * num - sumBelow;\n            sumBelow += num;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        vector<int>ans(nums.size(),0);\n        for(int i = 1;i<nums.size();i++)\n            ans[0]+=(nums[i]-nums[0]);\n\n        for(int j = 1;j<nums.size();j++)\n            ans[j] = ans[j-1]+(nums[j]-nums[j-1])*j-(nums[j]-nums[j-1])*(nums.size()-j);\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Subarray Sum with One Deletion",
        "algo_input": "Given an array of integers, return the maximum sum for a non-empty&nbsp;subarray (contiguous elements) with at most one element deletion.&nbsp;In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the&nbsp;sum of the remaining elements is maximum possible.\n\nNote that the subarray needs to be non-empty after deleting one element.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,-2,0,3]\nOutput: 4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.\n\nExample 2:\n\nInput: arr = [1,-2,-2,3]\nOutput: 3\nExplanation: We just choose [3] and it's the maximum sum.\n\n\nExample 3:\n\nInput: arr = [-1,-1,-1,-1]\nOutput: -1\nExplanation:&nbsp;The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t-104 &lt;= arr[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def maximumSum(self, arr: List[int]) -> int:\n        n = len(arr)\n        if n ==1:\n            return arr[0]\n        dpLeft = [-10**4-1 for _ in range(n)]\n        dpLeft[0] = arr[0]\n        i = 1 \n        while i < n :\n            dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])\n            i += 1\n        dpRight = [-10**4-1 for _ in range(n)]\n        dpRight[-1] = arr[-1]\n        j = n-2 \n        while j >= 0:\n            dpRight[j] = max(arr[j],dpRight[j+1]+arr[j])\n            j -= 1\n        k = 0\n        maxi = -10**4-1\n        while k < n:\n            # if we take it \n            curr_maxi_with = dpRight[k] + dpLeft[k] - arr[k]\n            \n            if k==0:\n                curr_maxi_without = dpRight[k+1]\n            elif k==n-1:\n                curr_maxi_without = dpLeft[k-1]\n            else:\n                if dpLeft[k-1]>=0 and dpRight[k+1]>=0:\n                    curr_maxi_without = dpRight[k+1] + dpLeft[k-1]\n                else:\n                    curr_maxi_without = max(dpLeft[k-1],dpRight[k+1])\n            \n            maxi= max(maxi,curr_maxi_without, curr_maxi_with)\n            k += 1\n        \n        return maxi ",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\n \n\n// var maximumSum = function(arr) {\n//     const len = arr.length;\n//     const dp = new Array(len).fill(() => [null, null]);\n//     dp[0][0] = arr[0];\n//     dp[0][1] = 0;\n//     let result = arr[0];\n//     for(let i = 1; i < len; i++) {\n//         dp[i][1] = Math.max(dp[i-1][1] + arr[i], dp[i-1][0]);\n//         dp[i][0] = Math.max(dp[i-1][0] + arr[i], arr[i]);\n//         result = Math.max(result, Math.max(dp[i][0], dp[i][1]));  \n//     }\n    \n//     return result;\n// };\n\n// optimization\nvar maximumSum = function(arr) {\n    let noDelete = arr[0], oneDelete = 0, max = arr[0];\n    for(let i = 1; i < arr.length; i++) {\n        oneDelete = Math.max(oneDelete + arr[i], noDelete);\n        noDelete = Math.max(noDelete + arr[i], arr[i]);\n        max = Math.max(max, Math.max(noDelete, oneDelete));\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maximumSum(int[] arr) {\n        int n = arr.length;\n        int[] prefixSum = new int[n+1];\n        prefixSum[0] = 0;\n        int ans = (int)-1e9;\n        for(int i = 1; i <= n; i++){\n            prefixSum[i] = prefixSum[i-1] + arr[i-1];\n            ans = Math.max(ans, arr[i-1]);\n        }\n        if(ans < 0) return ans;  \n        for(int i = 1; i <= n; i++){\n            if(arr[i-1] < 0){\n                int leftPrefixSum = 0;\n                // find max in i to 0\n                for(int j = i-1; j >= 0; j--){\n                    leftPrefixSum = Math.max(leftPrefixSum, prefixSum[i-1] -prefixSum[j]);\n                }\n                \n                int rightPrefixSum = 0;\n                // find max in i to n\n                for(int j = i+1; j <= n; j++){\n                    rightPrefixSum = Math.max(rightPrefixSum, prefixSum[j] -prefixSum[i]);\n                } \n                ans = Math.max(ans, leftPrefixSum + rightPrefixSum);\n            }\n        }\n        return Math.max(ans, prefixSum[n]);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumSum(vector<int>& arr) {\n        int n = arr.size(), curr, maxi = INT_MIN;\n        vector<int> fw(n + 1, 0), bw(n + 1, 0);\n        fw[0] = arr[0];\n        maxi = max(maxi, fw[0]);\n        \n\t\t// ith element denotes the maximum subarray sum with ith element as the last element\n        for(int i = 1; i < n; ++i) {\n            curr = max(arr[i], fw[i - 1] + arr[i]);\n            maxi = max(maxi, curr);\n            fw[i] = curr;\n        }\n        \n\t\t// similar to fw array, but in the backward direction\n        bw[n - 1] = curr = arr[n - 1];\n        for(int i = n - 2; i >= 0; --i) {\n            curr = max(arr[i], bw[i + 1] + arr[i]);\n            maxi = max(maxi, curr);\n            bw[i] = curr;\n        }\n        \n        int res = INT_MIN;\n        for(int i = 1; i < n - 1; ++i) {\n            res = max(res, fw[i - 1] + bw[i + 1]);\n        }\n        return max(res, maxi);\n    }\n};"
    },
    {
        "title": "Maximum Employees to Be Invited to a Meeting",
        "algo_input": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.\n\nThe employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.\n\nGiven a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.\n\n&nbsp;\nExample 1:\n\nInput: favorite = [2,2,1,2]\nOutput: 3\nExplanation:\nThe above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3. \n\n\nExample 2:\n\nInput: favorite = [1,2,0]\nOutput: 3\nExplanation: \nEach employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.\n\n\nExample 3:\n\nInput: favorite = [3,0,1,4,1]\nOutput: 4\nExplanation:\nThe above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == favorite.length\n\t2 &lt;= n &lt;= 105\n\t0 &lt;= favorite[i] &lt;=&nbsp;n - 1\n\tfavorite[i] != i\n\n",
        "solution_py": "class Solution:\n    def maximumInvitations(self, favorite: List[int]) -> int:\n        n = len(favorite)\n        visited_time = [0] * n\n        inpath = [False] * n\n        cur_time = 1\n        def get_max_len_cycle(cur) :\n            nonlocal cur_time\n            inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]\n            cur_time += 1\n            ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1\n            if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))\n            inpath[cur] = False\n            return ret\n        \n        ret_cycle = 0\n        for i in range(n) :\n            if visited_time[i] == 0 :\n                ret_cycle = max(ret_cycle, get_max_len_cycle(i))\n        \n        ret_not_cycle = 0\n        back_edge_graph = [[] for _ in range(n)]\n        for i in range(n) : back_edge_graph[favorite[i]].append(i)\n        def get_max_depth(cur) :\n            ret = 0\n            for nxt in back_edge_graph[cur] :\n                if favorite[cur] != nxt :\n                    ret = max(ret, get_max_depth(nxt) + 1)\n            return ret\n        \n        for i in range(n) :\n            if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1\n        \n        ret = max(ret_cycle, ret_not_cycle)\n        return ret",
        "solution_js": "/**\n * @param {number[]} favorite\n * @return {number}\n */\nvar maximumInvitations = function(favorite) {\n    let res = 0;\n    let len = favorite.length;\n    // count the number indegree\n    let indegree = new Array(len).fill(0);\n    // save the number relation\n    let rMap = new Map();\n    for(let i=0; i<favorite.length; i++){\n        indegree[favorite[i]] ++;\n\n        if(rMap.has(favorite[i])){\n            let arr = rMap.get(favorite[i]);\n            arr.push(i);\n            rMap.set(favorite[i], arr);\n        }else{\n            rMap.set(favorite[i], [i]);\n        }\n    }\n    // find the 0 indegree number\n    let arr = [];\n    for(let i=0; i<len; i++){\n        if(indegree[i] === 0){\n            arr.push(i);\n        }\n    }\n    // check if the circle exist\n    let search = 0;\n    // the length of uncircle\n    let l = 1;\n    // save the number and the length of uncircle\n    let lMap = new Map();\n    while(arr.length > 0){\n        let tmp = [];\n        for(let i=0; i<arr.length; i++){\n            lMap.set(arr[i], l);\n            let next = favorite[arr[i]];\n            indegree[next] --;\n            search ++;\n            if(indegree[next] === 0){\n                tmp.push(next);\n            }\n        }\n        // update the length of uncircle\n        l ++;\n        arr = [...tmp];\n    }\n\n    if(search === len){\n        // circle not exist\n    }else{\n        // circle exist\n        // find the not 0 indegree number\n        let keys = find(indegree);\n        // mark the search number in circle\n        let circleMap = new Map();\n        // the length of circle\n        let circleLen = 1;\n        // the max length of circle\n        let maxCircleLen = 0;\n        // sum the length of circle\n        let sumCircleLen = 0;\n        let cArr = [keys[0]];\n\n        while(cArr.length > 0){\n            let tmp = [];\n            for(let i=0; i<cArr.length; i++){\n                // not find the circle\n                if(!circleMap.has(cArr[i])){\n                    circleMap.set(cArr[i], circleLen);\n                    tmp.push(favorite[cArr[i]]);\n                // find the circle\n                }else{\n                    maxCircleLen = Math.max(maxCircleLen, circleLen-1);\n                    // if the length equals 2 then sum the length\n                    if(circleLen-1 === 2){\n                        let m = calc(cArr[i], rMap, lMap) + calc(favorite[cArr[i]], rMap, lMap) + 2;\n                        sumCircleLen += m;\n                    }\n                    // reset the length\n                    circleLen = 0;\n                    // find the next number not search\n                    for(let i=0; i<keys.length; i++){\n                        if(!circleMap.has(keys[i])){\n                            tmp.push(keys[i]);\n                            break;\n                        }\n                    }\n                }\n            }\n            circleLen ++;\n            cArr = [...tmp];\n        }\n        res = Math.max(res, maxCircleLen, sumCircleLen);\n    }\n\n    return res;\n};\n\nfunction calc(num, rMap, lMap){\n    let res = 0;\n    let arr = rMap.has(num) ? rMap.get(num) : [];\n    if(arr.length > 0){\n        for(let i=0; i<arr.length; i++){\n            let l = lMap.has(arr[i]) ? lMap.get(arr[i]) : 0;\n            res = Math.max(res, l);\n        }\n    }\n    return res;\n}\n\nfunction find(arr){\n    let res = [];\n    for(let i=0; i<arr.length; i++){\n        if(arr[i] > 0){\n            res.push(i);\n        }\n    }\n    return res;\n}",
        "solution_java": "class Solution {\n    public int maximumInvitations(int[] favorite) {\n        List<List<Integer>> graph = new ArrayList<>();\n        for (int i = 0; i < favorite.length; i++) {\n            graph.add(new ArrayList<>());\n        }\n\n        int answer = 0;\n\n        List<List<Integer>> pairs = new ArrayList<>();\n        for (int i = 0; i < favorite.length; i++) {\n            if (i == favorite[favorite[i]]) {\n                if (i < favorite[i]) {\n                    List<Integer> pair = new ArrayList<>();\n                    pair.add(i);\n                    pair.add(favorite[i]);\n                    pairs.add(pair);\n                }\n            } else {\n                graph.get(favorite[i]).add(i);\n            }\n        }\n\n        boolean[] visited = new boolean[favorite.length];\n        for (List<Integer> pair: pairs) {\n            answer += dfs(graph, pair.get(0), visited) + dfs(graph, pair.get(1), visited);\n        }\n\n        int[] counter = new int[favorite.length];\n        int[] round = new int[favorite.length];\n\n        int rnd = 1;\n\n        int circleMax = 0;\n\n        for (int i = 0; i < favorite.length; i++) {\n            if (visited[i]) {\n                continue;\n            }\n            if (round[i] != 0) {\n                continue;\n            }\n\n            int cnt = 1;\n            int j = i;\n            while (counter[j] == 0) {\n                counter[j] = cnt;\n                round[j] = rnd;\n                j = favorite[j];\n                cnt++;\n            }\n            if (round[j] == rnd) {\n                circleMax = Math.max(circleMax, cnt - counter[j]);\n            }\n            rnd++;\n        }\n        return Math.max(circleMax, answer);\n    }\n\n    private int dfs(List<List<Integer>> graph, int node, boolean[] visited) {\n        visited[node] = true;\n        int max = 0;\n        for (int neighbor: graph.get(node)) {\n            max = Math.max(max, dfs(graph, neighbor, visited));\n        }\n        return max + 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> rev;\n    vector<int> es, sizeOfTwo;\n    int N, ans1, ans2;\n    void dfs(vector<int>& depth, int cur, int d) {\n        if (depth[cur] > 0) {\n            if (d - depth[cur] == 2) sizeOfTwo.push_back(cur);\n            ans1 = max(ans1, d - depth[cur]);\n            return;\n        }\n        if (depth[cur] != -1) return;\n        depth[cur] = d;\n        dfs(depth, es[cur], d+1);\n        depth[cur] = 0; // 0 means visited\n    }\n    void findAllCircules() {\n        vector<int> depth(N, -1);\n        for (int i=0; i<N; i++) {\n            if (depth[i] == -1) {\n                dfs(depth, i, 1);\n            }\n        }\n    }\n    int dfs2(int cur, int except) {\n        int ret = 1;\n        int d = 0;\n        for (auto nxt : rev[cur]) {\n            if (nxt != except) {\n                d = max(d, dfs2(nxt, except));\n            }\n        }\n        return ret + d;\n    }\n    void expandSizeOfTwo() {\n        for (auto i : sizeOfTwo) {\n            int j = es[i];\n            ans2 += dfs2(i, j);\n            ans2 += dfs2(j, i);\n        }\n    }\n    int maximumInvitations(vector<int>& favorite) {\n        es = favorite;\n        N = es.size(), ans1 = 0, ans2 = 0;\n        rev.resize(N);\n        for (int i=0; i<N; i++) {\n            rev[es[i]].push_back(i);\n        }\n        findAllCircules();\n        expandSizeOfTwo();\n        return max(ans1, ans2);\n    }\n};"
    },
    {
        "title": "Fair Distribution of Cookies",
        "algo_input": "You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.\n\nThe unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.\n\nReturn the minimum unfairness of all distributions.\n\n&nbsp;\nExample 1:\n\nInput: cookies = [8,15,10,20,8], k = 2\nOutput: 31\nExplanation: One optimal distribution is [8,15,8] and [10,20]\n- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.\n- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.\nThe unfairness of the distribution is max(31,30) = 31.\nIt can be shown that there is no distribution with an unfairness less than 31.\n\n\nExample 2:\n\nInput: cookies = [6,1,3,2,2,4,1,2], k = 3\nOutput: 7\nExplanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]\n- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.\n- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.\n- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.\nThe unfairness of the distribution is max(7,7,7) = 7.\nIt can be shown that there is no distribution with an unfairness less than 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= cookies.length &lt;= 8\n\t1 &lt;= cookies[i] &lt;= 105\n\t2 &lt;= k &lt;= cookies.length\n\n",
        "solution_py": "class Solution:\n    def distributeCookies(self, cookies: List[int], k: int) -> int:\n        ans = float('inf')\n        fair = [0]*k\n        def rec(i):\n            nonlocal ans,fair\n            if i == len(cookies):\n                ans = min(ans,max(fair))\n                return\n\t\t\t# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution\n\t\t\tif ans <= max(fair):\n                return\n            for j in range(k):\n                fair[j] += cookies[i]\n                rec(i+1)\n                fair[j] -= cookies[i]\n        rec(0)\n        return ans",
        "solution_js": "var distributeCookies = function(cookies, k) {\n    cookies.sort((a, b) => b - a);\n    if(k === cookies.length) return cookies[0];\n    \n    const arr = new Array(k).fill(0);\n    let res = Infinity;\n    \n    function helper(arr, cookies, level) {\n        if(level === cookies.length) {\n            const max = Math.max(...arr);\n            res = Math.min(res, max);\n            return;\n        }\n        const cookie = cookies[level];\n        for(let i = 0; i < arr.length; i++) {\n            arr[i] += cookie;\n            helper(arr, cookies, level + 1);\n            arr[i] -= cookie;\n        }\n    }\n    \n    helper(arr, cookies, 0);\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    int ans;\n    int count[];\n    public int distributeCookies(int[] cookies, int k) {\n        ans= Integer.MAX_VALUE;\n        count= new int[k];\n\n        backtrack(0,cookies, k);\n        return ans;\n    }\n    public void backtrack(int cookieNumber, int[] cookies, int k)\n    {\n        if(cookieNumber==cookies.length)\n        {\n            int max= 0;\n            for(int i=0; i<k; i++)\n            {\n                max=Math.max(max, count[i]);\n\n            }\n            ans = Math.min(ans, max);\n            return;\n        }\n        for(int i=0;i<k; i++)\n        {\n            count[i]+=cookies[cookieNumber];\n            backtrack(cookieNumber+1, cookies, k);\n            count[i]-=cookies[cookieNumber];\n            if(count[i]==0) break;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = INT_MAX;\n    void solve(int start, vector<int>& nums, vector<int>& v, int k){\n        if(start==nums.size()){\n            int maxm = INT_MIN;\n            for(int i=0;i<k;i++){\n                maxm = max(maxm,v[i]);\n            }\n            ans = min(ans,maxm);\n            return;\n        }\n        for(int i=0;i<k;i++){\n            v[i] += nums[start];\n            solve(start+1,nums,v,k);\n            v[i] -= nums[start];\n        }\n    }\n    \n    int distributeCookies(vector<int>& nums, int k) { // nums is the cookies vector\n        int n = nums.size();\n        vector<int> v(k,0); // v is to store each sum of the k subsets\n        solve(0,nums,v,k);\n        return ans;\n    }\n};"
    },
    {
        "title": "K-th Symbol in Grammar",
        "algo_input": "We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.\n\n\n\tFor example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.\n\n\nGiven two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.\n\n&nbsp;\nExample 1:\n\nInput: n = 1, k = 1\nOutput: 0\nExplanation: row 1: 0\n\n\nExample 2:\n\nInput: n = 2, k = 1\nOutput: 0\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\nExample 3:\n\nInput: n = 2, k = 2\nOutput: 1\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 30\n\t1 &lt;= k &lt;= 2n - 1\n\n",
        "solution_py": "class Solution:\n  def solve(self,n,k):\n    if n==1 and k==1:\n      return 0 \n    mid = pow(2,n-1)//2 \n    if k<=mid:\n      return self.solve(n-1,k) \n    \n    return not self.solve(n-1,k-mid)\n    \n      \n  def kthGrammar(self,n,k):\n    if self.solve(n,k):\n      return 1 \n    else:\n      return 0 \n      \n    \n   \n    \n    \n    \n    \n    \n    \n    ",
        "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar kthGrammar = function(n, k) {\n    if (n == 1 && k == 1) {\n        return 0;\n    }\n\n    const mid = Math.pow(2, n-1) / 2;\n\n    if (k <= mid) {\n        return kthGrammar(n-1, k);\n    } else {\n        return kthGrammar(n-1, k-mid) == 1 ? 0 : 1;\n    }\n};",
        "solution_java": "class Solution {\n    public int kthGrammar(int n, int k) {\n       if (n == 1 || k == 1) {\n            return 0;\n        }\n        int length = (int) Math.pow(2, n - 1);\n        int mid = length / 2;\n        if (k <= mid) {\n            return kthGrammar(n - 1, k);\n        } else if (k > mid + 1) {\n            return invert(kthGrammar(n - 1, k - mid));\n        } else {\n            return 1;\n        }\n    }\n    static int invert(int x) {\n        if (x == 0) {\n            return 1;\n        }\n        return 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int kthGrammar(int n, int k) {\n        int kthNode = pow(2, (n-1)) + (k - 1);\n        vector<int>arr;\n        while(kthNode) {\n            arr.push_back(kthNode);\n            kthNode /= 2;\n        }\n        arr[arr.size() - 1] = 0;\n        for (int i = arr.size() - 2; i >= 0; i--) {\n            if (arr[i] % 2 == 0) {\n                arr[i] = arr[i+1];\n            }\n            else {\n                arr[i] = 1 ^ arr[i+1];\n            }\n        }\n        return arr[0];\n    }\n};"
    },
    {
        "title": "Dota2 Senate",
        "algo_input": "In the world of Dota2, there are two parties: the Radiant and the Dire.\n\nThe Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:\n\n\n\tBan one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.\n\tAnnounce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.\n\n\nGiven a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.\n\nThe round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.\n\nSuppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\".\n\n&nbsp;\nExample 1:\n\nInput: senate = \"RD\"\nOutput: \"Radiant\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\nExample 2:\n\nInput: senate = \"RDD\"\nOutput: \"Dire\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == senate.length\n\t1 &lt;= n &lt;= 104\n\tsenate[i] is either 'R' or 'D'.\n\n",
        "solution_py": "class Solution:\n    def predictPartyVictory(self, senate: str) -> str:\n        nxt = \"\"\n        ar, de = senate.count('R'), senate.count('D')\n        r , d = 0, 0\n        while(ar and de) :\n            for i in senate :\n                if (i== 'R' and d == 0):\n                    r += 1\n                    nxt = nxt + 'R'\n                elif (i== 'R' and d > 0):\n                    d -= 1\n                elif (i== 'D' and r > 0):\n                    r -= 1\n                elif(i== 'D' and r == 0):\n                    d += 1\n                    nxt = nxt + 'D'\n            senate = nxt\n            nxt = \"\"\n            ar, de = senate.count('R'), senate.count('D')\n        if (ar) :\n            return 'Radiant'\n        else:\n            return 'Dire'",
        "solution_js": "var predictPartyVictory = function(senate) {\n    let index = 0, RCount = 0, DCount = 0, deletion = false, delCount = 1;\n    while(delCount || index < senate.length) {\n        if(index >= senate.length) {\n            index = 0;\n            delCount = 0;\n        }\n        deletion = false;\n        if(senate.charAt(index) == 'R') {\n            if(DCount > 0) {\n                senate = senate.slice(0,index)+senate.slice(index+1);\n                DCount--;\n                index--;\n                deletion = true;\n                delCount++;\n            }\n            else {\n                RCount++;\n            }\n        }\n        else if(senate.charAt(index) == 'D') {\n            if(RCount > 0) {\n                senate = senate.slice(0,index)+senate.slice(index+1);\n                RCount--;\n                index--;\n                deletion = true;\n                delCount++;\n            }\n            else {\n                DCount++;\n            }\n        }\n        if(index == senate.length-1) {\n            if(senate.charAt(0) == 'R' && senate.charAt(index) == 'D' && DCount > 0 && !deletion) {\n                senate = senate.slice(1);\n                DCount--;\n                index = -1;\n            }\n            else if(senate.charAt(0) == 'D' && senate.charAt(index) == 'R' && RCount > 0 && !deletion) {\n                senate = senate.slice(1);\n                RCount--;\n                index = -1;\n            }            \n        }\n        index++;\n    }\n    return senate.charAt(0) == 'D' ? 'Dire' : 'Radiant';\n};",
        "solution_java": "// Two Queues Solution\n// Two queues to store the R index and D index.\n// If the senate can execute his right, the senate is alive and can execute in the next round.\n// Then we can add the senate back to the queue and process in the next round (idx + N).\n// Time complexity: O(N), each loop we add/remove 1 senate in the queue.\n// Space complexity: O(N)\nclass Solution {\n    public String predictPartyVictory(String senate) {\n        if (senate == null || senate.length() == 0) throw new IllegalArgumentException(\"Invalid input.\");\n        final int N = senate.length();\n        Queue<Integer> queR = new ArrayDeque<>();  // store the R index\n        Queue<Integer> queD = new ArrayDeque<>();  // store the D index\n        for (int i = 0; i < N; i++) {\n            if (senate.charAt(i) == 'R') {\n                queR.add(i);\n            } else {\n                queD.add(i);\n            }\n        }\n        while (!queR.isEmpty() && !queD.isEmpty()) {\n            int r = queR.poll();\n            int d = queD.poll();\n            if (r < d) {  // R is alive in the next round.\n                queR.add(r + N);\n            } else {  // D is alive in the next round.\n                queD.add(d + N);\n            }\n        }\n        return queR.isEmpty() ? \"Dire\" : \"Radiant\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string predictPartyVictory(string senate) {\n        queue<int> D, R;\n        int len = senate.size();\n        for (int i = 0; i < len; i++) {\n            if (senate[i] == 'D') {\n                D.push(i);\n            }\n            else {\n                R.push(i);\n            }\n        }\n\n        while (!D.empty() && !R.empty()) {\n            int dIdx = D.front();\n            D.pop();\n\n            int rIdx = R.front();\n            R.pop();\n\n            if (dIdx < rIdx) {\n                D.push(dIdx + len);\n            }\n            else {\n                R.push(rIdx + len);\n            }\n        }\n\n        return D.empty() ? \"Radiant\" : \"Dire\";\n    }\n};"
    },
    {
        "title": "Find the Difference",
        "algo_input": "You are given two strings s and t.\n\nString t is generated by random shuffling string s and then add one more letter at a random position.\n\nReturn the letter that was added to t.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcd\", t = \"abcde\"\nOutput: \"e\"\nExplanation: 'e' is the letter that was added.\n\n\nExample 2:\n\nInput: s = \"\", t = \"y\"\nOutput: \"y\"\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 1000\n\tt.length == s.length + 1\n\ts and t consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findTheDifference(self, s: str, t: str) -> str:\n        c = 0\n        for cs in s: c ^= ord(cs) #ord is ASCII value\n        for ct in t: c ^= ord(ct)\n        return chr(c) #chr = convert ASCII into character",
        "solution_js": "var findTheDifference = function(s, t) {\n    var map = {};\n    var re = \"\";\n    for(let i = 0; i < t.length; i++){\n        if(t[i] in map){\n            map[t[i]] += 1;\n        }else{\n            map[t[i]] = 1;\n        }\n    }\n\n    for(let i = 0; i < s.length; i++){\n        if(s[i] in map){\n            map[s[i]] -= 1;\n        }\n    }\n\n    for(let [key, value] of Object.entries(map)){\n        if(value > 0){\n            let temp = re.concat(key);\n            re = temp;\n        }\n    }\n    return re;\n};",
        "solution_java": "class Solution {\n    public char findTheDifference(String s, String t) {\n        char c = 0;\n        for(char cs : s.toCharArray()) c ^= cs;\n        for(char ct : t.toCharArray()) c ^= ct;\n        return c;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    char findTheDifference(string s, string t) {\n        char c = 0;\n        for(char cs : s) c ^= cs;\n        for(char ct : t) c ^= ct;\n        return c;\n    }\n};"
    },
    {
        "title": "Maximum Score From Removing Substrings",
        "algo_input": "You are given a string s and two integers x and y. You can perform two types of operations any number of times.\n\n\n\tRemove substring \"ab\" and gain x points.\n\n\t\n\t\tFor example, when removing \"ab\" from \"cabxbae\" it becomes \"cxbae\".\n\t\n\t\n\tRemove substring \"ba\" and gain y points.\n\t\n\t\tFor example, when removing \"ba\" from \"cabxbae\" it becomes \"cabxe\".\n\t\n\t\n\n\nReturn the maximum points you can gain after applying the above operations on s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput: 19\nExplanation:\n- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.\n\nExample 2:\n\nInput: s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput: 20\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\t1 &lt;= x, y &lt;= 104\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def maximumGain(self, s: str, x: int, y: int) -> int:\n        a = 'a'\n        b = 'b'\n        if x < y:\n            x, y = y, x\n            a, b = b, a\n        seen = Counter()\n        ans = 0\n        for c in s + 'x':\n            if c in 'ab':\n                if c == b and 0 < seen[a]:\n                    ans += x\n                    seen[a] -= 1\n                else:\n                    seen[c] += 1\n            else:\n                ans += y * min(seen[a], seen[b])\n                seen = Counter()\n\n        return ans",
        "solution_js": "var maximumGain = function(s, x, y) {\n    const n = s.length;\n    \n    let totPoints = 0;\n    let stack;\n    \n    if (x > y) {\n        stack = remove(s, x, \"ab\");\n        s = stack.join(\"\");\n        remove(s, y, \"ba\");\n        \n    }\n    else {\n        stack = remove(s, y, \"ba\");\n        s = stack.join(\"\");\n        remove(s, x, \"ab\");\n    }\n    \n    return totPoints;\n    \n    \n    function remove(str, points, match) {\n        const stack = [];\n        \n        for (let i = 0; i < str.length; i++) {\n            const char = str.charAt(i);\n            \n            if (stack.length > 0 && stack[stack.length - 1] + char == match) {\n                totPoints += points;\n                stack.pop();\n            }\n            else {\n                stack.push(char);\n            }\n        }\n        \n        return stack;\n    }\n};",
        "solution_java": "class Solution {\n    public int maximumGain(String s, int x, int y) {\n        \n        int aCount = 0;\n        int bCount = 0;\n        int lesser = Math.min(x, y);\n        int result = 0;\n        \n        for (int i = 0; i < s.length(); i++) {\n            char c = s.charAt(i);\n            if (c > 'b') {\n                result += Math.min(aCount, bCount) * lesser;\n                aCount = 0;\n                bCount = 0;\n            } else if (c == 'a') {\n                if (x < y && bCount > 0) {\n                    bCount--;\n                    result += y;\n                } else {\n                    aCount++;\n                }\n            } else {\n                if (x > y && aCount > 0) {\n                    aCount--;\n                    result += x;\n                } else {\n                    bCount++;\n                };\n            }\n        }\n        \n        result += Math.min(aCount, bCount) * lesser;\n        \n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int helper(string&str, char a, char b){\n        int count =0;\n        stack<char> st;\n        for(int i=0;i<str.length();i++) {\n            if(!st.empty() && str[i]==b && st.top()==a) {\n                st.pop();\n                count++;\n            }\n            else {\n                st.push(str[i]);\n            }\n        }\n        str=\"\";\n        while(!st.empty()) {\n            str += st.top();\n              st.pop();\n            }\n        reverse(str.begin(),str.end());\n        return count;\n    }\n\n    int maximumGain(string s, int x, int y) {\n        int ca=0,cb=0;\n        if(x>y) {\n            ca = helper(s,'a','b');\n            cb = helper(s,'b','a');\n        }\n        else {\n            cb = helper(s,'b','a');\n            ca = helper(s,'a','b');\n        }\n        return ca*x + cb*y;\n    }\n};"
    },
    {
        "title": "Valid Boomerang",
        "algo_input": "Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.\n\nA boomerang is a set of three points that are all distinct and not in a straight line.\n\n&nbsp;\nExample 1:\nInput: points = [[1,1],[2,3],[3,2]]\nOutput: true\nExample 2:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\tpoints.length == 3\n\tpoints[i].length == 2\n\t0 &lt;= xi, yi &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def isBoomerang(self, points: List[List[int]]) -> bool:\n        a,b,c=points\n        return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0])",
        "solution_js": "var isBoomerang = function(points) {\n    \n // if any two of the three points are the same point return false;\n \n if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) return false;\n if (points[0][0] == points[2][0] && points[0][1] == points[2][1]) return false;\n if (points[2][0] == points[1][0] && points[2][1] == points[1][1]) return false;\n \n // if the points are in a straight line return false;\n \n let slope1 = (points[0][1] - points[1][1]) / (points[0][0] - points[1][0]);\n let slope2 = (points[1][1] - points[2][1]) / (points[1][0] - points[2][0]);\n if (points[0][0] == points[1][0] && points[0][0] === points[2][0]) return false;\n if (points[0][1] == points[1][1] && points[0][1] === points[2][1]) return false;\n \n if (slope1 === slope2) return false;\n \n return true;\n \n};",
        "solution_java": "class Solution {\n    public boolean isBoomerang(int[][] points) {\n        double a, b, c, d, area;\n        a=points[0][0]-points[1][0];\n        b=points[1][0]-points[2][0];\n        c=points[0][1]-points[1][1];\n        d=points[1][1]-points[2][1];\n        area=0.5*((a*d)-(b*c));\n        return area!=0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isBoomerang(vector<vector<int>>& points) {\n        if (points.size()<=2) return false;\n        int x0=points[0][0], y0=points[0][1];\n        int x1=points[1][0], y1=points[1][1];\n        int x2=points[2][0], y2=points[2][1];\n        int dx1=x1-x0, dy1=y1-y0;\n        int dx2=x2-x1, dy2=y2-y1;\n        if (dy1*dx2==dy2*dx1) return false;\n        return true;\n    }\n};"
    },
    {
        "title": "Regions Cut By Slashes",
        "algo_input": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions.\n\nGiven the grid grid represented as a string array, return the number of regions.\n\nNote that backslash characters are escaped, so a '\\' is represented as '\\\\'.\n\n&nbsp;\nExample 1:\n\nInput: grid = [\" /\",\"/ \"]\nOutput: 2\n\n\nExample 2:\n\nInput: grid = [\" /\",\"  \"]\nOutput: 1\n\n\nExample 3:\n\nInput: grid = [\"/\\\\\",\"\\\\/\"]\nOutput: 5\nExplanation: Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 30\n\tgrid[i][j] is either '/', '\\', or ' '.\n\n",
        "solution_py": "class Solution:\n    def regionsBySlashes(self, grid: List[str]) -> int:\n        n=len(grid)\n        dots=n+1\n        par=[0]*(dots*dots)\n        rank=[0]*(dots*dots)\n        self.count=1\n\n        def find(x):\n            if par[x]==x:\n                return x\n            temp=find(par[x])\n            par[x]=temp\n            return temp\n        def union(x,y):\n            lx=find(x)\n            ly=find(y)\n            if lx!=ly:\n                if rank[lx]>rank[ly]:\n                    par[ly]=lx\n                elif rank[lx]<rank[ly]:\n                    par[lx]=ly\n                else:\n                    par[lx]=ly\n                    rank[ly]+=1\n            else:\n                self.count+=1\n    #-------------------------------------------#\n        for i in range(len(par)):\n            par[i]=i\n            rank[i]=1\n        for i in range(dots):\n            for j in range(dots):\n                if i==0 or j==0 or i==dots-1 or j==dots-1:\n                    cellno=i*dots+j\n                    if cellno!=0:\n                        union(0,cellno)\n        for i in range(len(grid)):\n            ch=grid[i]\n            for j in range(len(ch)):\n                if ch[j]=='/':\n                    cellno1=i*dots+j+1\n                    cellno2=(i+1)*dots+j\n\n                    union(cellno1,cellno2)\n                elif ch[j]=='\\\\':\n                    cellno1=i*dots+j\n                    cellno2=(i+1)*dots+j+1\n                    union(cellno1,cellno2)\n        return self.count",
        "solution_js": "// this is a very common disjoint set implement\nfunction DS(n) {\n    var root = [...new Array(n).keys()];\n    var rank = new Array(n).fill(0);\n    this.find = function(v) {\n        if (root[v] !== v) root[v] = this.find(root[v]);\n        return root[v];\n    }\n    this.union = function(i, j) {\n        var [ri, rj] = [this.find(i), this.find(j)];\n        if (ri === rj) return;\n        if (rank[ri] > rank[rj]) root[rj] = ri;\n        else if (rank[ri] < rank[rj]) root[ri] = rj;\n        else root[ri] = rj, rank[rj]++;\n    }\n\t// get how many unique unions\n    this.getUnoinCount = function() {\n        for (var i = 0; i < n; i++) this.find(i);\n        return new Set(root).size;\n    }\n}\n\nfunction getKeys(i, j, n) {\n    var val = i * n + j;\n    val *= 2;\n\t// left and right part key of grid[i][j]\n    return [val, val + 1];\n}\n\n/**\n * @param {string[]} grid\n * @return {number}\n */\nvar regionsBySlashes = function(grid) {\n    var n = grid.length;\n    if (n === 1) return grid[0][0] === ' ' ? 1 : 2;\n    var ds = new DS(n * n * 2);\n    for (var i = 0; i < n; i++) {\n        for (var j = 0; j < n; j++) {\n            var [left, right] = getKeys(i, j, n);\n\t\t\t// When this cell is ' ', union left and right.\n            if (grid[i][j] === ' ') ds.union(left, right);\n\t\t\t// if have upper neighbor\n            if (i !== 0) {\n                var [upLeft, upRight] = getKeys(i - 1, j, n);\n\t\t\t\t// For upper neighbor, if it's '/', we should choose right part to union, if '\\', choose left.\n                var upKey = grid[i - 1][j] === '\\\\' ? upLeft : upRight;\n\t\t\t\t// For current cell, if it's '/', we should choose left part to union, if '\\', choose right.\n                var curKey = grid[i][j] === '/' ? left : right;\n                ds.union(upKey, curKey);\n            }\n\t\t\t// if have left neighbor\n            if (j !== 0) {\n                var [leftLeft, leftRight] = getKeys(i, j - 1, n);\n\t\t\t\t// just choose the right part of the left neighbor\n                var leftKey = leftRight;\n\t\t\t\t// just choose the left part of the current cell\n                var curKey = left;\n                ds.union(leftKey, curKey);\n            }\n        }\n    }\n    return ds.getUnoinCount();\n};",
        "solution_java": "class Solution {\n    int[] parent;\n    int[] rank;\n    \n    public int regionsBySlashes(String[] grid) {\n        parent = new int[4*grid.length*grid.length];\n        rank = new int[4*grid.length*grid.length];\n        \n        for(int i=0;i<parent.length;i++){\n            parent[i] = i;\n            rank[i] = 0;\n        }\n        \n        for(int i=0;i<grid.length;i++){\n            for(int j=0;j<grid[i].length();j++){\n                char ch = grid[i].charAt(j);\n                \n                int bno = i * grid.length + j;\n                \n                if(ch != '/'){\n                    unionHelper(4*bno + 0 , 4*bno + 1);\n                    unionHelper(4*bno + 2, 4*bno + 3);\n                }\n                \n                if(ch != '\\\\'){\n                    unionHelper(4*bno + 0 , 4*bno + 3);\n                    unionHelper(4*bno + 1, 4*bno + 2);\n                }\n                \n                if(i > 0){\n                    int obno = (i-1) * grid.length + j;\n                    unionHelper(4*bno + 0 , 4*obno + 2);\n                }\n                \n                if(j > 0){\n                    int obno = i * grid.length + (j-1);\n                    unionHelper(4*bno + 3 , 4*obno + 1);\n                }\n                \n            }\n        }\n        \n        int count = 0;\n        \n        for(int i=0;i<parent.length;i++){\n            if(parent[i] == i){\n                count++;\n            }\n        }\n        \n        return count;       \n        \n    }\n    \n    \n    public int find(int x){\n        if(parent[x] == x){\n            return parent[x];\n        }else{\n            parent[x] = find(parent[x]);\n            return parent[x];\n        }\n    }\n    public void union(int xl,int yl){\n        if(rank[xl] < rank[yl]){\n            parent[xl] = yl;\n        }else if(rank[yl] < rank[xl]){\n            parent[yl] = xl;\n        }else{\n            parent[xl] = yl;\n            rank[yl]++;\n        }\n    }\n    public void unionHelper(int x,int y){\n        int xl = find(x);\n        int yl = find(y);\n        \n        if(xl != yl){\n            union(xl,yl);\n        }\n    }\n}",
        "solution_c": "/*\nConvert grid to 3*n X 3*n grid where eacah of the cell is upscalled to 3x3 grid\nand then map the diagonal to 0 or 1 depending on '/' or '\\' type in the grid.\n\nExample:\n[\"/\\\\\",\"\\\\/\"] this can be converted to following scaled grid:\n\n1 1 0 0 1 1 \n1 0 1 1 0 1 \n0 1 1 1 1 0 \n0 1 1 1 1 0 \n1 0 1 1 0 1 \n1 1 0 0 1 1 \n\nOnce this conversion is done, then its simple island count problem, run dfs from each cell \nto visit all cells and count number of times dfs is started and return it as answer.\n*/\n\nclass Solution {\npublic:\n    int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};\n    void dfs(vector<vector<int>>& g, vector<vector<int>>& vis, int i, int j){\n        for(int d = 0; d<4; ++d){\n            int x = i + dir[d][0];\n            int y = j + dir[d][1];\n            if( x >= 0 && y >= 0 && x < g.size() && y < g.size() && \n                vis[x][y] == -1 && g[x][y] == 1){\n                vis[x][y] = 1;\n                dfs(g, vis, x, y);\n            }\n        }\n    }\n    int regionsBySlashes(vector<string>& grid) {\n        int n = grid.size();\n        vector<vector<int>> g(3*n, vector<int> (3*n, 1)); \n        for(int i = 0; i < n; ++i){\n            for(int j = 0; j< n; ++j){\n                if(grid[i][j] == '\\\\'){\n                   for(int k = 0; k < 3; ++k) g[3*i+k][3*j+k] = 0;\n                }\n                else if(grid[i][j] == '/'){\n                   for(int k = 0; k < 3; ++k) g[3*i+k][3*j+ 2-k] = 0;\n                }\n            }\n        }\n        int count = 0;\n        vector<vector<int>> vis(3*n, vector<int> (3*n, -1));\n        \n        for(int i = 0; i < 3*n; ++i){\n            for(int j = 0; j < 3*n; ++j){\n                if(vis[i][j] == -1 && g[i][j] == 1){ //cout<<i<<\" \"<<j<<endl;\n                    count++;\n                    vis[i][j] = 1;\n                    dfs(g, vis, i, j);\n                }\n            }\n        }\n         \n        return count;\n    }\n};"
    },
    {
        "title": "Find Longest Awesome Substring",
        "algo_input": "You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.\n\nReturn the length of the maximum length awesome substring of s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"3242415\"\nOutput: 5\nExplanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n\n\nExample 2:\n\nInput: s = \"12345678\"\nOutput: 1\n\n\nExample 3:\n\nInput: s = \"213123\"\nOutput: 6\nExplanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists only of digits.\n\n",
        "solution_py": "from collections import defaultdict\nclass Solution:\n    def longestAwesome(self, s: str) -> int:\n        mask = 0\n        index = defaultdict(lambda:float('-inf'),{0:-1})\n        res = 0\n        for i,c in enumerate(s):\n            mask ^= (1<<(ord(c)-ord('0')))\n            if index[mask] == float('-inf'):\n                index[mask] = i\n            res = max(res, i-index[mask])\n\t\t\t#when the palindrome has one odd numbers of digits\n            for j in range(10):\n                tmp_mask = mask^(1<<j)\n                res = max(res, i-index[tmp_mask] if index[tmp_mask] != float('-inf') else 0)\n        return res",
        "solution_js": "var longestAwesome = function(s) {\n    // freq starts with 0:0 because 9 0s is also a state and if I come across a \n    // 0 down the road, that means that the whole array up to index i is of the required type\n    let firstIndex={0:0}, result=-1, curr=0\n    for (let i = 0; i < s.length; i++) {\n       curr^= 1<<s[i]\n       // Check if you have seen curr^0=curr before, \n\t   // because that would make the inbetween elements' xor = 000000000\n       if(firstIndex[curr]!==undefined)\n            result=Math.max(result,i-firstIndex[curr]+1)\n       // Check all the other xors, because that would make \n\t   // the inbetween elements of the required type (100000000,010000000,......,000000001)\n       for (let j = 0; j <10; j++) {\n            let ele=1<<j\n            if(firstIndex[curr^ele]!==undefined)\n                //i-firstIndex[curr^ele] because on freq I saved\n\t\t\t\t//the smallest index where I last met curr^ele\n                result=Math.max(result,i-firstIndex[curr^ele]+1)\n       }\n       if(firstIndex[curr]===undefined)\n\t\t   firstIndex[curr]=i+1// +1 cos 0th place is for my 0 state\n    }\n \n    return result\n};",
        "solution_java": "class Solution {\n    public int longestAwesome(String s) {\n        Map<Integer,Integer>map=new HashMap<>();\n        map.put(0,-1);\n        \n        int state=0;\n        int ans=0;\n        for(int i=0;i<s.length();i++){\n            int bit=(1<<(s.charAt(i)-'0'));\n            state ^=bit; //if odd freq then it becomes even or if even becomes odd\n            \n            if(map.containsKey(state))\n               ans=Math.max(ans,i-map.get(state));\n            \n                for(int odd=0;odd<=9;odd++){ //become odds one by one\n                    int mask=(1<<odd);\n                    \n                    Integer j=map.get(state^mask);\n                    \n                    if(j!=null)\n                        ans=Math.max(ans,i-j);\n                }\n            \n            if(!map.containsKey(state))\n                map.put(state,i);\n        }\n        return ans;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestAwesome(string s) {\n        unordered_map<int,int> map;\n        int mask = 0, maxL = 0;\n        map[mask] = -1;\n\n        for(int i=0; i<s.size(); ++i){\n            int ch = s[i]-'0';\n            mask^= (1<<ch);\n\n            if(map.find(mask) != map.end()){\n                maxL = max(maxL, i-map[mask]);\n            }\n\n            for(int x=0; x<=9; ++x){\n                int newMask = mask^(1<<x);\n                if(map.find(newMask) != map.end()){\n                    maxL = max(maxL, i-map[newMask]);\n                }\n            }\n\n            if(map.find(mask) == map.end()){\n                map[mask] = i;\n            }\n        }\n        return maxL;\n    }\n};"
    },
    {
        "title": "Path In Zigzag Labelled Binary Tree",
        "algo_input": "In an infinite binary tree where every node has two children, the nodes are labelled in row order.\n\nIn the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.\n\n\n\nGiven the label of a node in this tree, return the labels in the path from the root of the tree to the&nbsp;node with that label.\n\n&nbsp;\nExample 1:\n\nInput: label = 14\nOutput: [1,3,4,14]\n\n\nExample 2:\n\nInput: label = 26\nOutput: [1,2,6,10,26]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= label &lt;= 10^6\n\n",
        "solution_py": "class Solution:\n    def pathInZigZagTree(self, label: int) -> List[int]:\n        result = [label]\n\n        #determine level of label\n        #O(log n)\n        level, nodeCount = 1, 1\n        while label >= nodeCount * 2:\n            nodeCount *= 2\n            level += 1\n\n        #Olog(n) time\n        while label > 1:\n            #compute max and min node\n            maxNode, minNode = 2**level-1, 2**(level-1)\n\n            parent = ((maxNode + minNode) - label) // 2\n\n            #slightly costly operation\n            result = [parent] + result\n\n            label = parent\n            level -= 1\n\n        return result",
        "solution_js": "var pathInZigZagTree = function(label) {\n    //store highest and lowest value for each level\n    let levels = [[1,1]] //to reduce space complexity we will fill the levels array with out output as we go\n    let totalNodes = 1\n    let nodesInLastRow = 1\n    \n    //Calculate which level the label lies in\n    while (totalNodes < label) {      \n        let lowest = totalNodes + 1\n        \n        nodesInLastRow = nodesInLastRow * 2\n        totalNodes += nodesInLastRow\n          \n        let highest = totalNodes\n        \n        levels.push([lowest, highest])\n    }\n    \n\n    let index = levels.length\n    let childBoundaries = levels[levels.length -1]\n    levels[levels.length -1] = label\n    \n    //Work bottom up, for each level, calculate the value based on the child and the child boundaries boundaries\n    for (let i=levels.length-2; i>=0; i--) {\n        let childLevel = i+2 //2 because i is index of 0, so 1 is to preset it to 1...n and then and second one is parent level\n        let childValue = levels[i+1]    \n        \n        let inversionCalculation = Math.abs((childBoundaries[0] + childBoundaries[1]) - childValue)\n        \n        childBoundaries = levels[i]\n        \n        levels[i] = Math.floor(inversionCalculation/2)   \n    }\n    \n    return levels\n};",
        "solution_java": "class Solution {\n    \n   \n    \n    \n    public List<Integer> pathInZigZagTree(int label) \n    {\n        int level, upper, parent, i = label;\n        double min, max;\n        List<Integer> ans = new ArrayList<Integer> ();\n        \n        ans.add(i);\n        \n        while( i> 1)\n        {\n            level = (int)(Math.log(i) / Math.log(2));\n            upper = level -1;\n            min = Math.pow(2.0, upper);\n            max = Math.pow(2.0, level) - 1;\n            parent = (int)(min + max) - i/2; \n            \n            ans.add(0, parent);\n            i = parent;\n        }\n        \n        return ans;\n        \n        \n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    vector<int> pathInZigZagTree(int label)\n    {\n        vector<int> v;\n        int n = 0, num = label;\n        while (label)\n        {\n            n++;\n            label = label >> 1;\n        }\n\n        int l, r, c, ans;\n        for (int i = n; i >= 2; i--)\n        {\n\n            r = pow(2, i) - 1;\n            l = pow(2, i - 1);\n            c = r - num;\n            ans = l + c;\n            if ((n + i) % 2)\n            {\n                v.push_back(ans);\n            }\n            else\n            {\n                v.push_back(num);\n            }\n            num /= 2;\n        }\n        v.push_back(1);\n        sort(v.begin(), v.end());\n        return v;\n    }\n};"
    },
    {
        "title": "Longest Word in Dictionary",
        "algo_input": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.\n\nIf there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.\n\nNote that the word should be built from left to right with each additional character being added to the end of a previous word.&nbsp;\n\n&nbsp;\nExample 1:\n\nInput: words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput: \"world\"\nExplanation: The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\n\n\nExample 2:\n\nInput: words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput: \"apple\"\nExplanation: Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length &lt;= 30\n\twords[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestWord(self, words: List[str]) -> str:\n        TrieNode = lambda: defaultdict(TrieNode)\n        root = TrieNode()\n        for i,s in enumerate(words):\n            cur = root\n            for c in s: cur=cur[c]\n            cur['$']=i\n\n        ans = ''\n        st = list(root.values())\n        while st:\n            cur = st.pop()\n            if '$' in cur:\n                w = words[cur['$']]\n                if len(ans)<len(w) or len(ans)==len(w) and w<ans:ans=w\n                st.extend([cur[i] for i in cur if i!='$'])\n        return ans",
        "solution_js": "var longestWord = function(words) {\n  words.sort();\n  let trie = new Trie();\n  let result = \"\"\n  \n  for (const word of words) {\n      if (word.length === 1) {\n          trie.insert(word);\n          result = word.length > result.length ? word : result;\n      } else {\n          let has = trie.search(word.slice(0, word.length-1));\n          if (has) {\n              trie.insert(word);\n              result = word.length > result.length ? word : result;\n          }\n      }\n  }\n  \n  return result;\n};",
        "solution_java": "class Solution {\n    private class Node{\n        Node[] sub;\n        Node(){\n            sub = new Node[26];\n        }\n    }\n    Node root;\n    StringBuilder ans;\n    private void buildTire(String word){\n        Node temp = root;\n        int n = word.length();\n        for(int i = 0; i < n-1; i++){\n            int index = word.charAt(i)-'a';\n            if(temp.sub[index] == null) return;\n            temp = temp.sub[index];\n        }\n        int index = word.charAt(n-1)-'a';\n        temp.sub[index] = new Node();\n        \n        if(word.length() > ans.length())\n            ans = new StringBuilder(word);\n    }\n    public String longestWord(String[] words) {\n        this.ans = new StringBuilder();\n        this.root = new Node();\n        PriorityQueue<String> pq = new PriorityQueue<>();\n        pq.addAll(Arrays.asList(words));\n        while(!pq.isEmpty()) buildTire(pq.poll());\n        return ans.toString();\n    }\n}",
        "solution_c": "struct node{\n    int end=0;\n    node* adj[26];\n};\n\nclass Solution {\npublic:\n    string longestWord(vector<string>& words) {\n        auto root = new node();\n        auto insert = [&](string&s, int ind){\n            node* cur = root;\n            int i;\n            for(char&c:s){\n                i=c - 'a';\n                if(!cur->adj[i])cur->adj[i] = new node();\n                cur=cur->adj[i];\n            }\n            cur->end=ind;\n        };\n\n        int ind = 0;\n        for(string&s : words) insert(s,++ind);\n\n        stack<node*> st;\n        st.push(root);\n        string ans = \"\";\n        while(!st.empty()){\n            node* cur = st.top();st.pop();\n            if(cur->end>0 || cur==root){\n                if(cur!=root){\n                    string word = words[cur->end-1];\n                    if(word.size()>ans.size() ||\n                      (word.size()==ans.size() && word<ans)){ans = word;}\n                }\n\n                for(int j=0;j<26;j++)\n                    if(cur->adj[j])st.push(cur->adj[j]);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Optimal Division",
        "algo_input": "You are given an integer array nums. The adjacent integers in nums will perform the float division.\n\n\n\tFor example, for nums = [2,3,4], we will evaluate the expression \"2/3/4\".\n\n\nHowever, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.\n\nReturn the corresponding expression that has the maximum value in string format.\n\nNote: your expression should not contain redundant parenthesis.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1000,100,10,2]\nOutput: \"1000/(100/10/2)\"\nExplanation:\n1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant, since they don't influence the operation priority. So you should return \"1000/(100/10/2)\".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n\n\nExample 2:\n\nInput: nums = [2,3,4]\nOutput: \"2/(3/4)\"\n\n\nExample 3:\n\nInput: nums = [2]\nOutput: \"2\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 10\n\t2 &lt;= nums[i] &lt;= 1000\n\tThere is only one optimal division for the given iput.\n\n",
        "solution_py": "class Solution(object):\n    def optimalDivision(self, nums):\n\n        A = list(map(str, nums))\n        \n        \n        if len(A) <= 2:\n            \n            return '/'.join(A)\n        \n        \n        return A[0] + '/(' + '/'.join(A[1:]) + ')'",
        "solution_js": "var optimalDivision = function(nums) {\n\tconst { length } = nums;\n\tif (length === 1) return `${nums[0]}`;\n\tif (length === 2) return nums.join('/');\n\n\treturn nums.reduce((result, num, index) => {\n\t\tif (index === 0) return `${num}/(`;\n\t\tif (index === length - 1) return result + `${num})`;\n\t\treturn result + `${num}/`;\n\t}, '');\n};",
        "solution_java": "class Solution {\n    public String optimalDivision(int[] nums) {\n    \n         if(nums.length==1){\n            return nums[0] + \"\";\n        }else if(nums.length==2){\n            StringBuilder sb=new StringBuilder();\n            sb.append(nums[0] + \"/\" + nums[1]);\n            return sb.toString();\n        }\n        \n        StringBuilder sb=new StringBuilder();\n         sb.append(nums[0]);\n         sb.append(\"/(\");\n       for(int i=1;i<nums.length-1;i++){           \n            sb.append(nums[i] + \"/\");\n        }\n        sb.append(nums[nums.length-1] + \")\");\n      \n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string optimalDivision(vector<int>& nums) {\n        string s=\"\";\n        if(nums.size()==1)\n            return to_string(nums[0]);\n        if(nums.size()==2)\n            return to_string(nums[0])+'/'+to_string(nums[1]);\n        for(int i=0;i<nums.size();i++)\n        {\n            s+=to_string(nums[i])+\"/\";\n            if(i==0)\n                s+=\"(\";\n        }\n        s[s.size()-1]=')';\n        return s;\n    }\n};"
    },
    {
        "title": "Number of Matching Subsequences",
        "algo_input": "Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.\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\n&nbsp;\nExample 1:\n\nInput: s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\nOutput: 3\nExplanation: There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".\n\n\nExample 2:\n\nInput: s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 104\n\t1 &lt;= words.length &lt;= 5000\n\t1 &lt;= words[i].length &lt;= 50\n\ts and words[i] consist of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numMatchingSubseq(self, s: str, words: List[str]) -> int:\n        word_dict = defaultdict(list)\n        numMatch = 0\n        # add words into bucket with key as order of the first letter\n        for w in words:\n            word_dict[ord(w[0])-ord('a')].append(w)\n        # loop through the characters in s\n        for c in s:\n            qualified = word_dict[ord(c)-ord('a')]\n            word_dict[ord(c)-ord('a')] = []\n            for q in qualified:\n                # if the word starts with the specified letter. i.e this is the last letter of the word\n                if len(q) == 1:\n                    numMatch += 1\n                else:\n                    word_dict[ord(q[1])-ord('a')].append(q[1:])\n        return numMatch",
        "solution_js": "var numMatchingSubseq = function(s, words) {\n    let subsequence = false;\n    let count = 0;\n    let prevIdx, idx \n    for(const word of words) {\n        prevIdx = -1;\n        idx = -1;\n        subsequence = true;\n        for(let i = 0; i < word.length; i++) {\n            idx = s.indexOf(word[i], idx + 1);\n            if(idx > prevIdx) {\n                prevIdx = idx;\n            } else {\n                subsequence = false;\n                break;\n            }\n        }\n        if(subsequence) count++;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int numMatchingSubseq(String s, String[] words) {\n        int count = 0;\n        Map<String, Integer> map = new HashMap<>();\n        for(String word : words){\n            if(!map.containsKey(word)){\n                map.put(word, 1);\n            }\n            else{\n                map.put(word, map.get(word)+1);\n            }\n        }\n        for(String word : map.keySet()){\n            if(isSeq(word, s)){\n                count += map.get(word);\n            }\n        }\n        return count;\n    }\n    public boolean isSeq(String s1, String s2){\n        int s1ind = 0;\n        int s2ind = 0;\n        int counter = 0;\n        if(s1.length() > s2.length()){\n            return false;\n        }\n        while(s1ind < s1.length() && s2ind < s2.length()){\n            if(s1.charAt(s1ind) == s2.charAt(s2ind)){\n                counter++;\n                s1ind++;\n                s2ind++;\n            }\n            else{\n                s2ind++;\n            }\n        }\n        return counter == s1.length();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numMatchingSubseq(string s, vector<string>& words) {\n       int ct=0;\n        unordered_map<string,int>m;\n        \n        for(int i=0;i<words.size();i++)\n        {\n             m[words[i]]++;\n        }\n        \n        \n        for(auto it=m.begin();it!=m.end();it++)\n        {\n            string k=it->first;\n            \n            int z=0;\n            \n            for(int i=0;i<s.length();i++)\n            {\n                if(s[i]==k[z])\n                    z++;\n                else if(z==k.length())\n                    break;\n            }\n            if(z==k.length())\n                ct=ct+it->second;\n            \n        }        \n    return ct;\n    }\n};"
    },
    {
        "title": "Counting Words With a Given Prefix",
        "algo_input": "You are given an array of strings words and a string pref.\n\nReturn the number of strings in words that contain pref as a prefix.\n\nA prefix of a string s is any leading contiguous substring of s.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"pay\",\"attention\",\"practice\",\"attend\"], pref = \"at\"\nOutput: 2\nExplanation: The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".\n\n\nExample 2:\n\nInput: words = [\"leetcode\",\"win\",\"loops\",\"success\"], pref = \"code\"\nOutput: 0\nExplanation: There are no strings that contain \"code\" as a prefix.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length, pref.length &lt;= 100\n\twords[i] and pref consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def prefixCount(self, words: List[str], pref: str) -> int:\n        return sum(word.find(pref) == 0 for word in words)",
        "solution_js": "var prefixCount = function(words, pref) {\n    return words.filter(word => word.slice(0, pref.length) === pref).length;\n};",
        "solution_java": "class Solution {\n    public int prefixCount(String[] words, String pref) {\n    int c = 0;\n    for(String s : words) {\n        if(s.indexOf(pref)==0) \n            c++;\n    }\n    return c; \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int prefixCount(vector<string>& words, string pref) {\n        int c=0;\n        for(auto word:words){\n            int b=0;\n            for(int i=0;i<pref.size();i++){\n                if(word[i]!=pref[i]){\n                    break;\n                }else{\n                    b++;\n                }\n            }\n            if(b==pref.size()){\n                c++;\n            }\n        }\n        return c;\n    }\n};"
    },
    {
        "title": "Erect the Fence",
        "algo_input": "You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.\n\nYou are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.\n\nReturn the coordinates of trees that are exactly located on the fence perimeter.\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\nOutput: [[1,1],[2,0],[3,3],[2,4],[4,2]]\n\n\nExample 2:\n\nInput: points = [[1,2],[2,2],[4,2]]\nOutput: [[4,2],[2,2],[1,2]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 3000\n\tpoints[i].length == 2\n\t0 &lt;= xi, yi &lt;= 100\n\tAll the given points are unique.\n\n",
        "solution_py": "class Solution:\n\n    \"\"\"Compute the convex hull of a set of points.\n\n        Use Andrew's Monotone Chain algorithm, which has order O(N log(N)),\n        where N is the number of input points.\n    \"\"\"\n\n    def cross(self, p, a, b):\n        \"\"\"Return the cross product of the vectors p -> a and p -> b.\"\"\"\n        return (a[0] - p[0]) * (b[1] - p[1]) \\\n            - (a[1] - p[1]) * (b[0] - p[0])\n\n    def _convex_hull_monotone_chain(self, points):\n        \"\"\"Compute the convex hull of a list of points.\n        \n        Use Andrew's Monotone Chain algorithm, which is similar to Graham Scan,\n        except that it doesn't require sorting the points by angle.  This algorithm\n        takes O(N log(N)) time, where N is len(points).\n        \"\"\"\n        # Ensure all points are unique, and sort lexicographically.\n        points = list(sorted(set(points)))\n        \n        # If there are fewer than three points, they must form a hull.\n        if len(points) <= 2:\n            return points\n        \n        # Compute the lower and upper portion of the hull.\n        lower, upper = [], []\n        for out, it in ((lower, points), (upper, reversed(points))):\n            for p in it:\n                while len(out) >= 2 and self.cross(out[-2], out[-1], p) > 0:\n                    out.pop()\n                out.append(p)\n\n        # Concatenate the upper and lower hulls.  Remove the last point from each\n        # because those points are duplicated in both upper and lower.\n        return lower[:-1] + upper[:-1]\n\n    def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        Find the convex hull of a collection of points.\n        Return a list of indices of points forming the hull in clockwise order,\n        starting with the leftmost point.\n        \"\"\"\n        # Convert input points to tuples.\n        points = [tuple(p) for p in trees]\n        ans = set()\n        for point in self._convex_hull_monotone_chain(points):\n            ans.add(point)\n        return ans",
        "solution_js": "const outerTrees = (trees) => {\n    trees.sort((x, y) => {\n        if (x[0] == y[0]) return x[1] - y[1];\n        return x[0] - y[0];\n    });\n    let lower = [], upper = [];\n    for (const tree of trees) {\n        while (lower.length >= 2 && cmp(lower[lower.length - 2], lower[lower.length - 1], tree) > 0) lower.pop();\n        while (upper.length >= 2 && cmp(upper[upper.length - 2], upper[upper.length - 1], tree) < 0) upper.pop();\n        lower.push(tree);\n        upper.push(tree);\n\n    }\n    return [...new Set(lower.concat(upper))];\n};\n\nconst cmp = (p1, p2, p3) => {\n    let [x1, y1] = p1;\n    let [x2, y2] = p2;\n    let [x3, y3] = p3;\n    return (y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2);\n};",
        "solution_java": "class Solution {\n     public static class Pair {\n            int x;\n            int y;\n        \n            Pair(int x, int y) {\n              this.x = x;\n              this.y = y;\n            }\n        \n          }\n    public int[][] outerTrees(int[][] trees) {\n        List<Pair> points=new ArrayList<>();\n        for(int[] point:trees){\n           points.add(new Pair(point[0],point[1])); \n        }\n\n        List<Pair> res=new ArrayList<>();\n        if(points.size()==1){\n            return trees;\n        }\n        int n=points.size();\n        Collections.sort(points,(a,b)->a.y==b.y?a.x-b.x:a.y-b.y);\n        HashSet<ArrayList<Integer>> dup=new HashSet<>();\n        Stack<Pair> hull=new Stack<>();\n        \n        hull.push(points.get(0));\n        hull.push(points.get(1));\n        \n        for(int i=2;i<n;i++){\n            Pair top=hull.pop();\n            while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){\n                top=hull.pop();\n            }\n            hull.push(top);\n            hull.push(points.get(i));\n        }\n        for(int i=n-2;i>=0;i--){\n            Pair top=hull.pop();\n            while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){\n                top=hull.pop();\n            }\n            hull.push(top);\n            hull.push(points.get(i));\n        }\n\n        for(Pair p:hull){\n            ArrayList<Integer> tmp=new ArrayList<>();\n            tmp.add(p.x);\n            tmp.add(p.y);\n            if(dup.contains(tmp))continue;\n            dup.add(tmp);\n            res.add(p);\n        }\n\n        int[][] ans=new int[res.size()][2];\n        int i=0;\n        for(Pair p:res){\n            ans[i][0]=p.x;\n            ans[i][1]=p.y;\n            i++;\n        }\n        \n        return ans;\n        \n    }\n\n    public int ccw(Pair a,Pair b,Pair c){\n        double cp=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\n        if(cp<0)return -1;\n        else if(cp>0)return 1;\n        else return 0;\n    }\n}",
        "solution_c": "class Solution {\n public:\n  vector<vector<int>> outerTrees(vector<vector<int>>& trees) {\n    if (trees.size() <= 1) return trees;\n\n    int origin = 0;\n    for (int i = 0; i < trees.size(); ++i) {\n      if (trees[origin][1] > trees[i][1] || trees[origin][1] == trees[i][1] && trees[origin][0] > trees[i][0]) {\n        origin = i;\n      }\n    }\n    swap(trees[0], trees[origin]);\n    sort(trees.begin() + 1, trees.end(), [&](const vector<int>& lhs, const vector<int>& rhs) -> bool {\n      int result = cross(trees[0], lhs, rhs);\n      if (result != 0) return result > 0;\n      return norm(trees[0], lhs) < norm(trees[0], rhs);\n    });\n\n    // deal with cases that the last k points are on one line\n    int pos = trees.size() - 2;\n    while (pos > 0 && cross(trees[0], trees.back(), trees[pos]) == 0) {\n      --pos;\n    }\n    reverse(trees.begin() + pos + 1, trees.end());\n\n    vector<vector<int>> ans = {trees[0], trees[1]};\n    for (int i = 2; i < trees.size(); ++i) {\n      int cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);\n      while (cross_result < 0) {\n        ans.pop_back();\n        cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);\n      }\n      ans.push_back(trees[i]);\n    }\n    return ans;\n  }\n\n private:\n  inline double norm(const vector<int>& o, const vector<int>& x) {\n    int xx = x[0] - o[0];\n    int yy = x[1] - o[1];\n    return sqrt(xx * xx + yy * yy);\n  }\n\n  inline int cross(const vector<int>& x, const vector<int>& y, const vector<int>& z) {\n    return (y[0] - x[0]) * (z[1] - y[1]) - (y[1] - x[1]) * (z[0] - y[0]);\n  }\n};"
    },
    {
        "title": "Excel Sheet Column Number",
        "algo_input": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.\n\nFor example:\n\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n\n\n&nbsp;\nExample 1:\n\nInput: columnTitle = \"A\"\nOutput: 1\n\n\nExample 2:\n\nInput: columnTitle = \"AB\"\nOutput: 28\n\n\nExample 3:\n\nInput: columnTitle = \"ZY\"\nOutput: 701\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= columnTitle.length &lt;= 7\n\tcolumnTitle consists only of uppercase English letters.\n\tcolumnTitle is in the range [\"A\", \"FXSHRXW\"].\n\n",
        "solution_py": "def let_to_num(char):\n    abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    return abc.index(char) + 1\n\nclass Solution:\n    def titleToNumber(self, columnTitle: str) -> int:\n        ans = 0\n        for i in range(len(columnTitle)):\n            ans *= 26\n            ans += let_to_num(columnTitle[i])\n        return ans",
        "solution_js": "/**\n * @param {string} columnTitle\n * @return {number}\n */\nvar titleToNumber = function(columnTitle) {\n    /*\n        one letter: result between 1-26.\n        two letter: result between 26^1 + 1 -> 26^2 + digit. 27 - 702. All the combinations of A-Z and A-Z. \n    */\n    \n    let sum = 0;\n    for (let letter of columnTitle) {\n        let d = letter.charCodeAt(0) - 'A'.charCodeAt(0) + 1;\n        sum = sum * 26 + d;\n    }\n    \n    return sum;\n};",
        "solution_java": "class Solution {\n    public int titleToNumber(String columnTitle) {\n        int n = columnTitle.length();\n        int pow = 0;\n        int res = 0;\n        for(int i = n-1; i >= 0; i--) {\n            char c = columnTitle.charAt(i);\n            res += (c - 64) * Math.pow(26, pow);\n            pow++;\n        }\n\n        return res;\n    }\n}",
        "solution_c": "\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n    int titleToNumber(string columnTitle) {\n        int result = 0;\n        for(char c : columnTitle)\n        {\n\t\t\t//d = s[i](char) - 'A' + 1 (we used  s[i] -  'A' to convert the letter to a number like it's going to be C)\n\n            int d = c - 'A' + 1;\n            result = result * 26 + d;\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Fancy Sequence",
        "algo_input": "Write an API that generates fancy sequences using the append, addAll, and multAll operations.\n\nImplement the Fancy class:\n\n\n\tFancy() Initializes the object with an empty sequence.\n\tvoid append(val) Appends an integer val to the end of the sequence.\n\tvoid addAll(inc) Increments all existing values in the sequence by an integer inc.\n\tvoid multAll(m) Multiplies all existing values in the sequence by an integer m.\n\tint getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\nOutput\n[null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n\nExplanation\nFancy fancy = new Fancy();\nfancy.append(2);   // fancy sequence: [2]\nfancy.addAll(3);   // fancy sequence: [2+3] -&gt; [5]\nfancy.append(7);   // fancy sequence: [5, 7]\nfancy.multAll(2);  // fancy sequence: [5*2, 7*2] -&gt; [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3);   // fancy sequence: [10+3, 14+3] -&gt; [13, 17]\nfancy.append(10);  // fancy sequence: [13, 17, 10]\nfancy.multAll(2);  // fancy sequence: [13*2, 17*2, 10*2] -&gt; [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= val, inc, m &lt;= 100\n\t0 &lt;= idx &lt;= 105\n\tAt most 105 calls total will be made to append, addAll, multAll, and getIndex.\n\n",
        "solution_py": "def egcd(a, b):\n    if a == 0:\n        return (b, 0, 1)\n    else:\n        g, y, x = egcd(b % a, a)\n        return (g, x - (b // a) * y, y)\n\ndef modinv(a, m):\n    g, x, y = egcd(a, m)\n    return x % m\n\nmod = 1000000007\n\nclass Fancy(object):\n\n    def __init__(self):\n        self.seq = []\n        self.addC = 0\n        self.mulC = 1\n        \n    def append(self, val):\n        \"\"\"\n        :type val: int\n        :rtype: None\n        \"\"\"\n        self.seq.append([val, self.mulC, self.addC])\n        \n\n    def addAll(self, inc):\n        \"\"\"\n        :type inc: int\n        :rtype: None\n        \"\"\"\n        self.addC = (self.addC%mod + inc%mod)%mod\n\n    def multAll(self, m):\n        \"\"\"\n        :type m: int\n        :rtype: None\n        \"\"\"\n        self.mulC = (self.mulC%mod * m%mod)%mod\n        self.addC = (self.addC%mod * m%mod)%mod\n        \n\n    def getIndex(self, idx):\n        \"\"\"\n        :type idx: int\n        :rtype: int\n        \"\"\"\n        if(idx >= len(self.seq)):\n            return -1\n        \n        mulCo = self.seq[idx][1]\n        addCo = self.seq[idx][2]\n        val = self.seq[idx][0]\n        \n        inv = modinv(mulCo, mod)\n        a = (self.mulC%mod * inv%mod)%mod\n        val = (val%mod * a%mod)%mod\n        b = (addCo%mod * a%mod)%mod\n        val = (val%mod - b%mod)%mod\n        val = (val%mod + self.addC%mod)%mod\n        \n        return val",
        "solution_js": "var Fancy = function() {\n    this.sequence = [];\n    this.appliedOps = [];\n    this.ops = [];\n    this.modulo = Math.pow(10, 9) + 7;\n};\n\n/**\n * @param {number} val\n * @return {void}\n */\nFancy.prototype.append = function(val) {\n    this.sequence.push(val);\n    this.appliedOps.push(this.ops.length);\n};\n\n/**\n * @param {number} inc\n * @return {void}\n */\nFancy.prototype.addAll = function(inc) {\n    this.ops.push(['add', inc]);\n};\n\n/**\n * @param {number} m\n * @return {void}\n */\nFancy.prototype.multAll = function(m) {\n    this.ops.push(['mult', m]);\n};\n\n/**\n * @param {number} idx\n * @return {number}\n */\nFancy.prototype.getIndex = function(idx) {\n    if (idx >= this.sequence.length) {\n        return -1;\n    }\n\n    while (this.appliedOps[idx] < this.ops.length) {\n        const [operation, value] = this.ops[this.appliedOps[idx]];\n        this.appliedOps[idx]++;\n\n        if (operation === 'mult') {\n            this.sequence[idx] = (this.sequence[idx] * value) % this.modulo;\n        }\n\n        if (operation === 'add') {\n            this.sequence[idx] = (this.sequence[idx] + value) % this.modulo;\n        }\n    }\n\n    return this.sequence[idx];\n};\n\n/**\n * Your Fancy object will be instantiated and called as such:\n * var obj = new Fancy()\n * obj.append(val)\n * obj.addAll(inc)\n * obj.multAll(m)\n * var param_4 = obj.getIndex(idx)\n */",
        "solution_java": "class Fancy {\n    private ArrayList<Long> lst;\n    private ArrayList<Long> add;\n    private ArrayList<Long> mult;\n    private final long MOD = 1000000007;\n\n    public Fancy() {\n        lst = new ArrayList<>();\n        add = new ArrayList<>();\n        mult = new ArrayList<>();\n        add.add(0L);\n        mult.add(1L);\n    }\n\n    public void append(int val) {\n        lst.add((long) val);\n        int l = add.size();\n        add.add(add.get(l - 1));\n        mult.add(mult.get(l - 1));\n    }\n\n    public void addAll(int inc) {\n       int l = add.size();\n       add.set(l - 1, add.get(l - 1) + inc);\n    }\n\n    public void multAll(int m) {\n        int l = add.size();\n        add.set(l - 1, (add.get(l - 1) * m) % MOD);\n        mult.set(l - 1, (mult.get(l - 1) * m) % MOD);\n    }\n\n    public int getIndex(int idx) {\n        if (idx >= lst.size()) return -1;\n\n        int l = add.size();\n        long m = (mult.get(l - 1) * inverse(mult.get(idx))) % MOD;\n        long a = (add.get(l - 1) - (add.get(idx) * m) % MOD + MOD) % MOD;\n        return (int) (((lst.get(idx) * m) % MOD + a) % MOD);\n    }\n\n    long inverse(long a) {\n        return pow(a, MOD - 2);\n    }\n\n    long pow(long a, long n) {\n        if (n == 0) return 1;\n        if (n % 2 == 0) {\n            long t = pow(a, n / 2);\n            return (t * t) % MOD;\n        } else {\n            return (pow(a, n - 1) * a) % MOD;\n        }\n    }\n}",
        "solution_c": "int mod97 = 1000000007;\n/**\nCalculates multiplicative inverse\n*/\nunsigned long modPow(unsigned long x, int y) {\n        unsigned long tot = 1, p = x;\n        for (; y; y >>= 1) {\n            if (y & 1)\n                tot = (tot * p) % mod97;\n            p = (p * p) % mod97;\n        }\n        return tot;\n    }\nclass Fancy {\npublic:\n    unsigned long seq[100001];\n    unsigned int length = 0;\n    unsigned long increment = 0;\n    unsigned long mult = 1;\n    Fancy() {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n    }\n    \n    void append(int val) {\n        seq[length++] = (((mod97 + val - increment)%mod97) * modPow(mult, mod97-2))%mod97;\n    }\n    void addAll(int inc) {\n        increment = (increment+ inc%mod97)%mod97;\n    }\n    \n    void multAll(int m) {\n        mult = (mult* m%mod97)%mod97;\n        increment = (increment* m%mod97)%mod97;\n    }\n    \n    int getIndex(int idx) {\n        \n        if (idx >= length){\n            return -1;\n        }else{\n            return ((seq[idx] * mult)%mod97+increment)%mod97;\n        }\n    }\n};"
    },
    {
        "title": "Replace Elements in an Array",
        "algo_input": "You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].\n\nIt is guaranteed that in the ith operation:\n\n\n\toperations[i][0] exists in nums.\n\toperations[i][1] does not exist in nums.\n\n\nReturn the array obtained after applying all the operations.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\nOutput: [3,2,7,1]\nExplanation: We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].\n\n\nExample 2:\n\nInput: nums = [1,2], operations = [[1,3],[2,1],[3,2]]\nOutput: [2,1]\nExplanation: We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\tm == operations.length\n\t1 &lt;= n, m &lt;= 105\n\tAll the values of nums are distinct.\n\toperations[i].length == 2\n\t1 &lt;= nums[i], operations[i][0], operations[i][1] &lt;= 106\n\toperations[i][0] will exist in nums when applying the ith operation.\n\toperations[i][1] will not exist in nums when applying the ith operation.\n\n",
        "solution_py": "class Solution:\n    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:\n            replacements = {}\n            for x, y in reversed(operations):\n                replacements[x] = replacements.get(y, y)\n            for idx, val in enumerate(nums):\n                if val in replacements:\n                    nums[idx] = replacements[val]\n            return nums",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number[][]} operations\n * @return {number[]}\n */\nvar arrayChange = function(nums, operations) {\n    let map = new Map()\n\n    for(let i = 0; i < nums.length; i++){\n        let num = nums[i]\n        map.set(num, i)\n    }\n\n    for(let op of operations){\n        let key = op[0]\n        let value = op[1]\n\n        // if key exists\n        if(map.has(key)){\n            const idx = map.get(key)\n            map.set(value, idx)\n            map.delete(key)\n        }\n    }\n\n    for(let [key, idx] of map){\n        nums[idx] = key\n    }\n\n    return nums\n\n};",
        "solution_java": "class Solution {\n    public int[] arrayChange(int[] nums, int[][] operations) {\n        Map<Integer,Integer> map = new HashMap<>();\n        for(int i=0;i<nums.length;i++) map.put(nums[i],i);\n        for(int[] op: operations) {\n            nums[map.get(op[0])] = op[1];\n            map.put(op[1],map.get(op[0]));\n            map.remove(op[0]);\n        }\n        return nums;\n    }\n}",
        "solution_c": "int m[1000001];\nclass Solution {\npublic:\nvector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {\n    for (int i = 0; i < nums.size(); ++i)\n        m[nums[i]] = i;\n    for (auto &op : operations) {\n        nums[m[op[0]]] = op[1];\n        m[op[1]] = m[op[0]];\n    }\n    return nums;\n}\n};"
    },
    {
        "title": "Two City Scheduling",
        "algo_input": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti],&nbsp;the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.\n\nReturn the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n\n&nbsp;\nExample 1:\n\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n\n\nExample 2:\n\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\n\n\nExample 3:\n\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n\n\n&nbsp;\nConstraints:\n\n\n\t2 * n == costs.length\n\t2 &lt;= costs.length &lt;= 100\n\tcosts.length is even.\n\t1 &lt;= aCosti, bCosti &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n        n = len(costs)\n        m = n // 2\n        \n        @lru_cache(None)\n        def dfs(cur, a):\n\t\t\t# cur is the current user index\n\t\t\t# `a` is the number of people travel to city `a`\n\t\t\t\n            if cur == n:\n                return 0\n            \n\t\t\t# people to b city\n            b = cur - a\n            ans = float('inf')\n            \n\t\t\t# the number of people to `a` city number did not reach to limit, \n\t\t\t# then current user can trval to city `a`\n\t\t\t\n            if a < m:\n                ans = min(dfs(cur+1, a+1)+costs[cur][0], ans)\n            \n\t\t\t# the number of people to `b` city number did not reach to limit\n\t\t\t# then current user can trval to city `b`\n            if b < m:\n                ans = min(dfs(cur+1, a)+costs[cur][1], ans)\n                \n            return ans\n        \n        return dfs(0, 0)",
        "solution_js": "/**\n * @param {number[][]} costs\n * @return {number}\n */\nvar twoCitySchedCost = function(costs) {\n    // TC: O(nlogn) and O(1) extra space\n    let n=costs.length;\n    let countA=0,countB=0,minCost=0;\n    \n    // sorted in descending order by their absolute diff\n    costs=costs.sort((a,b)=>{\n        let diffA=Math.abs(a[0] - a[1]);\n        let diffB=Math.abs(b[0] - b[1]);\n        return diffB-diffA;\n    });\n    \n    for(let i=0;i<n;i++){\n        let [a,b]=costs[i];\n        if(a<b){\n            if(countA<n/2){\n                minCost+=a;\n                countA++;\n            }else{\n                minCost+=b;\n                countB++;\n            }\n        }else{\n            if(countB<n/2){\n                minCost+=b;\n                countB++;\n            }else{\n                minCost+=a;\n                countA++;\n            }\n        }\n    }\n    return minCost;\n};",
        "solution_java": "// costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\n//  The difference between them would be like this [511,  -394, -259, -45, -722, -108]  this will give us the differnce c[1] - c[0]\n// Now after sorting them from highest to smallest would be [511, -45, -108, -259, -394,-722] from high to low c2[1] - c2[0], c1[1] - c1[0]  if we want low to high then it would be like this c1[1] - c1[0], c2[1] - c2[0]\n// \n\nclass Solution {\n    public int twoCitySchedCost(int[][] costs) {\n       Arrays.sort(costs, (c1, c2) -> Integer.compare(c2[1] - c2[0], c1[1] - c1[0]));// biggest to smallest\n        int minCost = 0;               \n        int n = costs.length;\n        for (int i = 0; i < n; i++) {\n            minCost += i < n/2? costs[i][0] : costs[i][1];//First half -> A; Last half -> B  259 + 184 + 577 + 54 + 667 + 118\n        }\n        return minCost;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int twoCitySchedCost(vector<vector<int>>& costs) {\n        sort(costs.begin(), costs.end(), [](const vector<int> &curr, const vector<int> &next){ // CUSTOM COMPARATOR\n            return (curr[0]-curr[1]) < (next[0]-next[1]);   // (comparing cost of sending to A - cost to B)\n        });\n        // original:   [[10,20],[30,200],[400,50],[30,20]] \n        // after sort: [[30,200],[10,20],[30,20],[400,50]]\n        // to do:         a       a          b         b\n        \n        int sum = 0;\n        for(int i=0; i<costs.size()/2; i++){\n            sum+=costs[i][0];\n            // cout<<costs[i][0]<<\" \"; // 30 10\n        }\n        for(int i=costs.size()/2; i<costs.size(); i++){\n            sum+=costs[i][1];\n            // cout<<costs[i][1]<<\" \"; // 20 50\n        }\n        \n        return sum;\n    }\n};"
    },
    {
        "title": "Remove All Adjacent Duplicates in String II",
        "algo_input": "You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.\n\nWe repeatedly make k duplicate removals on s until we no longer can.\n\nReturn the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcd\", k = 2\nOutput: \"abcd\"\nExplanation: There's nothing to delete.\n\nExample 2:\n\nInput: s = \"deeedbbcccbdaa\", k = 3\nOutput: \"aa\"\nExplanation: \nFirst delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"\n\nExample 3:\n\nInput: s = \"pbbcggttciiippooaais\", k = 2\nOutput: \"ps\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\t2 &lt;= k &lt;= 104\n\ts only contains lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def removeDuplicates(self, s: str, k: int) -> str:\n        stack=[]\n        res=''\n        for i in range(len(s)):\n            if len(stack)==0:\n                stack.append([s[i],1])\n            elif stack[-1][0]==s[i]:\n                stack[-1][1]=stack[-1][1]+1\n            else:\n                stack.append([s[i],1])\n            if stack[-1][1]==k:\n                stack.pop()\n        for i in range(len(stack)):\n            res+=stack[i][0]*stack[i][1]\n        return res",
        "solution_js": "var removeDuplicates = function(s, k) {\n  const stack = []\n  for(const c of s){\n    const obj = {count: 1, char: c}\n    if(!stack.length){\n      stack.push(obj)\n      continue\n    }\n    const top = stack[stack.length-1]\n    if(top.char === obj.char && obj.count + top.count === k){\n      let count = k\n      while(count > 1){\n        stack.pop()\n        count--\n      }\n    }else if(top.char === obj.char){\n      obj.count+=top.count\n      stack.push(obj)\n    }else{\n      stack.push(obj)\n    }\n  }\n  return stack.reduce((a,b)=> a+b.char, '')\n};",
        "solution_java": "class Solution\n{\n    public String removeDuplicates(String s, int k)\n    {\n        int i = 0 ;\n        StringBuilder newString = new StringBuilder(s) ;\n        int[] count = new int[newString.length()] ;\n        while( i < newString.length() )\n        {\n            if( i == 0 || newString.charAt(i) != newString.charAt( i - 1 ) )\n            {\n                count[i] = 1 ;\n            }\n            else\n            {\n                count[i] = count[ i - 1 ] + 1 ;\n                if( count[i] == k )\n                {\n                    newString.delete( i - k + 1 , i + 1 ) ;\n                    i = i - k ;\n                }\n            }\n            i++ ;\n        }\n        return newString.toString() ;\n    }\n}",
        "solution_c": "#define pp pair< int , char > \n\nclass Solution {\npublic:\n    string removeDuplicates(string s, int k) {\n        \n        int n=s.size();\n        \n        stack< pp > stk;\n        \n        int i=0;\n        \n        while(i<n)\n        {\n            int count=1;\n            \n            char ch=s[i];\n            \n            while((i+1)<n && s[i]==s[i+1])\n            {\n                i++;\n                count++;\n            }\n         \n            int c=0;\n            \n            if(!stk.empty() && stk.top().second==ch)\n            {\n                c+=stk.top().first;\n                stk.pop();\n            }\n            \n            count+=c;\n            \n            count=count%k;\n            \n            if(count!=0)\n            {\n                stk.push({count , ch});\n            }\n            \n            i++;\n            \n            \n        }\n        \n        string str=\"\";\n        \n        while(!stk.empty())\n        {\n            int count=stk.top().first;\n            \n            while(count--)\n            {\n                str.push_back(stk.top().second);\n            }\n            \n            stk.pop();\n        }\n        \n        reverse(str.begin() , str.end());\n        \n        return str;\n        \n    }\n};"
    },
    {
        "title": "Roman to Integer",
        "algo_input": "Roman numerals are represented by seven different symbols:&nbsp;I, V, X, L, C, D and M.\n\nSymbol       Value\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000\n\nFor example,&nbsp;2 is written as II&nbsp;in Roman numeral, just two ones added together. 12 is written as&nbsp;XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.\n\nRoman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:\n\n\n\tI can be placed before V (5) and X (10) to make 4 and 9.&nbsp;\n\tX can be placed before L (50) and C (100) to make 40 and 90.&nbsp;\n\tC can be placed before D (500) and M (1000) to make 400 and 900.\n\n\nGiven a roman numeral, convert it to an integer.\n\n&nbsp;\nExample 1:\n\nInput: s = \"III\"\nOutput: 3\nExplanation: III = 3.\n\n\nExample 2:\n\nInput: s = \"LVIII\"\nOutput: 58\nExplanation: L = 50, V= 5, III = 3.\n\n\nExample 3:\n\nInput: s = \"MCMXCIV\"\nOutput: 1994\nExplanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 15\n\ts contains only&nbsp;the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').\n\tIt is guaranteed&nbsp;that s is a valid roman numeral in the range [1, 3999].\n\n",
        "solution_py": "class Solution:\n    def romanToInt(self, s: str) -> int:\n        roman = {\n            \"I\": 1,\n            \"V\": 5,\n            \"X\": 10,\n            \"L\": 50,\n            \"C\": 100,\n            \"D\": 500,\n            \"M\": 1000\n        }\n\n        sum = 0;\n        for i in range(0, len(s) - 1):\n            curr = roman[s[i]]\n            nxt = roman[s[i + 1]]\n            if curr < nxt:\n                sum -= curr\n            else:\n                sum += curr\n        sum += roman[s[-1]]\n        return sum",
        "solution_js": "var romanToInt = function(s) {\n      const sym = {\n        'I': 1,\n        'V': 5,\n        'X': 10,\n        'L': 50,\n        'C': 100,\n        'D': 500,\n        'M': 1000\n    }\n\n    let result = 0;\n\n    for (let i = 0; i < s.length; i++) {\n        const cur = sym[s[i]];\n        const next = sym[s[i + 1]];\n\n        if (cur < next) {\n            result += next - cur;\n            i++;\n        } else {\n            result += cur;\n        }\n    }\n\n    return result;\n};",
        "solution_java": "class Solution {\n    public int romanToInt(String s) {\n        int res=0;\n        // Let s = \"IV\" after traversing string res will be 6\n        // Let s= \"IX\" after traversing string res will be 11\n        for(int i=0;i<s.length();i++){\n            switch(s.charAt(i)){\n                case 'I': res=res+1;\n                    break;\n                case 'V': res=res+5;\n                    break;\n                case 'X': res+=10;\n                    break;\n                case 'L': res+=50;\n                    break;\n                case 'C': res+=100;\n                    break;\n                case 'D': res+=500;\n                    break;\n                case 'M': res+=1000;\n                    break;\n            }\n        }\n        // Since s= \"IV\" it satisfies first condition and 2 is subtracted from res. res=4\n        // Since s= \"IX\" it satisfies first condition and 2 is subtracted from res. res=9\n        if(s.contains(\"IV\")||s.contains(\"IX\"))\n            res=res-2;\n        if(s.contains(\"XL\")||s.contains(\"XC\"))\n            res=res-20;\n        if(s.contains(\"CD\")||s.contains(\"CM\"))\n            res=res-200;\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int romanToInt(string s){\n        unordered_map<char, int> T = { { 'I' , 1 },\n        { 'V' , 5 },\n        { 'X' , 10 },\n        { 'L' , 50 },\n        { 'C' , 100 },\n        { 'D' , 500 },\n        { 'M' , 1000 } };\n        int sum = T[s.back()];\n        for (int i = s.length() - 2; i >= 0; --i){\n            if (T[s[i]] < T[s[i + 1]]) sum -= T[s[i]];\n            else sum += T[s[i]];\n        }\n        return sum;\n    }\n};"
    },
    {
        "title": "Palindrome Number",
        "algo_input": "Given an integer x, return true if x is palindrome integer.\n\nAn integer is a palindrome when it reads the same backward as forward.\n\n\n\tFor example, 121 is a palindrome while 123 is not.\n\n\n&nbsp;\nExample 1:\n\nInput: x = 121\nOutput: true\nExplanation: 121 reads as 121 from left to right and from right to left.\n\n\nExample 2:\n\nInput: x = -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n\n\nExample 3:\n\nInput: x = 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n\n\n&nbsp;\nConstraints:\n\n\n\t-231&nbsp;&lt;= x &lt;= 231&nbsp;- 1\n\n\n&nbsp;\nFollow up: Could you solve it without converting the integer to a string?",
        "solution_py": "class Solution(object):\n   def isPalindrome(self,x):\n       return str(x) == str(x)[::-1]",
        "solution_js": "var isPalindrome = function(x) {\n    if(x < 0 || x % 10 === 0 && x !== 0) return false\n\n    let num = x\n    let rev_x = 0\n\n    while(x > 0){\n        let digit = Math.floor(x % 10)\n        rev_x = Math.floor(rev_x * 10 + digit)\n        x = Math.floor(x / 10)\n    }\n    return num === rev_x\n};",
        "solution_java": "class Solution {\n    public boolean isPalindrome(int x) {\n        int sum = 0;\n        int X = x;\n\n        while(x > 0){\n            sum = 10 * sum + x % 10;\n            x /= 10;\n        }\n\n        return sum == X;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPalindrome(int x) {\n        if (x < 0) {\n            return false;\n        }\n\n        long long reversed = 0;\n        long long temp = x;\n\n        while (temp != 0) {\n            int digit = temp % 10;\n            reversed = reversed * 10 + digit;\n            temp /= 10;\n        }\n\n        return (reversed == x);\n    }\n};"
    },
    {
        "title": "Number of Good Leaf Nodes Pairs",
        "algo_input": "You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.\n\nReturn the number of good leaf node pairs in the tree.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,null,4], distance = 3\nOutput: 1\nExplanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\n\n\nExample 2:\n\nInput: root = [1,2,3,4,5,6,7], distance = 3\nOutput: 2\nExplanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\n\n\nExample 3:\n\nInput: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput: 1\nExplanation: The only good pair is [2,5].\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 210].\n\t1 &lt;= Node.val &lt;= 100\n\t1 &lt;= distance &lt;= 10\n\n",
        "solution_py": "class Solution:\n    def countPairs(self, root: TreeNode, distance: int) -> int:\n        adjList=defaultdict(list)\n        leaves=[]\n        ct=0\n        \n        [#undirected graph two way using parent and node in postorder style]\n        def dfs(node, parent):\n            if node:\n                if not node.left and not node.right:\n                    leaves.append(node)\n                adjList[node].append(parent)\n                adjList[parent].append(node)\n                dfs(node.left,node)\n                dfs(node.right,node)\n        \n        [#construct graph and get all the leaves]\n        dfs(root, None)\n        \n        #bfs from each leaf till we find another leaf\n        for leaf in leaves:\n            q=deque([(leaf,0)] )\n            seen=set()\n            while q:\n                curr,dist = q.popleft()\n                seen.add(curr)\n                if dist>distance:\n                    break                \n                for nbr in adjList[curr]:\n                    if nbr and nbr not in seen:\n                        if nbr in leaves and dist+1<=distance:\n                            ct+=1\n                        q.append((nbr,dist+1))\n        \n        return ct//2",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} distance\n * @return {number}\n */\nvar countPairs = function(root, distance) {\n    var graph = new Map()\n    var leaves = new Map()\n    function dfs(root, parent) {\n        if (!root) return \n        if (!root.left && !root.right) {\n            leaves.set(root, true)\n        }\n\n        graph.set(root, [])\n        if (root.left) {\n            graph.get(root).push(root.left)\n        }\n        if (root.right) {\n            graph.get(root).push(root.right)\n        }\n        if (parent) {\n            graph.get(root).push(parent)\n        }\n        dfs(root.left, root)\n        dfs(root.right, root)\n    }  \n\n    dfs(root, null)\n\n    var visited = new Map()\n    var count = 0\n\n    function bfs(start, dis) {\n        visited.set(start, true)\n        var queue = [graph.get(start).filter(node => !visited.has(node))]\n\n        var innerVisited = new Map()\n\n        while (queue.length) {\n            var curLevelNodes = queue.shift()\n\n            if (!curLevelNodes.length) break\n            if (dis === 0) break\n\n            var nextLevelNodes = []\n            for (var i = 0; i < curLevelNodes.length; i++) {\n                var curLevelNode = curLevelNodes[i]\n\n                innerVisited.set(curLevelNode, true)\n\n                if (leaves.has(curLevelNode)) {\n                    count++\n                }\n\n                nextLevelNodes.push(\n                    ...graph\n                        .get(curLevelNode)\n                        .filter(node => \n                            !visited.has(node) && \n                            !innerVisited.has(node)\n                        )\n                )\n               \n            }\n            queue.push(nextLevelNodes)\n            dis--\n        }\n    }\n\n    leaves.forEach((value, leaf) => {\n        bfs(leaf, distance)\n    })\n\n    return count\n};",
        "solution_java": "class Solution {\n    static int res;\n    public int countPairs(TreeNode root, int distance) {\n        res=0;\n        rec(root,distance);\n        return res;\n    }\n    static List<Integer> rec(TreeNode root,int dist){\n        if(root==null){\n            return new LinkedList<Integer>();\n        }\n        List<Integer> left=rec(root.left,dist);\n        List<Integer> right=rec(root.right,dist);\n        if(left.size()==0&&right.size()==0){\n            List<Integer> temp=new LinkedList<>();\n            temp.add(1);\n            return temp;\n        }\n        for(int i:left){\n            for(int j:right){\n                if(i+j<=dist){\n                    res++;\n                }\n            }\n        }\n        List<Integer> temp=new LinkedList<>();\n        for(int i:left){\n            temp.add(i+1);\n        }\n        for(int i:right){\n            temp.add(i+1);\n        }\n        return temp;\n    }\n}",
        "solution_c": "class Solution {\n    vector<TreeNode*> leaves;\n    unordered_map<TreeNode* , TreeNode*> pof;\n    void makeGraph(unordered_map<TreeNode* , TreeNode*> &pof, TreeNode* root){\n        if(!root) return;\n        if(!root->left && !root->right){\n            leaves.push_back(root);\n            return;\n        }\n        if(root->left) pof[root->left]=root;\n        if(root->right) pof[root->right]=root;\n        makeGraph(pof, root->left);\n        makeGraph(pof, root->right);\n    }\npublic:\n    int countPairs(TreeNode* root, int distance) {\n        leaves={};\n        makeGraph(pof, root);\n        int ans=0;\n        queue<pair<TreeNode*, int>> q;\n        for(auto &l: leaves){\n            q.push({l, 0}); \n            unordered_set<TreeNode*> isVis;\n            while(q.size()){\n                auto [cur, dist]=q.front();\n                q.pop();\n                if(isVis.count(cur) || dist>distance) continue;\n                isVis.insert(cur);\n                if(!cur->left && !cur->right && cur!=l && dist<=distance){\n                    ans++;\n                    continue;\n                }\n                if(cur->left && !isVis.count(cur->left)) q.push({cur->left, dist+1});\n                if(cur->right && !isVis.count(cur->right)) q.push({cur->right, dist+1});\n                if(pof.count(cur) && !isVis.count(pof[cur])) q.push({pof[cur], dist+1});\n            }\n        }\n        return ans>>1;\n    }\n};"
    },
    {
        "title": "Single Element in a Sorted Array",
        "algo_input": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.\n\nReturn the single element that appears only once.\n\nYour solution must run in O(log n) time and O(1) space.\n\n&nbsp;\nExample 1:\nInput: nums = [1,1,2,3,3,4,4,8,8]\nOutput: 2\nExample 2:\nInput: nums = [3,3,7,7,10,11,11]\nOutput: 10\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def singleNonDuplicate(self, nums: List[int]) -> int:\n        return self.b_search(nums)[0]\n    \n    def b_search(self, nums):\n        if len(nums) == 1:\n            return nums\n        mid = len(nums)//2\n        a = nums[:mid]\n        b = nums[mid:]\n\t\t\n\t\t# check if last & first element of the two sub lists are same\n        if a[-1] == b[0]:\n            a = a[:-1]\n            b = b[1:]\n\t\t\n\t\t# ignore the sub list with even number of elements\n        if len(a)%2:\n            return self.b_search(a)\n        else:\n            return self.b_search(b)",
        "solution_js": "var singleNonDuplicate = function(nums) {\n    var start = 0;\n    var end = nums.length - 1\n    // to check one element\n     if (nums.length == 1) return nums[start]\n     while(start <= end) {\n        if(nums[start] != nums[start + 1]) {\n            return nums[start] }\n\n          if(nums[end] != nums[end - 1]) {\n            return nums[end]\n        }\n        // increment two point\n        start = start + 2;\n        end = end - 2;\n\n    }\n};",
        "solution_java": "class Solution {\n    public int singleNonDuplicate(int[] nums) {\n        if(nums.length==1) return nums[0];\n        int l = 0;\n        int h = nums.length-1;\n        \n        while(l<h){\n            int mid = l+(h-l)/2;      // divide the array\n            \n            if(nums[mid]==nums[mid+1]) mid = mid-1;      //two same elements should be in same half\n            \n            if((mid-l+1)%2!=0) h = mid;            // checking the length of left half. If its is odd then update ur right pointer to mid\n            \n            else l = mid+1;    // else your right half will be odd then update your left pointer to mid+1\n        }\n        \n        return nums[l];     //left pointer will have the answer at last\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int singleNonDuplicate(vector<int>& nums) {\n        int ans=0;\n        for(int i=0; i<nums.size();i++){\n            ans=ans^nums[i];\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Cost of Buying Candies With Discount",
        "algo_input": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.\n\nThe customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.\n\n\n\tFor example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they&nbsp;can take the candy with cost 1 for free, but not the candy with cost 4.\n\n\nGiven a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.\n\n&nbsp;\nExample 1:\n\nInput: cost = [1,2,3]\nOutput: 5\nExplanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.\n\n\nExample 2:\n\nInput: cost = [6,5,7,9,2,2]\nOutput: 23\nExplanation: The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.\n\n\nExample 3:\n\nInput: cost = [5,5]\nOutput: 10\nExplanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= cost.length &lt;= 100\n\t1 &lt;= cost[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minimumCost(self, cost: List[int]) -> int:\n        cost.sort(reverse=True)\n        res, i, N = 0, 0, len(cost)\n        while i < N:\n            res += sum(cost[i : i + 2])\n            i += 3\n        return res",
        "solution_js": "var minimumCost = function(cost) {\n    if (cost.length < 3) {\n        return cost.reduce((prev, cur) => prev + cur);\n    }\n\n    cost.sort((a, b) => b - a);\n    let count = 0;\n    let sum = 0;\n\n    for (const num of cost) {\n        if (count === 2) {\n            count = 0;\n            continue;\n        }\n        sum += num;\n        count++;\n    }\n\n    return sum;\n};",
        "solution_java": "class Solution {\n    /** Algorithm\n     * 1. Sort the cost array.\n     * 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.\n     * 3. Decrement the position by 3 and continue. stop when you reach 1.\n     * 4. From 1, add the remaining 1 or 2 items.\n     *\n     */\n    public int minimumCost(int[] cost) {\n        int minCost = 0;\n        int index = cost.length -1;\n        Arrays.sort(cost);\n        // add items in pairs of 2, the 3rd one getting it for free.\n        while (index > 1) {\n            minCost += cost[index] + cost[index -1];\n            index -= 3;\n        }\n        // add the remaining 1, 2 items, if any.\n        while(index >= 0) {\n            minCost += cost[index--];\n        }\n        return minCost;\n    }\n}",
        "solution_c": "//Solution 01:\nclass Solution {\npublic:\n    int minimumCost(vector<int>& cost) {\n        int n = cost.size();\n        int i = n-1, ans = 0;\n\n        if(n <= 2){\n            for(auto x: cost)\n                ans += x;\n            return ans;\n        }\n\n        sort(cost.begin(), cost.end());\n\n        while(i>=1){\n            ans += cost[i] + cost[i-1];\n            if(i-1 == 0 || i-1 == 1) return ans;\n            i = i-3;\n        }\n        ans += cost[0];\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Check Completeness of a Binary Tree",
        "algo_input": "Given the root of a binary tree, determine if it is a complete binary tree.\n\nIn a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,6]\nOutput: true\nExplanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\n\n\nExample 2:\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: false\nExplanation: The node with value 7 isn't as far left as possible.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t1 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution:\n\tdef isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n\t\t# if not root: return True\n\t\tdef node_count(root):\n\t\t\tif not root: return 0\n\t\t\treturn 1 + node_count(root.left) + node_count(root.right)\n\n\t\tdef isCBT(root,i,count):\n\t\t\tif not root: return True\n\t\t\tif i>=count: return False\n\t\t\treturn isCBT(root.left,2*i+1,count) and isCBT(root.right,2*i+2,count)\n\n\n\t\treturn isCBT(root,0,node_count(root))",
        "solution_js": "var isCompleteTree = function(root) {\nlet queue = [root];\nlet answer = [root];\nwhile(queue.length > 0) {\n    let current = queue.shift();\n    if(current) {\n        queue.push(current.left);\n        answer.push(current.left);\n        queue.push(current.right);\n        answer.push(current.right);\n    }\n}\n\nconsole.log(\"queue\", queue);\n\nwhile(answer.length > 0 ) {\n    let current = answer.shift();\n    if(current === null) break;\n}\nconsole.log(\"answer after shifting\", answer);\n let flag = true;\n for(let current of answer) {\n    if(current !== null) {\n        flag = false;\n        break\n    }\n}\n\nreturn flag\n};",
        "solution_java": "class Solution {\n    public boolean isCompleteTree(TreeNode root) {\n        boolean end = false;\n        Queue<TreeNode> queue = new LinkedList<>();\n        queue.offer(root);\n        while(!queue.isEmpty()) {\n            TreeNode currentNode = queue.poll();\n            if(currentNode == null) {\n                end = true;\n            } else {\n                if(end) {\n                    return false;\n                }\n                queue.offer(currentNode.left);\n                queue.offer(currentNode.right);\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isComplete = true;\n\n    // Returns min, max height of node\n    pair<int,int> helper(TreeNode *root){\n        // NULL is of height zero\n        if(root == NULL){\n            return {0, 0};\n        }\n\n        // Moving to its children\n        pair<int,int> lst = helper(root->left);\n        pair<int,int> rst = helper(root->right);\n\n        // Height of rst is greater than lst or\n        // There are levels which are not filled other than the last level (diff between levels > 1)\n        if(rst.second > lst.first || lst.second - rst.first > 1){\n            isComplete = false;\n        }\n\n        return {min(lst.first, rst.first)+1, max(lst.second, rst.second)+1};\n    }\n\n    bool isCompleteTree(TreeNode* root) {\n        helper(root);\n        return isComplete;\n    }\n};"
    },
    {
        "title": "Distinct Subsequences",
        "algo_input": "Given two strings s and t, return the number of distinct subsequences of s which equals t.\n\nA string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not).\n\nThe test cases are generated so that the answer fits on a 32-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from S.\nrabbbit\nrabbbit\nrabbbit\n\n\nExample 2:\n\nInput: s = \"babgbag\", t = \"bag\"\nOutput: 5\nExplanation:\nAs shown below, there are 5 ways you can generate \"bag\" from S.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, t.length &lt;= 1000\n\ts and t consist of English letters.\n\n",
        "solution_py": "class Solution:\n    def numDistinct(self, s: str, t: str) -> int:\n        if len(t) > len(s):\n            return 0\n        ls, lt = len(s), len(t)\n        res = 0\n        dp = [[0] * (ls + 1) for _ in range(lt + 1)]\n        for j in range(ls + 1):\n            dp[-1][j] = 1\n        for i in range(lt - 1, -1, -1):\n            for j in range(ls -1 , -1, -1):\n                dp[i][j] = dp[i][j + 1]\n                if s[j] == t[i]:\n\n                    dp[i][j] += dp[i + 1][j + 1]\n        return dp[0][0]",
        "solution_js": "var numDistinct = function(s, t) {\n    const n = s.length;\n\n    const memo = {};\n    const dfs = (index = 0, subsequence = '') => {\n        if(subsequence === t) return 1;\n        if(n - index + 1 < t.length - subsequence.length) return 0;\n        if(index === n) return 0;\n\n        const key = `${index}-${subsequence}`;\n        if(key in memo) return memo[key];\n\n        memo[key] = t[subsequence.length] !== s[index] ? 0 : dfs(index + 1, subsequence + s[index]);\n        memo[key] += dfs(index + 1, subsequence);\n        return memo[key];\n    }\n\n    return dfs();\n};",
        "solution_java": "class Solution {\n    // We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]\n    int f(int i,int j,String s,String t,int dp[][]){\n        //If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found a subsequence)\n        if(j<0)\n            return 1;\n        // if s gets exhausted then there are characters remaining in t which are yet to be matched as s got exhausted they could not be matched so there is no distinct subsequence\n        if(i<0){\n            return 0;\n        }\n        if(dp[i][j]!=-1)\n            return dp[i][j];\n        //If both the characters in s[i] and t[j] match then we have two case\n            //1) Either consider the i'th character of s and find the remaining distinct subsequences of s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)\n            //2) Do not consider s[i] so we are still at the same j'th character of t as we had not been considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1] i.e. f(i-1,j)\n        if(s.charAt(i)==t.charAt(j)){\n            dp[i][j]= f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp);\n        }\n        // If both of them do not match then we consider the 2nd case of matching characters\n        else{\n            dp[i][j]=f(i-1,j,s,t,dp);\n        } \n        return dp[i][j];\n    }\n    public int numDistinct(String s, String t) {\n        int n=s.length();\n        int m=t.length();\n        int dp[][]=new int[n][m];\n        for(int i=0;i<n;i++){\n            Arrays.fill(dp[i],-1);\n        }\n        return f(n-1,m-1,s,t,dp);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(string &s, string &t, int i, int j, vector<vector<int>> &dp){\n        if(j >= t.size()) return 1;\n        if(i >= s.size() || t.size() - j > s.size() - i) return 0;\n        if(dp[i][j] != -1) return dp[i][j];\n        int res = 0;\n        for(int k = i; k < s.size(); k++){\n            if(s[k] == t[j]) res += solve(s, t, k+1, j+1, dp); \n        }\n        return dp[i][j] = res;\n    }\n    \n    int numDistinct(string s, string t) {\n        if(s.size() == t.size()) return s == t;\n        vector<vector<int>> dp(s.size(), vector<int> (t.size(), -1));\n        return solve(s, t, 0 , 0, dp);\n    }\n};"
    },
    {
        "title": "Number of Substrings Containing All Three Characters",
        "algo_input": "Given a string s&nbsp;consisting only of characters a, b and c.\n\nReturn the number of substrings containing at least&nbsp;one occurrence of all these characters a, b and c.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcabc\"\nOutput: 10\nExplanation: The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;a,&nbsp;b&nbsp;and&nbsp;c are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\" and \"abc\" (again). \n\n\nExample 2:\n\nInput: s = \"aaacb\"\nOutput: 3\nExplanation: The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;a,&nbsp;b&nbsp;and&nbsp;c are \"aaacb\", \"aacb\" and \"acb\". \n\n\nExample 3:\n\nInput: s = \"abc\"\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 5 x 10^4\n\ts&nbsp;only consists of&nbsp;a, b or c&nbsp;characters.\n\n",
        "solution_py": "class Solution:\n    def numberOfSubstrings(self, s: str) -> int:\n        start = 0\n        end = 0\n        counter = 0\n        store = {'a' : 0, 'b' : 0, 'c' : 0}\n\n        for end in range(len(s)):\n            store[s[end]] += 1\n\n            while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:\n                counter += (len(s) - end)\n                store[s[start]] -= 1\n                start += 1\n\n        return counter",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar numberOfSubstrings = function(s) {\n    let ans = 0;\n    let map = {};\n    for(let i = 0, l = 0; i < s.length; i++) {\n        const c = s[i];\n        map[c] = (map[c] || 0) + 1;\n\n        while(Object.keys(map).length == 3) {\n            ans += s.length - i;\n            map[s[l]]--;\n            if(map[s[l]] == 0) {\n                delete map[s[l]];\n            }\n            l++;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int numberOfSubstrings(String s) {\n        int a = 0, b = 0, c = 0, count = 0;\n        for (int i = 0; i < s.length(); i++) {\n            switch (s.charAt(i)) {\n                case 'a': ++a; break;\n                case 'b': ++b; break;\n                case 'c': ++c; break;\n            }\n            if (a > 0 && b > 0 && c > 0) {\n                while (a > 0 && b > 0 && c > 0) {\n                    char farLeft = s.charAt(i - a - b - c + 1);\n                    switch (farLeft) {\n                        case 'a': {\n                            --a;\n                            count += doCount(s, i);\n                            break;\n                        }\n                        case 'b': {\n                            --b;\n                            count += doCount(s, i);\n                            break;\n                        }\n                        case 'c': {\n                            --c;\n                            count += doCount(s, i);\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n        return count;\n    }\n\n    private int doCount(String s, int i) {\n        int count = 0;\n        int n = s.length() - i;\n        if (n > 0) {\n            count += n;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfSubstrings(string s) {\n        int i=0,j=0;\n        int n = s.size();\n        map<char,int> mp;\n        int count=0;\n        while(j<n){\n            mp[s[j]]++;\n            if(mp.size()<3){\n                j++;\n            }\n            else{\n               while(mp.size()==3){\n                   count+=(n-j);\n                   mp[s[i]]--;\n                   if(mp[s[i]]==0) mp.erase(s[i]);\n                   i++;\n                }\n                j++;\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Rotating the Box",
        "algo_input": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:\n\n\n\tA stone '#'\n\tA stationary obstacle '*'\n\tEmpty '.'\n\n\nThe box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.\n\nIt is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.\n\nReturn an n x m matrix representing the box after the rotation described above.\n\n&nbsp;\nExample 1:\n\n\n\nInput: box = [[\"#\",\".\",\"#\"]]\nOutput: [[\".\"],\n&nbsp;        [\"#\"],\n&nbsp;        [\"#\"]]\n\n\nExample 2:\n\n\n\nInput: box = [[\"#\",\".\",\"*\",\".\"],\n&nbsp;             [\"#\",\"#\",\"*\",\".\"]]\nOutput: [[\"#\",\".\"],\n&nbsp;        [\"#\",\"#\"],\n&nbsp;        [\"*\",\"*\"],\n&nbsp;        [\".\",\".\"]]\n\n\nExample 3:\n\n\n\nInput: box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n&nbsp;             [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n&nbsp;             [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\nOutput: [[\".\",\"#\",\"#\"],\n&nbsp;        [\".\",\"#\",\"#\"],\n&nbsp;        [\"#\",\"#\",\"*\"],\n&nbsp;        [\"#\",\"*\",\".\"],\n&nbsp;        [\"#\",\".\",\"*\"],\n&nbsp;        [\"#\",\".\",\".\"]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == box.length\n\tn == box[i].length\n\t1 &lt;= m, n &lt;= 500\n\tbox[i][j] is either '#', '*', or '.'.\n",
        "solution_py": "class Solution:\n    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n        # move stones to right, row by row\n        for i in range(len(box)):\n            stone = 0\n            for j in range(len(box[0])):\n                if box[i][j] == '#': # if a stone\n                    stone += 1\n                    box[i][j] = '.'\n                elif box[i][j] == '*': # if a obstacle\n                    for m in range(stone):\n                        box[i][j-m-1] = '#'\n                    stone = 0\n            # if reaches the end of j, but still have stone\n            if stone != 0:\n                for m in range(stone):\n                        box[i][j-m] = '#'\n        \n        # rotate box, same as leetcode #48\n        box[:]  = zip(*box[::-1])\n        \n        return box",
        "solution_js": "var rotateTheBox = function(box) {\n  for(let r=0; r<box.length;r++){\n    let idx = null\n    for(let c = 0;c<box[r].length;c++){\n      const curr = box[r][c]\n      if(curr === '*'){\n        idx = null\n        continue\n      }\n      if(curr === '#' && idx === null){\n        idx = c\n        continue\n      }\n      if(curr === '.' &&\n         box[r][idx] === '#' &&\n         idx <= c){\n        box[r][idx] = '.'\n        box[r][c] = '#'\n        idx++\n      }\n    }\n  }\n  return transpose(box)\n};\n\nfunction transpose(arr){\n  const B = []\n  for(let c = 0; c < arr[0].length; c++){\n    if(!B[c]) B[c] = []\n    for(let r = 0; r < arr.length; r++){\n      B[c][r] = arr[r][c]\n    }\n    B[c].reverse()\n  }\n  return B\n}",
        "solution_java": " class Solution {\n     public char[][] rotateTheBox(char[][] box) {\n         int row = box.length, col = box[0].length;\n         char[][] res = new char[col][row];\n         // rotate first, then drop\n         for (int i = 0; i < row; i++) {\n             for (int j = 0; j < col; j++) {\n                 res[j][i] = box[row-1-i][j];\n             }\n         }\n\n        for (int i = col - 1; i >= 0; i--) {\n             for (int j = 0; j < row; j++) {\n                 if (res[i][j] == '#') {\n                     int curRow = i;\n                     while (curRow+1 < col && res[curRow+1][j] == '.') {\n                         curRow++;\n                     }\n                     if (curRow != i) {\n                         res[curRow][j] = '#';\n                         res[i][j] = '.';\n                     }\n                 }\n             }\n         }\n         return res;\n     }\n }",
        "solution_c": "class Solution {\npublic:\n    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {\n        int m = box.size();\n        int n = box[0].size();\n\n        vector<vector<char>> ans(n,vector<char>(m,'.'));\n\n        for(int i=0;i<m;++i){\n            int k = n; //Stores last obstacle or occupied position\n            for(int j=n-1;j>=0;--j)\n            {\n                if(box[i][j] == '#')\n                {\n                    ans[--k][i] = '#';\n                }\n                else if(box[i][j] == '*')\n                {\n                     k = j;\n                     ans[j][i] = '*';\n                }\n            }\n        }\n        for(int i=0;i<n;++i){\n            reverse(ans[i].begin(), ans[i].end());\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Distance to Type a Word Using Two Fingers",
        "algo_input": "\nYou have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.\n\n\n\tFor example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).\n\n\nGiven the string word, return the minimum total distance to type such string using only two fingers.\n\nThe distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.\n\nNote that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.\n\n&nbsp;\nExample 1:\n\nInput: word = \"CAKE\"\nOutput: 3\nExplanation: Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -&gt; cost = 0 \nFinger 1 on letter 'A' -&gt; cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -&gt; cost = 0 \nFinger 2 on letter 'E' -&gt; cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3\n\n\nExample 2:\n\nInput: word = \"HAPPY\"\nOutput: 6\nExplanation: Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -&gt; cost = 0\nFinger 1 on letter 'A' -&gt; cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -&gt; cost = 0\nFinger 2 on letter 'P' -&gt; cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -&gt; cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= word.length &lt;= 300\n\tword consists of uppercase English letters.\n\n",
        "solution_py": "from functools import cache\nclass Solution:\n    def minimumDistance(self, word: str) -> int:\n        alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        COL = 6\n        index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}\n        def dist(a, b):\n            return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])\n        @cache\n        def dfs(lhand, rhand, i):\n            if i == len(word): return 0\n            res = float('inf')\n            res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))\n            res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))\n            return res\n        return dfs(-1, -1, 0)",
        "solution_js": "const dist = function(from, to){\n    if(from==-1) return 0; \n    const d1 = Math.abs((from.charCodeAt(0)-65)%6-(to.charCodeAt(0)-65)%6),\n          d2 = Math.abs(Math.floor((from.charCodeAt(0)-65)/6)-Math.floor((to.charCodeAt(0)-65)/6));\n    return d1 + d2;\n}\nvar minimumDistance = function(word) {\n\n    const dp = new Map();\n    \n    const dfs = function(i, lpos, rpos){\n        if(i==word.length) \n            return 0;\n        const key = [i,lpos,rpos].join(',');\n        if(dp.get(key)) \n            return dp.get(key);\n        dp.set(key, Math.min(dist(lpos,word[i])+dfs(i+1,word[i],rpos), dist(rpos,word[i])+dfs(i+1,lpos,word[i])));\n        return dp.get(key);\n    }\n    return dfs(0, -1, -1);\n};",
        "solution_java": "class Solution {\n    HashMap<Character,Integer[]> pos;\n    int [][][]memo;\n    int type(String word,int index,char finger1,char finger2){\n        if (index==word.length()) return 0;\n        int ans=9999999;\n        if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];\n        if (finger1=='['){\n            \n            ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));\n        }\n        else{\n            \n            Integer [] prev=pos.get(finger1);\n            Integer [] curr=pos.get(word.charAt(index));\n            int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n            ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);\n        }\n        if (finger2=='['){\n            ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));\n        }\n        else{\n            Integer [] prev=pos.get(finger2);\n            Integer [] curr=pos.get(word.charAt(index));\n            int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n            ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);\n        }\n        memo[index][finger1-'A'][finger2-'A']=ans;\n        return ans;\n    }\n    public int minimumDistance(String word) {\n        pos=new HashMap();\n        for (int i=0;i<26;i++){\n            Integer [] coord={i/6,i%6};\n            pos.put((char)('A'+i),coord);\n        }\n        memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];\n        for (int[][] row : memo) {\n            for (int[] rowColumn : row) {\n                Arrays.fill(rowColumn, -1);\n            }\n        }\n        return  type(word,0,'[','[');\n        }\n}",
        "solution_c": "class Solution {\npublic:\n    string alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    unordered_map<char, pair<int, int>> m;\n    int distCalc(char a, char b) {\n        pair<int, int> p_a = m[a];\n        pair<int, int> p_b = m[b];\n        \n        int x_diff = abs(p_a.first - p_b.first);\n        int y_diff = abs(p_a.second - p_b.second);\n        \n        return x_diff + y_diff;\n    }\n    int dp[301][27][27];\n    int minDist(string word, int i, char finger1_char, char finger2_char) {\n        if(i == word.size()) return 0;\n       \n        if(dp[i][finger1_char - 'A'][finger2_char - 'A'] != -1) return dp[i][finger1_char - 'A'][finger2_char - 'A'];\n        \n        //finger1\n        int op1 =  (finger1_char == '[' ? 0 : distCalc(finger1_char, word[i])) + minDist(word, i + 1, word[i], finger2_char);\n        \n        //finger2\n        int op2 =  (finger2_char == '[' ? 0 : distCalc(finger2_char, word[i])) + minDist(word, i + 1, finger1_char, word[i]);\n        \n        return dp[i][finger1_char - 'A'][finger2_char - 'A'] = min(op1, op2);\n    }\n    int minimumDistance(string word) {\n        //each letter has choice to be clicked by finger 1 or 2\n        \n        int row = -1;\n        for(int i = 0; i < alpha.length(); i++) {\n            int col = i % 6;\n            if(col == 0) row++;\n            m[alpha[i]] = {row, col};\n        }\n         memset(dp, -1, sizeof(dp));\n         return minDist(word, 0, '[', '[');\n    }\n};"
    },
    {
        "title": "Binary Number with Alternating Bits",
        "algo_input": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: true\nExplanation: The binary representation of 5 is: 101\n\n\nExample 2:\n\nInput: n = 7\nOutput: false\nExplanation: The binary representation of 7 is: 111.\n\nExample 3:\n\nInput: n = 11\nOutput: false\nExplanation: The binary representation of 11 is: 1011.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def hasAlternatingBits(self, n: int) -> bool:\n        bin_n = bin(n)[2:]\n        for i in range(len(bin_n)-1):\n            if bin_n[i] == '0' and bin_n[i+1] == '0':\n                return False\n            \n            if bin_n[i] == '1' and bin_n[i+1] == '1':\n                return False\n            \n        return True",
        "solution_js": "/**\n * @param {number} n\n * @return {boolean}\n */\nvar hasAlternatingBits = function(n) {\n  let previous;\n  while (n) {\n    const current = n & 1;\n    if (previous === current) return false;\n    previous = current;\n    n >>>= 1;\n  }\n  return true;\n};",
        "solution_java": "class Solution {\n    public boolean hasAlternatingBits(int n) {\n        int flag = 1;\n        if(n % 2 == 0) flag = 0;\n        return bin(n / 2, flag);\n    }\n    public boolean bin(int n, int flag) {\n        if(flag == n % 2) return false;\n        if(n == 0) return true;\n        else return bin(n / 2, n % 2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    const static uint32_t a = 0b10101010101010101010101010101010;\n    bool hasAlternatingBits(int n) {\n        return ((a >> __builtin_clz(n)) ^ n) == 0;\n    }\n};"
    },
    {
        "title": "Implement strStr()",
        "algo_input": "Implement strStr().\n\nGiven two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n\nClarification:\n\nWhat should we return when needle is an empty string? This is a great question to ask during an interview.\n\nFor the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().\n\n&nbsp;\nExample 1:\n\nInput: haystack = \"hello\", needle = \"ll\"\nOutput: 2\n\n\nExample 2:\n\nInput: haystack = \"aaaaa\", needle = \"bba\"\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= haystack.length, needle.length &lt;= 104\n\thaystack and needle consist of only lowercase English characters.\n\n",
        "solution_py": "class Solution(object):\n    def strStr(self, haystack, needle):\n        if needle == '':\n            return 0\n        else:\n            return self.search_substring(haystack, needle)\n\n    def search_substring(self, haystack, needle):\n        len_substring = len(needle)\n        for i in range(len(haystack)):\n            if haystack[i: i + len_substring] == needle:\n                return i\n        return -1",
        "solution_js": "var strStr = function(haystack, needle) {\n    return haystack.indexOf(needle)\n};",
        "solution_java": "class Solution {\n    public int strStr(String haystack, String needle) {\n        \n        if(needle.length()>haystack.length()) {\n            return -1;\n        } \n        if(needle.length()==haystack.length()) {\n            if(haystack.equals(needle)) {\n                return 0;\n            }\n            return -1;\n        }\n        \n        \n        int i=0;\n        int j=0;\n        while(i<needle.length() && j<haystack.length()) {\n            if(needle.charAt(i)==haystack.charAt(j)) {\n                i++;\n                j++;\n                if(i==needle.length()) {\n                    return j-needle.length();\n                }\n            } else {\n                j = j-i+1; // backtrack to last pos+1 where there was a probable match\n                i=0;\n            }\n        }\n        \n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int strStr(string haystack, string needle) {\n        return haystack.find(needle);\n    }\n};"
    },
    {
        "title": "Check if Word Can Be Placed In Crossword",
        "algo_input": "You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.\n\nA word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:\n\n\n\tIt does not occupy a cell containing the character '#'.\n\tThe cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.\n\tThere must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.\n\tThere must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.\n\n\nGiven a string word, return true if word can be placed in board, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\nOutput: true\nExplanation: The word \"abc\" can be placed as shown above (top to bottom).\n\n\nExample 2:\n\nInput: board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\nOutput: false\nExplanation: It is impossible to place the word because there will always be a space/letter above or below it.\n\nExample 3:\n\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\nOutput: true\nExplanation: The word \"ca\" can be placed as shown above (right to left). \n\n\n&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m * n &lt;= 2 * 105\n\tboard[i][j] will be ' ', '#', or a lowercase English letter.\n\t1 &lt;= word.length &lt;= max(m, n)\n\tword will contain only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n        m, n = len(board), len(board[0])\n        W = len(word)\n        \n        def valid(x, y):\n            return 0 <= x < m and 0 <= y < n\n        \n        def place(x, y, word, direction):\n            dx, dy = direction\n            for c in word:\n                if not valid(x, y) or board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != c):\n                    return False\n                x, y = x+dx, y+dy\n            return True\n            \n        \n        for x in range(m):\n            for y in range(n):\n                if board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != word[0]):\n                    continue\n                \n                # left to right\n                if (not valid(x, y-1) or board[x][y-1] == '#') and (not valid(x, y+W) or board[x][y+W] == '#') and place(x, y, word, [0, 1]):\n                    return True\n                \n                # right to left\n                if (not valid(x, y+1) or board[x][y+1] == '#') and (not valid(x, y-W) or board[x][y-W] == '#') and place(x, y, word, [0, -1]):\n                    return True\n                \n                # top to bottom\n                if (not valid(x-1, y) or board[x-1][y] == '#') and (not valid(x+W, y) or board[x+W][y] == '#') and place(x, y, word, [1, 0]):\n                    return True\n                \n\t\t\t\t# bottom to top\n                if (not valid(x+1, y) or board[x+1][y] == '#') and (not valid(x-W, y) or board[x-W][y] == '#') and place(x, y, word, [-1, 0]):\n                    return True\n                \n        return False",
        "solution_js": "/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\nvar placeWordInCrossword = function(board, word) {\n    for (let i = 0; i < board.length; i++) {\n        for (let j = 0; j < board[0].length; j++) {\n            if (i === 0 || board[i - 1][j] === '#') {\n                if (match(getFill(i, j, false))) {\n                    return true;\n                }\n            }\n            if (j === 0 || board[i][j - 1] === '#') {\n                if (match(getFill(i, j, true))) {\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n\n    function getFill(x, y, goRight) {\n        if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] !== '#') {\n            return goRight ? board[x][y] + getFill(x, y + 1, goRight) : board[x][y] + getFill(x + 1, y, goRight);\n        }\n        return '';\n    }\n\n    function match(str) {\n        if (str.length !== word.length) {\n            return false;\n        }\n        let fromLeft = true;\n        let fromRight = true;\n        let l = 0;\n        let r = str.length - 1;\n        for (let each of word) {\n            if (!fromLeft && !fromRight) {\n                return false;\n            }\n            if (fromLeft) {\n                if (each !== str[l] && str[l] !== ' ') {\n                    fromLeft = false;\n                }\n                l++;\n            }\n            if (fromRight) {\n                if (each !== str[r] && str[r] !== ' ') {\n                    fromRight = false;\n                }\n                r--;\n            }\n        }\n        return fromLeft || fromRight;\n    }\n};",
        "solution_java": "class Solution {\n    public boolean placeWordInCrossword(char[][] board, String word) {\n        String curr = \"\";\n\n        Trie trie = new Trie();\n\n        // Insert all horizontal strings\n        for (int i = 0; i < board.length; i++) {\n            for (int j = 0; j < board[0].length; j++) {\n                if (board[i][j] == '#') {\n                    insertIntoTrie(trie, curr);\n                    curr = \"\";\n                }\n                else {\n                    curr += board[i][j];\n                }\n            }\n            insertIntoTrie(trie, curr);\n            curr = \"\";\n        }\n\n        // Insert all vertical strings\n        for (int i = 0; i < board[0].length; i++) {\n            for (int j = 0; j < board.length; j++) {\n                if (board[j][i] == '#') {\n                    insertIntoTrie(trie, curr);\n                    curr = \"\";\n                }\n                else {\n                    curr += board[j][i];\n                }\n            }\n            insertIntoTrie(trie, curr);\n            curr = \"\";\n        }\n\n        return trie.isPresent(word);\n    }\n\n    // Insert string and reverse of string into the trie\n    private void insertIntoTrie(Trie trie, String s) {\n        trie.insert(s);\n        StringBuilder sb = new StringBuilder(s);\n        sb.reverse();\n        trie.insert(sb.toString());\n    }\n\n    class TrieNode {\n        Map<Character, TrieNode> children;\n        boolean isEnd;\n\n        TrieNode() {\n            children = new HashMap<>();\n            isEnd = false;\n        }\n\n    }\n\n    class Trie {\n        TrieNode root;\n\n        Trie() {\n            root = new TrieNode();\n        }\n\n        void insert(String s) {\n            TrieNode curr = root;\n\n            for (int i = 0; i < s.length(); i++)\n            {\n                char c = s.charAt(i);\n                if (!curr.children.containsKey(c)) {\n                    curr.children.put(c, new TrieNode());\n                }\n\n                curr = curr.children.get(c);\n            }\n\n            curr.isEnd = true;\n        }\n\n        boolean isPresent(String key) {\n            TrieNode curr = root;\n            return helper(key, 0, root);\n\n        }\n\n        boolean helper(String key, int i, TrieNode curr) {\n            if (curr == null)\n                return false;\n\n            if (i == key.length())\n                return curr.isEnd;\n\n            char c = key.charAt(i);\n            return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));\n\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool placeWordInCrossword(vector<vector<char>>& board, string word) {\n        int m = board.size();\n        int n = board[0].size();\n        for(int i = 0 ; i < m ; i++){\n            for(int j = 0 ; j < n; j++){\n                if(board[i][j] != '#'){\n                    if(valid(board, i-1, j) && check(board, word, i, j, 0, true, 1)) return true;\n                    if(valid(board, i+1, j) && check(board, word, i, j, 0, true, -1)) return true;\n                    if(valid(board, i, j-1) && check(board, word, i, j, 0, false, 1)) return true;\n                    if(valid(board, i, j+1) && check(board, word, i, j, 0, false, -1)) return true;\n                }\n            }\n        }\n        return false;\n    }\n\n    bool check(vector<vector<char>>& board, string &word, int x, int y, int pos, bool vertical, int inc){\n        if(pos == word.size()){\n            if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;\n            return board[x][y] == '#';\n        }\n        if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false;\n        if(board[x][y] == '#') return false;\n        if(board[x][y] != ' ' && board[x][y] != word[pos]) return false;\n        int newx = x + vertical * inc;\n        int newy = y + (!vertical) * inc;\n        return check(board, word, newx, newy, pos+1, vertical, inc);\n    }\n\n    bool valid(vector<vector<char>>& board, int x, int y){\n        if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;\n        return board[x][y] == '#';\n    }\n};"
    },
    {
        "title": "Delete the Middle Node of a Linked List",
        "algo_input": "You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.\n\nThe middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.\n\n\n\tFor n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.\n\n\n&nbsp;\nExample 1:\n\nInput: head = [1,3,4,7,1,2,6]\nOutput: [1,3,4,1,2,6]\nExplanation:\nThe above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node. \n\n\nExample 2:\n\nInput: head = [1,2,3,4]\nOutput: [1,2,4]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.\n\n\nExample 3:\n\nInput: head = [2,1]\nOutput: [2]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 105].\n\t1 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n  def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n    if not head: return head\n    if head and not head.next: return None\n\n    prev = ListNode(0, head)\n    slow = fast = head\n    while fast and fast.next:\n      prev = slow\n      slow = slow.next\n      fast = fast.next.next\n\n    prev.next = slow.next\n    return head",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\n// Two Pointer: Fast & Slow | O(N) | O(1)\nvar deleteMiddle = function(head) {\n  if (!head.next) return null;\n\n  let prev = head;\n  let slow = head;\n  let fast = head.next;\n  let size = 2;\n\n  while (fast && fast.next) {\n    prev = slow;\n    slow = slow.next;\n    fast = fast.next.next;\n    size += fast ? 2 : 1;\n  }\n\n  if (size % 2 === 0) slow.next = slow.next.next;\n  else prev.next = slow.next;\n\n  return head;\n};",
        "solution_java": "class Solution {\n    public ListNode deleteMiddle(ListNode head) {\n        // Base Condition\n        if(head == null || head.next == null) return null;\n        // Pointers Created\n        ListNode fast = head;\n        ListNode slow = head;\n        ListNode prev = head;\n\n        while(fast != null && fast.next != null){\n            prev = slow;\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        prev.next = slow.next;\n        return head;\n    }\n}",
        "solution_c": "**Intution**- we know that we can find middle node using two pointer fast and slow. \n After we iterate through linkedlist slow pointer is our middle node and since we need to delete it\n we only need pointer to its previous node and then just simply put next to next node in previous node.\n Woahh ! you are done with deleting middle NODE;\n\nclass Solution {\npublic:\n\tListNode* deleteMiddle(ListNode* head) {\n\t\t   if(head->next==nullptr) return nullptr;\n\t\t   ListNode *f=head;\n\t\t   ListNode *s=head,*prev;\n\t\t  while(f!=nullptr && f->next!=nullptr){\n\t\t\t  f=f->next->next;\n\t\t\t  prev=s;\n\t\t\t  s=s->next;\n\t\t  }\n\t\tprev->next=prev->next->next;\n\t\treturn head;\n\t}\n};"
    },
    {
        "title": "Minimum Number of Work Sessions to Finish the Tasks",
        "algo_input": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.\n\nYou should finish the given tasks in a way that satisfies the following conditions:\n\n\n\tIf you start a task in a work session, you must complete it in the same work session.\n\tYou can start a new task immediately after finishing the previous one.\n\tYou may complete the tasks in any order.\n\n\nGiven tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.\n\nThe tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].\n\n&nbsp;\nExample 1:\n\nInput: tasks = [1,2,3], sessionTime = 3\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.\n\n\nExample 2:\n\nInput: tasks = [3,1,3,1,1], sessionTime = 8\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.\n\n\nExample 3:\n\nInput: tasks = [1,2,3,4,5], sessionTime = 15\nOutput: 1\nExplanation: You can finish all the tasks in one work session.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == tasks.length\n\t1 &lt;= n &lt;= 14\n\t1 &lt;= tasks[i] &lt;= 10\n\tmax(tasks[i]) &lt;= sessionTime &lt;= 15\n\n",
        "solution_py": "class Solution:\n    def minSessions(self, tasks, T):\n        n = len(tasks)\n\n        @lru_cache(None)\n        def dp(mask):\n            if mask == 0: return (1, 0)\n            ans = (float(\"inf\"), float(\"inf\"))\n            for j in range(n):\n                if mask & (1<<j):\n                    pieces, last = dp(mask - (1 << j))\n                    full = (last + tasks[j] > T)\n                    ans = min(ans, (pieces + full, tasks[j] + (1-full)*last))  \n            return ans\n\n        return dp((1<<n) - 1)[0]",
        "solution_js": "/**\n * @param {number[]} tasks\n * @param {number} sessionTime\n * @return {number}\n */\nvar minSessions = function(tasks, sessionTime) {\n  const n = tasks.length;\n  const dp = Array(1 << n).fill().map(() => Array(16).fill(-1));\n  \n  const solve = (mask, time) => {\n    if (mask === (1 << n) - 1) {\n      return 1;\n    }\n    \n    if (dp[mask][time] !== -1) {\n      return dp[mask][time];\n    }\n    \n    let min = Infinity;\n    for (let i = 0; i < n; ++i) {\n      if (mask & (1 << i)) {\n        continue;\n      }\n\n      if (time >= tasks[i]) {\n        min = Math.min(\n          min,\n          solve(mask | (1 << i), time - tasks[i]),\n        );\n      } else {\n        min = Math.min(\n          min,\n          1 + solve(mask | (1 << i), sessionTime - tasks[i]),\n        );\n      }\n    }\n    \n    dp[mask][time] = min;\n    return min;\n  }\n  \n  return solve(0, sessionTime);\n};",
        "solution_java": "// Java Solution\nclass Solution {\n    public int minSessions(int[] tasks, int sessionTime) {\n        int n = tasks.length, MAX = Integer.MAX_VALUE;\n        int[][] dp = new int[1<<n][2];\n        dp[0][0] = 1;\n        dp[0][1] = 0;\n\n        for(int i = 1; i < (1 << n); i++) {\n            dp[i][0] = MAX;\n            dp[i][1] = 0;\n\n            for(int t = 0; t < n; t++) {\n                if(((1<<t) & i) == 0) continue;\n\n                int[] prev = dp[(1<<t) ^ i];\n                if(prev[1] + tasks[t] <= sessionTime) {\n                    dp[i] = min(dp[i], new int[]{prev[0], prev[1] + tasks[t]});\n                }else{\n                    dp[i] = min(dp[i], new int[]{prev[0] + 1, tasks[t]});\n                }\n            }\n        }\n\n        return dp[(1<<n) - 1][0];\n    }\n\n    private int[] min(int[] d1, int[] d2) {\n        if(d1[0] > d2[0]) return d2;\n        if(d1[0] < d2[0]) return d1;\n        if(d1[1] > d2[1]) return d2;\n\n        return d1;\n    }\n}",
        "solution_c": "// C++ Solution\nclass Solution {\npublic:\n    int minSessions(vector<int>& tasks, int sessionTime) {\n        const int N = tasks.size();\n        const int INF = 1e9;\n        vector<pair<int, int>> dp(1 << N, {INF, INF});\n        dp[0] = {0, INF};\n        for(int mask = 1; mask < (1 << N); ++mask) {\n            pair<int, int> best = {INF, INF};\n            for(int i = 0; i < N; ++i) {\n                if(mask & (1 << i)) {\n                    pair<int, int> cur = dp[mask ^ (1 << i)];\n                    if(cur.second + tasks[i] > sessionTime) {\n                        cur = {cur.first + 1, tasks[i]};\n                    } else\n                        cur.second += tasks[i];\n                    best = min(best, cur);\n                }\n            }\n            dp[mask] = best;\n        }\n        return dp[(1 << N) - 1].first;\n    }\n};"
    },
    {
        "title": "Longest Well-Performing Interval",
        "algo_input": "We are given hours, a list of the number of hours worked per day for a given employee.\n\nA day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.\n\nA well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.\n\nReturn the length of the longest well-performing interval.\n\n&nbsp;\nExample 1:\n\nInput: hours = [9,9,6,0,6,6,9]\nOutput: 3\nExplanation: The longest well-performing interval is [9,9,6].\n\n\nExample 2:\n\nInput: hours = [6,6,6]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= hours.length &lt;= 104\n\t0 &lt;= hours[i] &lt;= 16\n\n",
        "solution_py": "class Solution:\n    def longestWPI(self, hours: List[int]) -> int:\n        #accumulative count\n        #+1 when > 8, -1 when less than 8. \n        #find strictly increasing length.\n        \n        p = [] #number of tiring days vs not\n        c = 0\n        for e in hours:\n            if e > 8:\n                c +=1\n            else:\n                c-=1\n            \n            p.append(c)\n            \n            \n        \n        #for every moment: we want earliest moment which could be positive overall tiring days.\n        a = []\n        #a is sorted by tiringnes. At day 8 have -2, want earliest point that could get us to at least 1.\n        #so up until that point we have -3, -4, etc, and we want earliest out of it to get longest well performing interval. Which is when prefix comes in.\n        \n        a1 =[]\n        for i in range(len(p)):\n            a.append([p[i], i])\n            a1.append(p[i])\n        \n        a1.sort() #bisectable list\n        a.sort()\n        \n        prefix = []\n        currearly = float('inf')\n        for t, day in a:\n            currearly = min(currearly, day)\n            prefix.append(currearly)\n        \n        \n        res = 0\n        \n        # print(p)\n        \n        for i in range(len(hours)):\n            if p[i] > 0:\n                res = max(res, i + 1) \n            \n            else:\n                #find earliest \n                #value must be less than -1-p[i] \n                loc = bisect_right(a1, -1+p[i]) #bisect right means anything before this is less than or equals to\n                \n                \n                \n                if loc == 0: #the rightmost place to put it is at the beginning...\n                    \n                    continue\n                \n                \n                else:\n                    earliest = prefix[loc - 1]\n                    \n                    if earliest >= i: continue\n                    \n                    interval = i - earliest #notice: we're not including the starting index, since its also technically being removed!\n\n                    # print(\"From day\", earliest, \"to\", i)\n                    \n                    res = max(res, interval)\n        \n        \n        \n        return res\n        \n        \n        \n        ",
        "solution_js": "var longestWPI = function(hours) {\n    var dp = new Array(hours.length).fill(0);\n    for(i=0;i<hours.length;i++){\n       if(dp[i-1]>0 && hours[i]<=8){\n            dp[i]=dp[i-1]-1;\n            continue;\n        }\n        let tiring = 0;\n        for(j=i;j<hours.length;j++){\n            if(hours[j]>8) tiring++;\n            else tiring--;\n            if(tiring>0) dp[i] = Math.max(dp[i], j-i+1);\n        }}\n    return Math.max(...dp);\n};",
        "solution_java": "// Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)\n// For Longest Well Performing Interval/Window\n// T.C. = O(n^2) , S.C. = O(n)\nclass Solution {\n    \n    public int longestWPI(int[] hours) {\n        int n = hours.length;\n        \n        int[] prefixSumTiringDaysMinusNonTiringDaysArr = new int[n + 1];\n        prefixSumTiringDaysMinusNonTiringDaysArr[0] = 0;\n        \n        int prefixSumTiringDaysCount = 0;\n        int prefixSumNonTiringDaysCount = 0;\n        \n        for (int i = 0 ; i < n ; i++) {\n            int noOfHoursWorkedToday = hours[i];\n            \n            if (noOfHoursWorkedToday > 8) {\n                prefixSumTiringDaysCount++;\n            }\n            else {\n                prefixSumNonTiringDaysCount++;\n            }\n            \n            prefixSumTiringDaysMinusNonTiringDaysArr[i + 1] = prefixSumTiringDaysCount - prefixSumNonTiringDaysCount;\n            // System.out.print(prefixSumTiringDaysMinusNonTiringDaysArr[i] + \" \");\n        }\n        // System.out.println(prefixSumTiringDaysMinusNonTiringDaysArr[n]);\n        \n        int longestLengthOfContinuousPositiveSequence = 0;\n        \n        for (int currentSlidingWindowLength = 1 ; currentSlidingWindowLength <= n ; currentSlidingWindowLength++) {\n            // System.out.print(currentSlidingWindowLength + \" - \");\n            for (int i = 0 ; i <= n - currentSlidingWindowLength ; i++) {\n                int j = i + currentSlidingWindowLength - 1;\n                // System.out.print(i + \",\" + j + \" \");\n                int currentIntervalNoOfTiringDaysMinusNonTiringDays = prefixSumTiringDaysMinusNonTiringDaysArr[j + 1] - prefixSumTiringDaysMinusNonTiringDaysArr[i];\n                if (currentIntervalNoOfTiringDaysMinusNonTiringDays > 0) { // => currentInterval = Well Performing Interval\n                    longestLengthOfContinuousPositiveSequence = Math.max(currentSlidingWindowLength, longestLengthOfContinuousPositiveSequence);\n                }\n            }\n            // System.out.println();\n        }\n        // System.out.println();\n        \n        int lengthOfLongestWellPerformingInterval = longestLengthOfContinuousPositiveSequence;\n        \n        return lengthOfLongestWellPerformingInterval;\n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n\tint longestWPI(vector<int>& hours) {\n        int n = hours.size();\n\t\tint ans = 0;\n\t\tint ct = 0;\n\t\tunordered_map<int, int> m;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (hours[i] > 8) ct++;\n\t\t\telse ct--;\n\t\t\tif (ct > 0) ans = max(ans, i + 1);\n\t\t\telse {\n\t\t\t\tif (m.find(ct) == m.end()) m[ct] = i;\n\t\t\t\tif (m.find(ct - 1) != m.end()) ans = max(ans, i - m[ct - 1]);\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Shortest Subarray with Sum at Least K",
        "algo_input": "Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.\n\nA subarray is a contiguous part of an array.\n\n&nbsp;\nExample 1:\nInput: nums = [1], k = 1\nOutput: 1\nExample 2:\nInput: nums = [1,2], k = 4\nOutput: -1\nExample 3:\nInput: nums = [2,-1,2], k = 3\nOutput: 3\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-105 &lt;= nums[i] &lt;= 105\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "# 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative, \n# the numbers in sliding window are not always incrementing\n# ex [8,-4,3,1,6], 10\n\n# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.\n# 3. monotonic queue is used to keep the prefix sums are in the incrementing order\n# 4. If the diffenence between the cur and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n\nclass Solution:\n    def shortestSubarray(self, nums: List[int], k: int) -> int:\n        prefixsum = [0]\n        monoq = deque()\n        minLen = float('inf')\n        # to calculate prefix sum\n        for n in nums:\n            prefixsum.append(n+prefixsum[-1])\n        for idx, cur in enumerate(prefixsum):\n            while monoq and prefixsum[monoq[-1]] >= cur: monoq.pop() # to maintain monotonic queue\n\n            # If the diffenence between the head and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n            while monoq and cur-prefixsum[monoq[0]]>=k: \n                minLen = min(minLen, idx-monoq.popleft())\n            monoq.append(idx)\n        return -1 if minLen == float('inf') else minLen",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar DoublyLinkedList = function(sum = \"DUMMY\", index = \"DUMMY\") {\n    this.property = {sum, index}\n    this.prev = null\n    this.next = null\n}\n\nDoublyLinkedList.prototype.deque = function() {\n    const dequeNode = this.next\n\n    this.next = dequeNode.next\n    dequeNode.next.prev = this\n\n    dequeNode.next = null\n    dequeNode.prev = null\n    return dequeNode\n}\n\nDoublyLinkedList.prototype.pop = function() {\n    const dequeNode = this.prev\n\n    this.prev = dequeNode.prev\n    dequeNode.prev.next = this\n\n    dequeNode.next = null\n    dequeNode.prev = null\n    return dequeNode\n}\n\nDoublyLinkedList.prototype.push = function(node) {\n    const prev = this.prev\n    const next = this\n\n    node.prev = prev\n    node.next = next\n\n    prev.next = node\n    next.prev = node\n}\n\nvar shortestSubarray = function(nums, k) {\n    // Steps :-\n    // Initalize 3 vaiables :- sum = 0, subArrayLength = Infinity, queue -> []\n\n    const dummyHead = new DoublyLinkedList()\n    const dummyTail = new DoublyLinkedList()\n    dummyHead.next = dummyTail\n    dummyTail.prev = dummyHead\n\n    let queueSize = 0\n\n    let subArraySize = Number.MAX_SAFE_INTEGER\n    let sum = 0\n    for (let i = 0; i < nums.length; i++) {\n        sum += nums[i]\n\n        // Gives one possible answer, if sum is greater than or\n        // equal to k\n        if (sum >= k)\n            subArraySize = Math.min(subArraySize, i+1)\n\n        let lastDequeued\n\n        // Reduce the queue from left till the sum of elements from\n        // first index of queue till last index of queue is less than k\n        // Each time we constantly update the lastdequeued element\n        // As the last lastdequeued will satisfy sum - lastDequeued.sum >= k\n        // Thus the range would be i-lastDequeued.property.index\n        // (without lastDequeued.property.index)\n        while (queueSize > 0 && sum - dummyHead.next.property.sum >= k) {\n            queueSize--\n            lastDequeued = dummyHead.deque()\n        }\n\n        // Using the lastDequeued value to check\n        if (lastDequeued !== undefined) {\n            subArraySize = Math.min(subArraySize, i-lastDequeued.property.index)\n        }\n\n        // Maintaining the monotonic queue\n        while (queueSize > 0 && sum <= dummyTail.prev.property.sum) {\n            queueSize--\n            dummyTail.pop()\n        }\n\n        const newNode = new DoublyLinkedList(sum, i)\n\n        dummyTail.push(newNode)\n        queueSize++\n    }\n    return subArraySize === Number.MAX_SAFE_INTEGER ? -1 : subArraySize\n};",
        "solution_java": "class Solution {\n    public int shortestSubarray(int[] nums, int k) {\n        \n         TreeMap<Long, Integer> maps = new TreeMap<>();\n         long sum = 0l;\n         int min = nums.length + 1;\n\t\t \n         maps.put(0l, -1);\n        \n         for(int i = 0; i < nums.length; i++) {\n             sum += nums[i];ntry(sum - k) != null) \n\t\t\t       min = Math.min(min, i - maps.floorEntry(sum - k).getValue()); \n            while(!maps.isEmpty() && maps.lastEntry().getKey() >= sum) \n\t\t\t       maps.remove(maps.lastEntry().getKey());\n        \n            maps.put(sum, i);\n         }\n        \n        return min == (nums.length + 1) ? -1 : min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    //2-pointer doesnt work on neg elements\n    //Using mono deque to solve sliding window\n    int shortestSubarray(vector<int>& nums, int k) {\n        int n = nums.size();\n        int minsize = INT_MAX;\n        vector<long> prefixsum(n,0);\n        deque<int> dq;\n\n        prefixsum[0] = nums[0];\n        for(int i = 1;i<n;i++) prefixsum[i] = prefixsum[i-1] + nums[i];\n\n        for(int i = 0;i<n;i++){\n            if(prefixsum[i]>=k)\n                minsize = min(minsize,i+1);\n\n            while(!dq.empty() && prefixsum[i]-prefixsum[dq.front()]>=k){\n                minsize = min(minsize,i-dq.front());\n                dq.pop_front();\n            }\n\n            while(!dq.empty() && prefixsum[i]<=prefixsum[dq.back()]){\n                dq.pop_back();\n            }\n\n            dq.push_back(i);\n        }\n        return (minsize==INT_MAX) ? -1 : minsize;\n    }\n};"
    },
    {
        "title": "Find XOR Sum of All Pairs Bitwise AND",
        "algo_input": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.\n\n\n\tFor example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.\n\n\nYou are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.\n\nConsider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 &lt;= i &lt; arr1.length and 0 &lt;= j &lt; arr2.length.\n\nReturn the XOR sum of the aforementioned list.\n\n&nbsp;\nExample 1:\n\nInput: arr1 = [1,2,3], arr2 = [6,5]\nOutput: 0\nExplanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\n\n\nExample 2:\n\nInput: arr1 = [12], arr2 = [4]\nOutput: 4\nExplanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr1.length, arr2.length &lt;= 105\n\t0 &lt;= arr1[i], arr2[j] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n        def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)\n        return xor_lis(arr1) & xor_lis(arr2)",
        "solution_js": "var getXORSum = function(arr1, arr2) {\n    // (x & 2) xor (x & 3) =[ !(x&2) & (x&3) ] OR  [ (x&2) & !(x&3) ]\n\t// = [ (!x || !2 ) & (x&3) ] OR [ (x&2) & (!x || !3) ]\n    // = [ (!x || !2) & x & 3 ]   OR  [ x & 2 & (!x || !3) ]\n    // = (!2 & x & 3 ) || (x & 2 & !3)\n    // = x & [ (!2 & 3) || (!3 & 2) ]\n    // = x & (2 XOR 3)\n    // const ans = (2 XOR 3 XOR....) in arr2\n    // The same principle: x, y,z... in arr1\n    // res = (x & ans) XOR (y & ans) XOR .....\n    //  = ans & (x XOR y XOR z .......)\n    // Finally: res = (XOR: arr1) AND (XOR: arr2);\n    var xor1 = arr1.reduce((acc,cur)=>acc^cur);\n    var xor2 = arr2.reduce((acc,cur)=>acc^cur);\n    return xor1 & xor2;\n};",
        "solution_java": "class Solution {\n\n    public int getXORSum(int[] arr1, int[] arr2) {\n        int[] x = (arr1.length < arr2.length ? arr2 : arr1);\n        int[] y = (arr1.length < arr2.length ? arr1 : arr2);\n        int xorSumX = 0;\n        for (int xi : x) {\n            xorSumX ^= xi;\n        }\n        int answer = 0;\n        for (int yj : y) {\n            answer ^= (yj & xorSumX);\n        }\n        return answer;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    // this code is basically pure mathematics, mainly distributive property with AND and XOR\n    \n    int getXORSum(vector<int>& arr1, vector<int>& arr2) {\n        int m=arr1.size();\n        int n=arr2.size();\n        long int ans1=0,ans2=0;\n        for(int i=0;i<m;i++)  // this loop stores the XOR between every element of arr1\n        {\n            ans1=ans1 ^ arr1[i];\n        }\n        for(int j=0;j<n;j++)   // this loop stores the XOR between every element of arr2\n        {\n            ans2=ans2 ^ arr2[j];\n        }\n        return ans1 & ans2;  // AND operation of both XOR's is the answer.\n        \n    }\n};"
    },
    {
        "title": "Add to Array-Form of Integer",
        "algo_input": "The array-form of an integer num is an array representing its digits in left to right order.\n\n\n\tFor example, for num = 1321, the array form is [1,3,2,1].\n\n\nGiven num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.\n\n&nbsp;\nExample 1:\n\nInput: num = [1,2,0,0], k = 34\nOutput: [1,2,3,4]\nExplanation: 1200 + 34 = 1234\n\n\nExample 2:\n\nInput: num = [2,7,4], k = 181\nOutput: [4,5,5]\nExplanation: 274 + 181 = 455\n\n\nExample 3:\n\nInput: num = [2,1,5], k = 806\nOutput: [1,0,2,1]\nExplanation: 215 + 806 = 1021\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 104\n\t0 &lt;= num[i] &lt;= 9\n\tnum does not contain any leading zeros except for the zero itself.\n\t1 &lt;= k &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n        return list(str(int(\"\".join(map(str,num)))+k))",
        "solution_js": "var addToArrayForm = function(num, k) {\n    const length = num.length;\n    let digit = 0, index = length-1;\n    while(k > 0 || digit > 0) {\n        if(index >= 0) {\n            digit = digit + num[index] + k%10;\n            num[index] = digit%10;\n        }\n        else {\n            digit = digit + k%10;\n            num.unshift(digit%10);\n        }\n        digit = digit > 9 ? 1 : 0;\n        k = parseInt(k/10);\n        index--;\n    }\n    if(digit) num.unshift(digit);\n    return num;\n};",
        "solution_java": "class Solution {\n    public List<Integer> addToArrayForm(int[] num, int k) {\n        List<Integer> res = new ArrayList<>();\n        \n        int i = num.length;\n        while(--i >= 0 || k > 0) {\n            if(i >= 0)\n                k += num[i];\n            \n            res.add(k % 10);\n            k /= 10;\n        }\n        Collections.reverse(res);\n        \n        return res;\n    }\n}",
        "solution_c": "Time: O(max(n,Log k))  Space: O(1)\n\nclass Solution {\npublic:\n    vector<int> addToArrayForm(vector<int>& num, int k) {\n        vector<int> res;\n        int i=size(num)-1;\n        int c=0,sum;\n        while(i>=0){\n            sum=num[i]+k%10+c;\n            res.push_back(sum%10);\n            c=sum/10;\n            k/=10;i--;\n        }\n        while(k){\n            sum=k%10+c;\n            res.push_back(sum%10);\n            c=sum/10;\n            k/=10;\n        }\n        if(c)\n            res.push_back(c);\n        reverse(begin(res),end(res));\n        return res;\n    }\n};\n\n--> Approach 2 \n\nclass Solution {\npublic:\n    vector<int> addToArrayForm(vector<int>& num, int k) {\n        vector<int> res;\n        int i=size(num)-1;\n        int sum;\n        while(i>=0){\n            sum=num[i]+k;\n            res.push_back(sum%10);\n            k=sum/10;i--;\n        }\n        while(k){\n            res.push_back(k%10);\n            k/=10;\n        }\n        reverse(begin(res),end(res));\n        return res;\n    }\n};"
    },
    {
        "title": "Best Team With No Conflicts",
        "algo_input": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.\n\nHowever, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.\n\nGiven two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.\n\n&nbsp;\nExample 1:\n\nInput: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput: 34\nExplanation:&nbsp;You can choose all the players.\n\n\nExample 2:\n\nInput: scores = [4,5,6,5], ages = [2,1,2,1]\nOutput: 16\nExplanation:&nbsp;It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\n\n\nExample 3:\n\nInput: scores = [1,2,3,5], ages = [8,9,10,1]\nOutput: 6\nExplanation:&nbsp;It is best to choose the first 3 players. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= scores.length, ages.length &lt;= 1000\n\tscores.length == ages.length\n\t1 &lt;= scores[i] &lt;= 106\n\t1 &lt;= ages[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def bestTeamScore(self, scores, ages):\n        \"\"\"\n        :type scores: List[int]\n        :type ages: List[int]\n        :rtype: int\n        \"\"\"\n        l = len(scores)\n        mapped = [[ages[i], scores[i]] for i in range(l)]\n        mapped = sorted(mapped, key = lambda x : (x[0], x[1]))\n        dp = [i[1] for i in mapped]\n\n        for i in range(l):\n            for j in range(0, i):\n                if mapped[j][1] <= mapped[i][1]:\n                    dp[i] = max(dp[i], mapped[i][1] + dp[j])\n                elif mapped[i][0] == mapped[j][0]:\n                    dp[i] = max(dp[i], mapped[i][1] + dp[j])\n\n        return max(dp)",
        "solution_js": "var bestTeamScore = function(scores, ages) {\n    const players = scores.map((score, index) => ({ score, age: ages[index] }))\n        .sort((a,b) => a.score === b.score ? a.age - b.age : a.score - b.score);\n    let memo = new Array(scores.length).fill(0).map(_ => new Array());\n    return dfs(0, 0);\n    \n    function dfs(maxAge, index) {\n        if (index === players.length) {\n            return 0;\n        }\n        \n        if (memo[index][maxAge] !== undefined) {\n            return memo[index][maxAge];\n        }\n        \n        let max = 0;\n        let currentPlayer = players[index];\n\n        // cannot take because I'm too young and better than an old guy in my team\n        if (currentPlayer.age < maxAge) {\n            memo[index][maxAge] = dfs(maxAge, index + 1)\n            return memo[index][maxAge];\n        }\n        \n        // take\n        max = Math.max(max, currentPlayer.score + dfs(Math.max(maxAge, currentPlayer.age), index + 1));\n        \n        // not take\n        max = Math.max(max, dfs(maxAge, index + 1));\n        \n        memo[index][maxAge] = max;\n        return max;\n    }\n};",
        "solution_java": "class Solution {\n    public int bestTeamScore(int[] scores, int[] ages) {\n        int n = scores.length;\n        // combine the arrays for ease in processing\n        int[][] combined = new int[n][2];\n        for (int i = 0; i < n; i++) {\n            combined[i][0] = ages[i];\n            combined[i][1] = scores[i];\n        }\n        \n        // sort the arrays by age and scores\n        Arrays.sort(combined, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n        \n\t\t// find max answer between all possible teams\n        int ans = 0;\n        for (int i = 0; i < n; i++)\n            ans = Math.max(ans, recurse(combined, i));\n        \n        return ans;\n    }\n    \n    private int recurse(int[][] combined, int cur) {\n        // base case\n        if (cur == -1)\n            return 0;\n        \n        // try teaming player with others if no conflict found\n        int ans = 0;\n        for (int prev = 0; prev < cur; prev++) {\n            if (combined[cur][0] == combined[prev][0] || combined[cur][1] >= combined[prev][1])\n                ans = Math.max(ans, recurse(combined, prev));\n        }\n        \n        // add score of current player\n        ans += combined[cur][1];\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[1005][1005];\n    int bestTeamScore(vector<int>& scores, vector<int>& ages) {\n        vector<vector<int>>grp;\n        for(int i=0;i<scores.size();i++)\n        {\n            grp.push_back({scores[i],ages[i]});\n        }\n        sort(grp.begin(),grp.end());     \n        memset(dp,-1,sizeof(dp));\n        return recur(grp,0,ages.size(),0);\n    }\n    \n    int recur(vector<vector<int>>&grp , int i , int n , int maxiAge)\n    {\n        if(i==n)\n            return 0;\n        if(dp[i][maxiAge]!=-1)\n            return dp[i][maxiAge];\n        // score is already greater than previous socre we need to check age \n        // if current age is  greater than previous maxiAge then two choices\n        if(grp[i][1]>=maxiAge)\n        {\n            return dp[i][maxiAge] = max(grp[i][0]+recur(grp,i+1,n,grp[i][1]),recur(grp,i+1,n,maxiAge));\n        }\n        return dp[i][maxiAge] = recur(grp,i+1,n,maxiAge);\n    }\n};"
    },
    {
        "title": "Reduce Array Size to The Half",
        "algo_input": "You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.\n\nReturn the minimum size of the set so that at least half of the integers of the array are removed.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,3,3,3,5,5,5,2,2,7]\nOutput: 2\nExplanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\n\n\nExample 2:\n\nInput: arr = [7,7,7,7,7,7]\nOutput: 1\nExplanation: The only possible set you can choose is {7}. This will make the new array empty.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 105\n\tarr.length is even.\n\t1 &lt;= arr[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minSetSize(self, arr: List[int]) -> int:\n        n = len(arr)\n        half = n // 2\n        \n        c = Counter(arr)\n        s = 0\n        ans = 0\n        \n        for num, occurances in c.most_common():\n            s += occurances\n            ans += 1\n            if s >= half:\n                return ans\n        return ans",
        "solution_js": "var minSetSize = function(arr) {\n  let halfSize = arr.length / 2;\n  const numsCount = Object.values(getNumsCount(arr)).sort((a, b) => b - a); // get the frequencies in an array sorted in descending order\n  let setSize = 0;\n  if (numsCount[0] >= halfSize) return 1; // if the highest frequency is greater than or equal to half of the array size, then you already have your smallest set size of 1\n  for (let i = 0; i < numsCount.length; i++) {\n    let numCount = numsCount[i];\n    if (halfSize > 0) {\n      setSize++;\n      halfSize -= numCount;\n    } else {\n      return setSize;\n    };\n  };\n};\n\nvar getNumsCount = function (arr) {\n  let eleCounts = {};\n  for (let i = 0; i < arr.length; i++) {\n    let num = arr[i];\n    if (!eleCounts[num]) {\n      eleCounts[num] = 1;\n    } else {\n      eleCounts[num]++;\n    };\n  };\n  return eleCounts;\n};",
        "solution_java": "class Solution {\n    public int minSetSize(int[] arr) {\n        int size=arr.length;\n        int deletedSize=0;\n        int countIteration=0;\n        Map<Integer,Integer> hashMap=new HashMap<>();\n        Queue<Map.Entry<Integer,Integer>> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());\n        \n        for(int i=0;i<size;i++)\n        {\n            if(hashMap.get(arr[i])!=null)\n               hashMap.put(arr[i],hashMap.get(arr[i])+1);\n            else \n                hashMap.put(arr[i],1);\n        }\n        \n        for(Map.Entry<Integer,Integer> entry:hashMap.entrySet())\n        {\n            queue.add(entry);\n        }\n        \n        while(!queue.isEmpty())\n        {\n            int totalOccurence=queue.poll().getValue();\n            deletedSize+=totalOccurence; \n            countIteration++;\n            if(deletedSize>=size/2)\n                return countIteration;\n           \n        }\n        return countIteration;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minSetSize(vector<int>& arr) {\n        const int n=1e5+10 ;\n        int a[n]={0} ;\n        for(int i=0 ;i<arr.size() ;i++)\n        {\n            a[arr[i]]++ ;\n        }\n        priority_queue<int> maxh ;\n        for(int i=0; i<n ;i++)\n        {\n            maxh.push(a[i]) ;\n        }\n        int sum=0 ;\n        int count=0 ;\n\n        while(sum<(arr.size()/2))\n        {\n            sum=sum+maxh.top() ;\n            maxh.pop() ;\n            count++ ;\n        }\n        return count ;\n\n    }\n};"
    },
    {
        "title": "Binary Tree Coloring Game",
        "algo_input": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.\n\nInitially, the first player names a value x with 1 &lt;= x &lt;= n, and the second player names a value y with 1 &lt;= y &lt;= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.\n\nThen, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)\n\nIf (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.\n\nYou are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput: true\nExplanation: The second player can choose the node with value 2.\n\n\nExample 2:\n\nInput: root = [1,2,3], n = 3, x = 1\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t1 &lt;= x &lt;= n &lt;= 100\n\tn is odd.\n\t1 &lt;= Node.val &lt;= n\n\tAll the values of the tree are unique.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def findParent(self,node,par = None):\n        if node:\n            self.parent[node.val] = par\n            self.findParent(node.left,node)\n            self.findParent(node.right,node)\n    \n    def traverse(self,node,done):\n        if node:\n            if node in done: return 0\n            done[node] = True\n            a = self.traverse(self.parent[node.val],done)\n            b = self.traverse(node.left,done)\n            c = self.traverse(node.right,done)\n            return a + b + c + 1\n        return 0\n    \n    def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n        self.parent = {}\n        self.findParent(root)\n        parent = self.parent[x]\n        node = root if root.val == x else parent.left if parent and parent.left and parent.left.val == x else parent.right\n        up = self.traverse(parent,{node:True})\n        left = self.traverse(node.left,{node:True})\n        right = self.traverse(node.right,{node:True})\n        return (up > left + right) or (left > up + right) or (right > up + left)",
        "solution_js": "var left, right, val;\nvar btreeGameWinningMove = function(root, n, x) {\n    function count(node) {\n        if (node == null)\n            return 0;\n        var l = count(node.left);\n        var r = count(node.right);\n        if (node.val == val) {\n            left = l;\n            right = r;\n        }\n        return l + r + 1;\n    }\n    val = x;\n    count(root);\n    return Math.max(n - left - right - 1, Math.max(left, right)) > n / 2;\n};",
        "solution_java": "\tclass Solution {\n\tint xkaLeft=0,xkaRight=0;\n\tpublic int size(TreeNode node, int x)\n\t{\n\t\tif(node==null)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tint ls=size(node.left,x);\n\t\tint rs=size(node.right,x);\n\n\t\tif(node.val==x)\n\t\t{\n\t\t\txkaLeft=ls;\n\t\t\txkaRight=rs;\n\t\t}\n\n\t\treturn ls+rs+1;\n\t}\n\tpublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n\n\t\tsize(root,x);\n\t\tint parent=n-(xkaLeft+xkaRight+1);\n\t\tint max=Math.max(parent,Math.max(xkaRight,xkaLeft));\n\t\tif(max>n/2)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    // nodex means \"node with val = x\" \n    // Idea behind this is to block either nodex's parent or it's left child or right child. Block means we will chose that node as nodey. Why? because it will devide the tree in two parts, one for player 1 and other for player 2. Then we have to just take the maximum no of nodes we can get, from these three nodes as head, and if max is greater than n/2, means we can will.\n    TreeNode *nodex, *parentx;\n    Solution(){\n        nodex = NULL;\n        parentx = NULL;\n    }\n    int count(TreeNode *root)\n    {\n        if (root == NULL)\n            return 0;\n        int a = count(root->left);\n        int b = count(root->right);\n        return a + b + 1;\n    }\n    bool findx(TreeNode *root, int x)\n    {\n        if (root == NULL)\n            return false;\n        parentx = root;\n        if (root->val == x)\n        {\n            nodex = root;\n            return true; \n        }\n        bool a = findx(root->left, x);\n        if (a)\n            return true;\n        bool b = findx(root->right, x);\n        return b;\n    }\n    bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n        findx(root, x); // Find the node which has val = x\n        int p = n - count(nodex); // Count the no of nodes of blue color, if we decide to take parent of nodex as nodey\n        int r = count(nodex->right); // Count the no of nodes of blue color, if we decide to take right child of nodex as nodey\n        int l = count(nodex->left); // Count the no of nodes of blue color, if we decide to take left child of nodex as nodey\n        int mx = max(p,r);\n        mx = max(mx, l); // max of all three possible scenarios\n        if (mx > n/2)\n            return true;\n        else\n            return false;\n    }\n};"
    },
    {
        "title": "Word Search",
        "algo_input": "Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n\nThe word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\nOutput: true\n\n\nExample 2:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\nOutput: true\n\n\nExample 3:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn = board[i].length\n\t1 &lt;= m, n &lt;= 6\n\t1 &lt;= word.length &lt;= 15\n\tboard and word consists of only lowercase and uppercase English letters.\n\n\n&nbsp;\nFollow up: Could you use search pruning to make your solution faster with a larger board?\n",
        "solution_py": "class Solution:\n    def exist(self, board: List[List[str]], word: str) -> bool:\n        m = len(board)\n        n = len(board[0])\n        \n        marked = set() # visited by the dfs\n        def dfs(cell: Tuple[int, int], wp: int) -> bool:\n            i = cell[0]\n            j = cell[1]\n            \n            if wp == len(word):\n                return True\n            \n            # Get appropriate neighbours and perform dfs on them\n            # When going on dfs, we mark certain cells, we should remove # \n            #them from the marked list after we return from the dfs\n            marked.add((i,j))\n            neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]\n            for x, y in neibs:\n                if (\n                        x < 0 or y < 0 or\n                        x >= m or y >= n or\n                        (x, y) in marked or\n                        board[x][y] != word[wp]\n                ):\n                    continue\n                \n                if dfs((x,y), wp + 1):\n                    return True\n                \n            marked.remove((i,j))\n            return False\n                \n        \n        for i in range(m):\n            for j in range(n):\n                if board[i][j] == word[0]:\n                    if dfs((i,j), 1):\n                        return True\n        \n        return False",
        "solution_js": "/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\n\nlet visited\n\nconst getNeighbours=([i,j],board)=>{\n    let arr=[];\n    if(i>0 && !visited[i-1][j])arr.push([i-1,j])\n    if(j>0 && !visited[i][j-1])arr.push([i,j-1])\n    if(i+1<board.length && !visited[i+1][j])arr.push([i+1,j])\n    if(j+1<board[i].length && !visited[i][j+1])arr.push([i,j+1])\n    return arr;\n}\nconst dfs=([i,j],board, word,index)=>{\n if(word[index]!==board[i][j])return false;\n if(word.length-1===index)return true;\n    visited[i][j]=true;\n    let neighbours=getNeighbours([i,j],board,word,index)||[];\n\n    for(let k=0;k<neighbours.length;k++){\n        let temp_result=dfs(neighbours[k],board, word,index+1);\n        if(temp_result===true)return true;\n    }\n    visited[i][j]=false;\n    return false;\n\n}\n\nvar exist = function(board, word) {\n    visited=[];\n    for(let i=0;i<board.length;i++){\n        visited[i]=[];\n        for(let j=0;j<board[i].length;j++){\n           visited[i][j]=false;\n        }\n    }\n   for(let i=0;i<board.length;i++){\n        for(let j=0;j<board[i].length;j++){\n           if(board[i][j]===word[0]){\n               let result=dfs([i,j],board,word,0);\n               if(result===true)return true;\n           }\n        }\n    }\n\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean exist(char[][] board, String word) {\n        boolean vis[][]=new boolean[board.length][board[0].length];\n        for(int i=0;i<board.length;i++){\n           for(int j=0;j<board[0].length;j++){\n              if(word.charAt(0)==board[i][j]){\n              boolean is=isexist(i,j,board,vis,1,word);\n              if(is) return true;\n              }\n           }\n        }\n        return false;\n    }\n\n    static int dir[][]={{1,0},{0,1},{-1,0},{0,-1}};\n\n    static boolean isexist(int r, int c,char board[][],boolean vis[][],\n                           int idx,String word){\n        if(idx==word.length()) return true;\n        vis[r][c]=true;\n        for(int k=0;k<4;k++){\n            int rd=r+dir[k][0];\n            int cd=c+dir[k][1];\n            if(rd<0 || cd<0 || rd>=board.length || cd>=board[0].length\n              || vis[rd][cd]==true ||\n               board[rd][cd]!=word.charAt(idx)) continue;\n            boolean is=isexist(rd,cd,board,vis,idx+1,word);\n            if(is) return true;\n        }\n        vis[r][c]=false;\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool solve(int i,int j,int &m,int &n,vector<vector<char>> &board,string &str,int s){\n        if(s>=str.length()){\n            return true;\n        }\n        if(i<0||j<0||i>=m||j>=n||board[i][j]=='#'){\n            return false;\n        }\n        char c = board[i][j];\n        board[i][j] = '#';\n        bool a = false;\n        if(c==str[s])\n        a = solve(i+1,j,m,n,board,str,s+1)||solve(i-1,j,m,n,board,str,s+1)||solve(i,j-1,m,n,board,str,s+1) ||  solve(i,j+1,m,n,board,str,s+1);\n        board[i][j] = c;\n        return a;\n    }\n    bool exist(vector<vector<char>>& board, string word) {\n        int i,j,m=board.size(),n=board[0].size();\n        for(i = 0; i < m; i++){\n            for(j = 0; j < n; j++){\n                if(board[i][j]==word[0] && solve(i,j,m,n,board,word,0)){\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Subsets II",
        "algo_input": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set).\n\nThe solution set must not contain duplicate subsets. Return the solution in any order.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,2]\nOutput: [[],[1],[1,2],[1,2,2],[2],[2,2]]\nExample 2:\nInput: nums = [0]\nOutput: [[],[0]]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 10\n\t-10 &lt;= nums[i] &lt;= 10\n\n",
        "solution_py": "class Solution:\n    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n        ans = []\n        nums.sort()\n        def subset(p, up):\n            if len(up) == 0:\n                if p not in ans:\n                    ans.append(p)\n                return \n            ch = up[0]\n            subset(p+[ch], up[1:])\n            subset(p, up[1:])\n        subset([], nums)\n        return ans",
        "solution_js": "var subsetsWithDup = function(nums) {\n    let result = [];\n    //sort the nums to avoid duplicates;\n    nums.sort((a,b) => a -b);\n    result.push([]);\n\n    let startIdx = 0;\n    let endIdx = 0;\n\n    for(let i =0; i<nums.length; i++){\n        let current = nums[i];\n        startIdx = 0;\n\n        //check for duplicates and get the idx of last subset\n        if(i> 0 && nums[i] === nums[i-1]){\n            startIdx = endIdx +1;\n        }\n        endIdx = result.length - 1;\n\n        for(let j = startIdx; j< endIdx+1; j++){\n            let set1 = result[j].slice(0);\n            set1.push(current);\n            result.push(set1);\n        }\n    }\n\n    return result;\n\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> subsetsWithDup(int[] nums) {\n        // Sort the input array to handle duplicates properly\n        Arrays.sort(nums);\n        // Start the recursion with an empty prefix list\n        return subset(new ArrayList<Integer>(), nums);\n    }\n    \n    // Recursive function to generate subsets\n    public List<List<Integer>> subset(ArrayList<Integer> prefix, int[] nums) {\n        List<List<Integer>> result = new ArrayList<>();\n        \n        // Base case: If there are no elements in nums, add the current prefix to result\n        if (nums.length == 0) {\n            result.add(new ArrayList<>(prefix));\n            return result;\n        }\n        \n        // Include the first element of nums in the prefix\n        ArrayList<Integer> withCurrent = new ArrayList<>(prefix);\n        withCurrent.add(nums[0]);\n        \n        // Recursive call with the first element included\n        List<List<Integer>> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));\n        \n        List<List<Integer>> right = new ArrayList<>();\n        \n        // Check for duplicates in the prefix and decide whether to include the first element again\n        if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {\n            // If the current element is a duplicate, don't include it in the prefix\n            // This avoids generating duplicate subsets\n        } else {\n            // If the current element is not a duplicate, include it in the prefix\n            right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));\n        }\n        \n        // Combine the subsets with and without the current element\n        left.addAll(right);\n        return left;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> ans;\n    void recur(vector<int>& nums, int i, vector<int> vec){\n        if(i > nums.size()){\n            return;\n        }\n        for(int j = i; j < nums.size(); j++){\n            vec.push_back(nums[j]);\n\n            vector<int> temp = vec;\n            sort(vec.begin(), vec.end());\n\n            if(find(ans.begin(), ans.end(), vec) == ans.end()){\n                ans.push_back(vec);\n            }\n\n            recur(nums, j + 1, vec);\n\n            //can't just pop_back any need to pop_back the one we added\n            vec = temp;\n            vec.pop_back();\n        }\n    }\n\n    vector<vector<int>> subsetsWithDup(vector<int>& nums) {\n        vector<int> vec;\n        ans.push_back(vec);\n        recur(nums, 0, vec);\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Score of Parentheses",
        "algo_input": "Given a balanced parentheses string s, return the score of the string.\n\nThe score of a balanced parentheses string is based on the following rule:\n\n\n\t\"()\" has score 1.\n\tAB has score A + B, where A and B are balanced parentheses strings.\n\t(A) has score 2 * A, where A is a balanced parentheses string.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"()\"\nOutput: 1\n\n\nExample 2:\n\nInput: s = \"(())\"\nOutput: 2\n\n\nExample 3:\n\nInput: s = \"()()\"\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 50\n\ts consists of only '(' and ')'.\n\ts is a balanced parentheses string.\n\n",
        "solution_py": "class Solution:\n    def scoreOfParentheses(self, s: str) -> int:\n        \n        level = 0\n        result = 0\n        prev = \"\"\n        \n        for c in s:           \n            if c == \"(\":\n                level += 1\n            if c == \")\":\n                if prev == \"(\":\n                    result += 2 ** (level - 1)\n                level -= 1                \n            prev = c\n            \n        return result",
        "solution_js": "var scoreOfParentheses = function(s) {\n    let len = s.length, pwr = 0, ans = 0;\n\n    for (let i = 1; i < len; i++){\n        if (s.charAt(i) === \"(\"){\n            pwr++;\n        }\n        else if (s.charAt(i-1) === \"(\"){\n            ans += 1 << pwr--;\n        }\n        else{\n            pwr--;\n        }\n    }\n\n    return ans;\n}",
        "solution_java": "class Solution {\n    public int scoreOfParentheses(String s) {\n        Stack<Integer> st = new Stack<>();\n        int score = 0;\n        for(int i = 0; i < s.length(); i++){\n            char ch = s.charAt(i);\n            if(ch == '('){\n                st.push(score);\n                score = 0;\n            }\n            else {\n                score = st.pop() + Math.max(2 * score, 1);\n            }\n        }\n        return score;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int scoreOfParentheses(string s) {\n        stack<int> st;\n        int score = 0;\n        for(int i = 0; i < s.size(); i++){\n            if(s[i] == '('){\n                st.push(score);\n                score = 0;\n            }\n            else {\n                score = st.top() + max(2 * score, 1);\n                st.pop();\n            }\n        }\n        return score;\n    }\n};"
    },
    {
        "title": "Implement Magic Dictionary",
        "algo_input": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.\n\nImplement the&nbsp;MagicDictionary&nbsp;class:\n\n\n\tMagicDictionary()&nbsp;Initializes the object.\n\tvoid buildDict(String[]&nbsp;dictionary)&nbsp;Sets the data structure&nbsp;with an array of distinct strings dictionary.\n\tbool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]\nOutput\n[null, null, false, true, false, false]\n\nExplanation\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;dictionary.length &lt;= 100\n\t1 &lt;=&nbsp;dictionary[i].length &lt;= 100\n\tdictionary[i] consists of only lower-case English letters.\n\tAll the strings in&nbsp;dictionary&nbsp;are distinct.\n\t1 &lt;=&nbsp;searchWord.length &lt;= 100\n\tsearchWord&nbsp;consists of only lower-case English letters.\n\tbuildDict&nbsp;will be called only once before search.\n\tAt most 100 calls will be made to search.\n\n",
        "solution_py": "class MagicDictionary:\n\n\tdef __init__(self):\n\t\tTrieNode = lambda : defaultdict(TrieNode)\n\t\tself.root = TrieNode()\n\n\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\tfor s in dictionary:\n\t\t\tcur = self.root\n\t\t\tfor c in s: cur = cur[ord(c)-ord('a')]\n\t\t\tcur['$']=True\n\n\tdef search(self, searchWord: str) -> bool:\n\t\tdef find(i,cur,mis):\n\t\t\tif i==len(searchWord) and mis==0: return('$' in cur)\n\t\t\tif mis < 0: return False\n\t\t\tif i==len(searchWord) and mis!=0: return False\n\t\t\tind = ord(searchWord[i])-ord('a')\n\t\t\tans = False\n\t\t\tfor j in range(26):\n\t\t\t\tif j in cur:\n\t\t\t\t\tif(j!=ind):\n\t\t\t\t\t\tans |= find(i+1,cur[j],mis-1)\n\t\t\t\t\telse: ans |= find(i+1,cur[j],mis)\n\t\t\treturn ans\n\t\t\t\n\t\treturn find(0,self.root,1)",
        "solution_js": "function TrieNode(){\n    this.children = new Map()\n    this.endOfWord = false;\n}\n\nvar MagicDictionary = function() {\n    this.root = new TrieNode()\n};\n\nMagicDictionary.prototype.buildDict = function(dictionary) {\n    for(let word of dictionary){\n        let curr = this.root\n        for(let letter of word){\n            let map = curr.children\n            if(!map.has(letter)) map.set(letter, new TrieNode())\n            curr = map.get(letter)\n        }\n        curr.endOfWord = true\n    }\n};\n\nMagicDictionary.prototype.search = function(searchWord){\n    return  dfs(this.root, searchWord, 0, 0)\n}\n\nfunction dfs(root, str, i, count){\n    if(count>1) return false\n    if(i==str.length) return count == 1 && root.endOfWord\n\t\n    for(let [char, node] of root.children){\n        let c = 0;\n        if(char != str[i]) c = 1\n        if(dfs(node, str, i+1, count+c)) return true;\n    }\n    return false\n}",
        "solution_java": "class MagicDictionary {\n    private String[] dictionary;\n    \n    public MagicDictionary() {}\n    \n    public void buildDict(String[] dictionary) {\n        this.dictionary = dictionary;\n    }\n    \n    public boolean search(String searchWord) {\n        for (String dictWord: this.dictionary) {\n            if (this.match(searchWord, dictWord, 1))\n                return true;\n        }\n        \n        return false;\n    }\n    \n    private boolean match(String s, String t, int expectedDiff) {\n        if (s.length() != t.length())\n            return false;\n        \n        int diff = 0;\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) != t.charAt(i))\n                diff++;\n            if (diff > expectedDiff)\n                return false;\n        }\n        \n        return diff == expectedDiff;\n    }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */",
        "solution_c": "struct node{\n\tbool end = false;\n\tnode *children[26];\n};\n\nclass MagicDictionary {\npublic:\n\n\tnode* root;\n\tvoid insert(string&s){\n\t\tnode* cur = root;\n\t\tfor(char&c : s){\n\t\t\tif(!cur->children[c-'a']){\n\t\t\t\tcur->children[c-'a'] = new node();\n\t\t\t}\n\t\t\tcur = cur->children[c-'a'];\n\t\t}\n\t\tcur->end=true;\n\t}\n\tMagicDictionary() {\n\t\troot = new node();\n\t}\n\n\tvoid buildDict(vector<string> dictionary) {\n\t\tfor(string&s : dictionary)insert(s);\n\t}\n\t\n\tbool find(int i, string& s,node* cur, int mismatch){\n\t\tif(i == s.size() and mismatch==0) return cur->end;\n\t\tif(mismatch<0)return false;\n\t\tif((!cur || i == s.size()) and mismatch!=0) return false;\n\n\t\tint ind = s[i]-'a';\n\t\tbool ans = false;\n\t\tfor(int j=0;j<26;j++){\n\t\t\tif(cur->children[j]){\n\t\t\t\tif(j!=ind){\n\t\t\t\t\tans |= find(i+1,s,cur->children[j],mismatch-1);\n\t\t\t\t}else{\n\t\t\t\t\tans |= find(i+1,s,cur->children[j],mismatch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\tbool search(string searchWord) {\n\t\treturn find(0,searchWord,root,1);\n\t}\n};"
    },
    {
        "title": "Reorder Routes to Make All Paths Lead to the City Zero",
        "algo_input": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.\n\nRoads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.\n\nThis year, there will be a big event in the capital (city 0), and many people want to travel to this city.\n\nYour task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.\n\nIt's guaranteed that each city can reach city 0 after reorder.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput: 3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\nExample 2:\n\nInput: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput: 2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\nExample 3:\n\nInput: n = 3, connections = [[1,0],[2,0]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 5 * 104\n\tconnections.length == n - 1\n\tconnections[i].length == 2\n\t0 &lt;= ai, bi &lt;= n - 1\n\tai != bi\n\n",
        "solution_py": "from collections import defaultdict\nclass Solution:\n    def minReorder(self, n: int, connections: List[List[int]]) -> int:\n        count, stack, visited = 0, [ 0 ], set() #Add root node to stack\n        neighbours = defaultdict(list) #To store neighbours\n\t\tadjacency = defaultdict(list) #To store adjacency\n        for i, j in connections:\n            adjacency[i].append(j)\n            neighbours[i].append(j)\n            neighbours[j].append(i)\n        while stack:\n            current = stack.pop()\n            if current in visited:\n                continue\n            else:\n                visited.add(current)\n            for i in neighbours[current]:\n                if i in visited:\n                    continue\n                if current not in adjacency[i]:\n                    count += 1\n                stack.append(i)\n        return count",
        "solution_js": "var minReorder = function(n, connections) {\n    // from: (<from city>, [<to cities>])\n    // to: (<to city>, [<from cities>])\n    const from = new Map(), to = new Map();\n\n    // Function to insert in values in map\n    const insert = (map, key, value) => {\n        if(map.has(key)){\n            const arr = map.get(key);\n            arr.push(value);\n            map.set(key, arr);\n        } else {\n            map.set(key, [value]);\n        }\n    }\n\n    // Set all values in both maps\n    for(const [a,b] of connections){\n        insert(from, a, b);\n        insert(to, b, a);\n    }\n\n    // Queue: cities to visit\n    const queue = [0], visited = new Set();\n    let count = 0;\n\n    while(queue.length) {\n        const cur = queue.shift(); // First element in queue\n\n        // Check values in first map\n        if(from.has(cur)){\n            for(const x of from.get(cur)){\n                // If visited, do nothing else add to queue\n                if(visited.has(x)) continue;\n                queue.push(x);\n                count++; // Change direction of this path\n            }\n        }\n\n        if(to.has(cur)){\n            // If visited, do nothing else add to queue\n            for(const x of to.get(cur)){\n                if(visited.has(x)) continue;\n                queue.push(x);\n            }\n        }\n\n        visited.add(cur); // Mark city as visited\n    }\n\n    return count\n};",
        "solution_java": "class Solution {\n    int dfs(List<List<Integer>> al, boolean[] visited, int from) {\n        int change = 0;\n        visited[from] = true;\n        for (var to : al.get(from))\n            if (!visited[Math.abs(to)])\n                change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);\n        return change;   \n    }\n    public int minReorder(int n, int[][] connections) {\n        List<List<Integer>> al = new ArrayList<>();\n        for(int i = 0; i < n; ++i) \n            al.add(new ArrayList<>());\n        for (var c : connections) {\n            al.get(c[0]).add(c[1]);\n            al.get(c[1]).add(-c[0]);\n        }\n        return dfs(al, new boolean[n], 0);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> Radj[50001],adj[50001] ,visited;\n    int bfs(){\n        int edges = 0 ;\n        queue<int> q ;\n        q.push(0) ;\n\n        while(q.size()){\n            auto src = q.front() ; q.pop() ;\n            visited[src] = 1 ;\n\n            for(auto &nbr : adj[src]){\n                if(visited[nbr]) continue ;\n                //this connection needs reverse orientation\n                ++edges ;\n                q.push(nbr) ;\n            }\n\n            for(auto &nbr : Radj[src]){\n                if(visited[nbr]) continue ;\n                q.push(nbr) ;\n            }\n        }\n\n        return edges ;\n    }\n    int minReorder(int n, vector<vector<int>>& connections) {\n        visited.resize(n,0);\n        for(auto &x : connections) adj[x[0]].push_back(x[1]) , Radj[x[1]].push_back(x[0]);\n        return bfs() ;\n    }\n};"
    },
    {
        "title": "Find the Difference of Two Arrays",
        "algo_input": "Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:\n\n\n\tanswer[0] is a list of all distinct integers in nums1 which are not present in nums2.\n\tanswer[1] is a list of all distinct integers in nums2 which are not present in nums1.\n\n\nNote that the integers in the lists may be returned in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,3], nums2 = [2,4,6]\nOutput: [[1,3],[4,6]]\nExplanation:\nFor nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].\n\nExample 2:\n\nInput: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput: [[3],[]]\nExplanation:\nFor nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 1000\n\t-1000 &lt;= nums1[i], nums2[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def findDifference(self, nums1, nums2):\n        \"\"\"\n        :type nums1: List[int]\n        :type nums2: List[int]\n        :rtype: List[List[int]]\n        \"\"\"\n        a = []\n        for i in range(len(nums1)):\n            if nums1[i] not in nums2:\n                a.append(nums1[i])\n        b = []\n        for i in range(len(nums2)):\n            if nums2[i] not in nums1:\n                b.append(nums2[i])\n\n        c = [list(set(a))] + [list(set(b))]\n\n        return c",
        "solution_js": "var findDifference = function(nums1, nums2) {\n    const s1 = new Set(nums1);\n    const s2 = new Set(nums2);\n\n    const a1 = [...s1].filter(x => !s2.has(x));\n    const a2 = [...s2].filter(x => !s1.has(x));\n\n    return [a1, a2];\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {\n        Set<Integer> set1 = new HashSet<>(); // create 2 hashsets\n        Set<Integer> set2 = new HashSet<>();\n        for(int num : nums1){ set1.add(num); } // add nums1 elements to set1\n        for(int num : nums2){ set2.add(num); } // add nums2 elements to set2\n\n        List<List<Integer>> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return\n        resultList.add(new ArrayList<>());\n        resultList.add(new ArrayList<>());\n\n        for(int num : set1){ // just iterate to all elements of set1\n            if(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.\n        }\n        for(int num : set2){ // just iterate to all elements of set2\n            if(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1\n        }\n        return resultList;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {\n\t//unordered_set is implemented using a hash table where keys are hashed into indices of a hash table\n\t// all operations take O(1) on average\n        unordered_set<int> n1;\n        unordered_set<int> n2;\n        for(int i=0;i<nums1.size();i++)\n            n1.insert(nums1[i]);\n        \n        for(int i=0;i<nums2.size();i++)\n            n2.insert(nums2[i]);\n        \n        vector<int> ans1;\n\t\tvector<vector<int>> ans;\n        for(int x:n1)\n        {\n            if(n2.find(x)==n2.end())\n                ans1.push_back(x);\n        }\n\t\tans.push_back(ans1);\n\t\tans1.clear();\n        for(int x:n2)\n        {\n            if(n1.find(x)==n1.end())\n                ans1.push_back(x);\n        }\n        ans.push_back(ans1);\n        return ans;\n    }\n};"
    },
    {
        "title": "New 21 Game",
        "algo_input": "Alice plays the following game, loosely based on the card game \"21\".\n\nAlice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.\n\nAlice stops drawing numbers when she gets k or more points.\n\nReturn the probability that Alice has n or fewer points.\n\nAnswers within 10-5 of the actual answer are considered accepted.\n\n&nbsp;\nExample 1:\n\nInput: n = 10, k = 1, maxPts = 10\nOutput: 1.00000\nExplanation: Alice gets a single card, then stops.\n\n\nExample 2:\n\nInput: n = 6, k = 1, maxPts = 10\nOutput: 0.60000\nExplanation: Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.\n\n\nExample 3:\n\nInput: n = 21, k = 17, maxPts = 10\nOutput: 0.73278\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= k &lt;= n &lt;= 104\n\t1 &lt;= maxPts &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def new21Game(self, n: int, k: int, maxPts: int) -> float:\n        dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])\n        s = sum(dp)\n        for i in range(k):\n            dp.appendleft(s / maxPts)\n            s += dp[0] - dp.pop()\n\n        return dp[0]",
        "solution_js": "var new21Game = function(n, k, maxPts) {\n    if (k+maxPts <= n || k===0) return 1;\n\n    let dp = [];\n    dp[0] = 1;\n    dp[1] = 1/maxPts;\n\n    for (let i = 2; i <= n; i++) {\n        dp[i] = 0;\n\n        if (i <= k) {\n            dp[i] = (1 + 1/maxPts) * dp[i-1];\n        } else {\n            dp[i] = dp[i-1];\n        }\n        if (i > maxPts) {\n            dp[i] -= dp[i-maxPts-1] / maxPts;\n        }\n    }\n\n    return dp.reduce((acc, cur, idx) => {\n        if (idx >= k) {\n            acc += cur;\n        }\n        return acc;\n    }, 0)\n};",
        "solution_java": "class Solution {\n    public double new21Game(int n, int k, int maxPts) {\n        double[] dp = new double[k + maxPts];\n        dp[0] = 1;\n        for (int i = 0; i < k; i++){\n            for (int j = 1; j <= maxPts; j++){\n                dp[i + j] += dp[i] * 1.0 / maxPts;\n            }\n        }\n\n        double ans = 0;\n        for (int i = k; i < k + maxPts && i <= n; i++){\n            ans += dp[i];\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double new21Game(int n, int k, int maxPts) {\n        if(k==0 || n>=k+maxPts-1)\n            return (double) 1;\n        vector<double> dp(n+1);\n        dp[0]=1;\n        double sum = 0;\n        for(int i=0; i<n; i++)\n        {\n            if(i<k)\n                sum+=dp[i]; // reach f(2) by directly drawing f(2) or f(1) and f(1) \n            if(i>=maxPts)\n                sum-=dp[i-maxPts];\n                \n            dp[i+1] = sum/maxPts;\n        }\n        double ret = 0;\n        for(int i=k; i<=n; i++)\n            ret+=dp[i];\n        return ret;\n    }\n};"
    },
    {
        "title": "Walking Robot Simulation",
        "algo_input": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:\n\n\n\t-2: Turn left 90 degrees.\n\t-1: Turn right 90 degrees.\n\t1 &lt;= k &lt;= 9: Move forward k units, one unit at a time.\n\n\nSome of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.\n\nReturn the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).\n\nNote:\n\n\n\tNorth means +Y direction.\n\tEast means +X direction.\n\tSouth means -Y direction.\n\tWest means -X direction.\n\n\n&nbsp;\nExample 1:\n\nInput: commands = [4,-1,3], obstacles = []\nOutput: 25\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.\n\n\nExample 2:\n\nInput: commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput: 65\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.\n\n\nExample 3:\n\nInput: commands = [6,-1,-1,6], obstacles = []\nOutput: 36\nExplanation: The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= commands.length &lt;= 104\n\tcommands[i] is either -2, -1, or an integer in the range [1, 9].\n\t0 &lt;= obstacles.length &lt;= 104\n\t-3 * 104 &lt;= xi, yi &lt;= 3 * 104\n\tThe answer is guaranteed to be less than 231.\n\n",
        "solution_py": "class Solution:\n    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n        obs = set(tuple(o) for o in obstacles)\n        x = y = a = out = 0\n        move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}\n        for c in commands:\n            if c == -1:\n                a += 90\n            elif c == -2:\n                a -= 90\n            else:\n                direction = a % 360\n                dx, dy = move[direction]\n                for _ in range(c):\n                    if (x + dx, y + dy) in obs:\n                        break\n                    x += dx\n                    y += dy\n                out = max(out, x**2 + y**2)\n        return out",
        "solution_js": "/**\n * @param {number[]} commands\n * @param {number[][]} obstacles\n * @return {number}\n */\nvar robotSim = function(commands, obstacles) {  \n  let result = 0;\n  let currentPosition = [0, 0];\n  let currentDirection = 'top';\n  const mySet = new Set();\n  \n  // This is to have a O(1) check instead of doing a linear scan\n  obstacles.forEach(obs => {\n    mySet.add(`${obs[0]},${obs[1]}`);\n  }); // O(m)\n  \n  for (let i = 0; i < commands.length ; i++) { // O(n)\n    const move = commands[i];\n    if (move === -1) {\n      if (currentDirection === 'top') {\n        currentDirection = 'right';\n      } else if (currentDirection === 'right') {\n        currentDirection = 'down';\n      } else if (currentDirection === 'down') {\n        currentDirection = 'left';\n      } else {\n        currentDirection = 'top';\n      }\n    }\n    \n    if (move === -2) {\n      if (currentDirection === 'top') {\n        currentDirection = 'left';\n      } else if (currentDirection === 'left') {\n        currentDirection = 'down';\n      } else if (currentDirection === 'down') {\n        currentDirection = 'right';\n      } else {\n        currentDirection = 'top';\n      }\n    }\n    \n    if (move > 0) {\n      for (let i = 0; i < move; i++) { O(move)\n      const isY = (currentDirection === 'top' || currentDirection === 'down');\n      const isPositive = (currentDirection === 'top' || currentDirection === 'right');\n      \n      const newPosition = [currentPosition[0] + (!isY ? isPositive? 1: -1 : 0), currentPosition[1] + (isY ? isPositive ? 1 : -1 : 0)];\n      const positionString = `${newPosition[0]},${newPosition[1]}`;\n\n      if (!mySet.has(positionString)) {\n        currentPosition = newPosition;\n        result = Math.max(result, (Math.pow(currentPosition[0], 2) + Math.pow(currentPosition[1], 2)));\n      } else {\n        break;\n      }\n    }\n    }\n  }\n  return result;\n};",
        "solution_java": "class Solution {\n    public int robotSim(int[] commands, int[][] obstacles) {\n        int dir = 0; // states 0north-1east-2south-3west\n        int farthestSofar = 0;\n\n        int xloc = 0;\n        int yloc = 0;\n\n        Set<String> set = new HashSet<>();\n        for (int[] obs : obstacles) {\n            set.add(obs[0] + \",\" + obs[1]);\n        }\n\n        int steps;\n\n        for(int i: commands){\n\n            if( i == -1){//turn right 90\n                dir++;\n            }\n            else if (i == -2){//turn left 90\n                dir--;\n            }\n            else{//move forward value of i baring no obsticals\n                dir = dir%4;\n                if (dir== -1){\n                    dir = 3;\n                }\n                else if(dir == -3){\n                    dir = 1;\n                }\n                else if(dir == -2){\n                    dir = 2;\n                }\n                // dir %4 = -1 -> 3\n                // dir %4 = -2 -> 2\n                // dir %4 = -3 -> 1\n                if(dir == 0){\n                    steps = 0;\n                    while (steps < i && !set.contains((xloc) + \",\" + (yloc+1))) {\n                    yloc++;\n                    steps++;\n                    }\n                }\n                else if (dir == 1){\n                    steps = 0;\n                    while (steps < i && !set.contains((xloc+1) + \",\" + (yloc))) {\n                    xloc++;\n                    steps++;\n                    }\n                }\n                else if (dir == 2){\n                    steps = 0;\n                    while (steps < i && !set.contains((xloc) + \",\" + (yloc-1))) {\n                    yloc--;\n                    steps++;\n                    }\n                }\n                else{ //case dir == 3\n                    steps = 0;\n                    while (steps < i && !set.contains((xloc-1) + \",\" + (yloc))) {\n                    xloc--;\n                    steps++;\n                    }\n                }\n            }\n            farthestSofar = Math.max(farthestSofar, xloc*xloc + yloc*yloc);\n        }\n        return farthestSofar;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    //N--> left(-2):W, right(-1):E\n    //S--> left:E, right:W\n    //E--> left:N, right:S\n    //W--> left:S, right:N\n\n    vector<vector<int>> change= { //for direction change\n        {3,2},\n        {2,3},\n        {0,1},\n        {1,0}\n    };\n\n    vector<vector<int>> sign = { //signs for x and y coordinates movement\n        {0,1},//North\n        {0,-1},//south\n        {1,0},//east\n        {-1,0}//west\n    };\n\n    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {\n        set<vector<int>> s;\n        for(int i = 0;i<obstacles.size();i++){\n            s.insert(obstacles[i]);\n        }\n        int direction = 0;\n        int ans = 0;\n        int xi = 0,yi = 0;\n        for(int i = 0;i<commands.size();i++){\n            if(commands[i]<=9 && commands[i]>=1){\n                int signx = sign[direction][0];\n                int signy = sign[direction][1];\n                while(commands[i]){\n                    xi += signx;\n                    yi += signy;\n                    if(s.count({xi,yi})){\n                        xi -= signx;\n                        yi -= signy;\n                        break;\n                    }\n                    commands[i]--;\n                }\n            }\n            else{\n                direction = change[direction][commands[i]+2];\n            }\n            ans = max(ans,xi*xi+yi*yi);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Path Sum",
        "algo_input": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,3,1],[1,5,1],[4,2,1]]\nOutput: 7\nExplanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.\n\n\nExample 2:\n\nInput: grid = [[1,2,3],[4,5,6]]\nOutput: 12\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 200\n\t0 &lt;= grid[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n\n    def minPathSum(self, grid: List[List[int]]) -> int:\n        prev=[0]*len(grid[0])\n        for i in range(len(grid)):\n            temp=[0]*len(grid[0])\n            for j in range(len(grid[0])):\n                if i==0 and j==0:\n                    temp[j]=grid[i][j]\n                    continue\n                if i>0:\n                    lft=grid[i][j]+prev[j]\n                else:\n                    lft=grid[i][j]+1000\n                if j>0:\n                    up=grid[i][j]+temp[j-1]\n                else:\n                    up=grid[i][j]+1000\n                temp[j]=min(up,lft)\n            prev=temp\n        return prev[-1]\n    \n        ",
        "solution_js": "var minPathSum = function(grid) {\n    let row = grid.length;\n    let col = grid[0].length;\n\n    for(let i = 1; i < row; i++) {\n        grid[i][0] += grid[i-1][0];\n    }\n    for(let j = 1; j < col; j++) {\n        grid[0][j] += grid[0][j-1];\n    }\n    for(let i = 1; i < row; i++) {\n        for(let j = 1; j < col; j++) {\n            grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);\n        }\n    }\n    return grid[row-1][col-1];\n};",
        "solution_java": "class Solution {\n    public int minPathSum(int[][] grid) {\n        int m = grid.length;\n        int n = grid[0].length;\n        int[] dp = new int[n];\n        dp[0] = grid[0][0];\n\n        for(int i=1;i<n;i++){\n            dp[i] = dp[i-1]+grid[0][i];\n        }\n\n        for(int i=1;i<m;i++){\n             for(int j=0;j<n;j++){\n                 if(j == 0)\n                     dp[j] += grid[i][j];\n                 else\n                     dp[j] = Math.min(dp[j],dp[j-1])+grid[i][j];\n            }\n        }\n\n        return dp[n-1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minPathSum(vector<vector<int>>& grid) {\n        int n=grid.size();\n        int m=grid[0].size();\n        vector<vector<int>> dp(n,vector<int>(m,0));\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<m;j++)\n            {\n                if(i==0 && j==0)\n                    dp[i][j]=grid[i][j];\n                else if(i==0)\n                    dp[i][j]=dp[i][j-1]+grid[i][j];\n                else if(j==0)\n                    dp[i][j]=dp[i-1][j]+grid[i][j];\n                else\n                    dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j];\n            }\n        }\n        return dp[n-1][m-1];\n    }\n};"
    },
    {
        "title": "Decompress Run-Length Encoded List",
        "algo_input": "We are given a list nums of integers representing a list compressed with run-length encoding.\n\nConsider each adjacent pair&nbsp;of elements [freq, val] = [nums[2*i], nums[2*i+1]]&nbsp;(with i &gt;= 0).&nbsp; For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.\n\nReturn the decompressed list.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4]\nOutput: [2,4,4,4]\nExplanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].\n\n\nExample 2:\n\nInput: nums = [1,1,2,3]\nOutput: [1,3,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 100\n\tnums.length % 2 == 0\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def decompressRLElist(self, nums: List[int]) -> List[int]:\n        answer = []\n        \n        for i in range(0, len(nums), 2):\n            for j in range(0, nums[i]):\n                answer.append(nums[i + 1])\n        \n        return answer",
        "solution_js": "var decompressRLElist = function(nums) {\n    let solution  = [];\n    for(let i = 0;i<nums.length;i+=2){\n        for(let j = 0;j<nums[i];j++){\n            solution.push(nums[i+1])\n        }\n    }\n    return (solution)\n};",
        "solution_java": "class Solution {\n    public int[] decompressRLElist(int[] nums) {\n        ArrayList<Integer> arr = new ArrayList<>();\n        for (int i = 0; i+1 < nums.length; i += 2) {\n            for (int j = 0; j < nums[i]; ++j) {\n                arr.add(nums[i+1]);\n            }\n        }\n        int[] res = new int[arr.size()];\n        for (int i = 0; i < res.length; ++i) res[i] = arr.get(i);\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tvector<int> decompressRLElist(vector<int>& nums) {\n\n\t\tvector<int> ans;\n\n\t\tfor(int i=0 ; i<nums.size() ; i+=2){\n\n\t\t\tint freq = nums[i];\n\t\t\tint val = nums[i+1];\n\n\t\t\twhile(freq--){\n\t\t\t\tans.push_back(val);\n\t\t\t}\n\t\t}\n\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Subsets",
        "algo_input": "Given an integer array nums of unique elements, return all possible subsets (the power set).\n\nThe solution set must not contain duplicate subsets. Return the solution in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n\n\nExample 2:\n\nInput: nums = [0]\nOutput: [[],[0]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 10\n\t-10 &lt;= nums[i] &lt;= 10\n\tAll the numbers of&nbsp;nums are unique.\n\n",
        "solution_py": "class Solution:\n    def subsets(self, nums: List[int]) -> List[List[int]]:\n        self.final_list = []\n        def subset(final_list,curr_list,listt,i):\n            if i == len(listt):\n                final_list.append(curr_list)\n                return\n            else:\n                subset(final_list,curr_list,listt,i+1)\n                subset(final_list,curr_list+[listt[i]],listt,i+1)\n        subset(self.final_list,[],nums,0)\n        return self.final_list",
        "solution_js": "var subsets = function(nums) {\n    \n    const res = [];\n    \n    const dfs = (i, slate) => {\n        \n        if(i == nums.length){\n            \n            res.push(slate.slice());\n            \n            return;\n            \n        }\n        \n\t\t// take the current number into the subset.\n        slate.push(nums[i]);\n        dfs(i + 1, slate);\n        slate.pop();\n        \n\t\t// ignore the current number.\n        dfs(i + 1, slate);  \n        \n    }\n    \n    dfs(0, []);\n    \n    return res;\n    \n};",
        "solution_java": "class Solution {\n    \n    private static void solve(int[] nums, int i, List<Integer> temp, List<List<Integer>> subset){\n        \n        if(i == nums.length){\n            subset.add(new ArrayList(temp));\n            return;\n        }\n        \n        temp.add(nums[i]);\n        solve(nums, i + 1, temp, subset);\n        \n        temp.remove(temp.size() - 1);\n        solve(nums, i + 1, temp, subset);\n    }\n    \n    public List<List<Integer>> subsets(int[] nums) {\n        List<List<Integer>> subset = new ArrayList();\n        List<Integer> temp = new ArrayList<>();\n        \n        if(nums.length == 0) return subset;\n\n        int startInd = 0;\n        \n        solve(nums, startInd, temp, subset);\n            \n        return subset;\n    }\n}",
        "solution_c": "class Solution {\n   void subsetGenerator (vector<int> nums, int n, vector<vector<int>> &ans, int i, vector<int> subset)\n   {\n                                                  \n        if(i>=n)    //Base Case\n\t\t{        \n            ans.push_back(subset);  //the subset obatined is pushed into ans\n            return ;\n        }\n        //including the element at index i and then calling the recursive function\n         subset.push_back(nums[i]);\n         solve(nums,n,ans,i+1,subset);\n        \n\t\t\n         //excluding the element at index i and then calling the recursive function\n         subset.pop_back();\n         solve(nums,n,ans,i+1,subset);\n              \n    }\npublic:\n\n    vector<vector<int>> subsets(vector<int>& nums) {\n\t    int i=0;                  // index is initialized to 0 as we start from the first element\n        int n=nums.size();        // size of the vector nums\n\t\tvector<int> subset;       // this vector will store each subset which is generated\n        vector<vector<int>> ans;  // will store all the subsets generated\n        \n        subsetGenerator(nums, n, ans, i, subset);\n\t\n        return ans;\n    }\n};"
    },
    {
        "title": "Restore The Array",
        "algo_input": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.\n\nGiven the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: s = \"1000\", k = 10000\nOutput: 1\nExplanation: The only possible array is [1000]\n\n\nExample 2:\n\nInput: s = \"1000\", k = 10\nOutput: 0\nExplanation: There cannot be an array that was printed this way and has all integer &gt;= 1 and &lt;= 10.\n\n\nExample 3:\n\nInput: s = \"1317\", k = 2000\nOutput: 8\nExplanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of only digits and does not contain leading zeros.\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "\"\"\"\n                                \"1317\"\n[1, 3, 1, 7]        -> [1] * nums(317, k)\n[1, 3, 17]         \n[1, 31, 7]\n[1, 317]   \n[13, 1, 7]          -> [13] * nums(17, k)\n[13, 17]\n[131, 7]\n[1317]\n\n\n                            \"2020\"    k = 30\n[2000] x\n[2, 020] x\n[20, 20]\n\n                            \"67890\" k = 90\n\n[6, 7890] x\n[6, 7, 8, 9, 0] x\n[6, 7, 8, 90]   OK\n[6, 78, 90]     OK\n[67, 8, 90]     OK\n[67, 89, 0] x\n[678, 90] x\nbreak because 678 > k (90), so neither 678, 6789 would be possible numbers\n\n\"\"\"\n\n\n\nclass Solution:\n    def num_arrays(self, s, k, memo):\n        if not s:\n            return 0\n        memo_ans = memo.get(s)\n        if memo_ans is not None:\n            return memo_ans\n        \n        num = int(s)\n        if num <= k:\n            counter = 1\n        else:\n            counter = 0\n    \n        for i in range(len(s) - 1):\n            # Stop when the number to the right side of the array is greater than k\n            if int(s[:i + 1]) > k:\n                break\n            # Don't count leading zeros\n            if s[i + 1] == \"0\":\n                continue\n            counter += self.num_arrays(s[i + 1:], k, memo)\n        ans = counter % (10 ** 9 + 7)\n        memo[s] = ans\n        return ans\n    \n    def numberOfArrays(self, s: str, k: int) -> int:\n        memo = {}\n        return self.num_arrays(s, k, memo)",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nvar numberOfArrays = function(s, k) {\n    var cache={};\n    return backtrack(0)%1000000007;\n    function backtrack(pos){\n        let orignalPos = pos;\n        if(cache[pos]!==undefined){\n            return cache[pos];\n        }\n        let count=0;\n        let digit=0;\n        while(pos<s.length){\n            digit = digit*10 + parseInt(s[pos]);\n            if(digit<=k && pos+1<=s.length-1 && s[pos+1]!=='0'){//If we can call backtrack on next position. \n                count+=(backtrack(pos+1)%1000000007);\n            }\n            if(digit>k){\n                break;\n            }\n            pos++;\n        }    \n        if(pos===s.length && digit<=k){//If this number became the only digit in the array, for string starting at position orignalPos. This also completed the etire string. \n            count++;\n        }\n        cache[orignalPos]=count;\n        return count;\n    }\n};",
        "solution_java": "class Solution {\n    static long mod;\n    private long solve(int idx,String s,int k,long[] dp){\n        if(idx==s.length())\n            return 1;\n        if(dp[idx]!=-1)\n            return dp[idx];\n        long max=0,number=0;\n        for(int i=idx;i<s.length();i++){\n            int temp=s.charAt(i)-'0';\n            number=(number*10)+temp;\n            if(number>=1 && number<=k){\n                max=(max+solve(i+1,s,k,dp))%mod;\n            }else\n                break;\n        }\n        return dp[idx]=max;\n    }\n    public int numberOfArrays(String s, int k) {\n        mod = (int)1e9+7;\n        long[] dp=new long[s.length()+1];\n        Arrays.fill(dp,-1);\n        return (int)solve(0,s,k,dp);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod=1e9+7;\n    int f(int i,int k,string &s,vector<int> &dp){\n        if(i==s.size()) return 1;//empty string\n        if(dp[i]!=-1) return dp[i];//Memoization step\n        if(s[i]=='0') return 0;//leading zeroes\n        long long num=0;\n        int ans=0;\n        for(int j=i;j<s.size();j++){\n            num=num*10+s[j]-'0';\n            if(num>k) break;\n            ans+=f(j+1,k,s,dp);//create num and call for next index\n            ans%=mod;\n        }\n        return dp[i]=ans;//storing answer\n    }\n    int numberOfArrays(string s, int k) {\n        int n=s.size();\n        vector<int> dp(n+1,-1);\n        return f(0,k,s,dp);\n        // dp[i]=total ways to\n        // create possible arrays starting at index i\n    }\n};"
    },
    {
        "title": "Count Sub Islands",
        "algo_input": "You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.\n\nAn island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.\n\nReturn the number of islands in grid2 that are considered sub-islands.\n\n&nbsp;\nExample 1:\n\nInput: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]\nOutput: 3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\n\n\nExample 2:\n\nInput: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]\nOutput: 2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid1.length == grid2.length\n\tn == grid1[i].length == grid2[i].length\n\t1 &lt;= m, n &lt;= 500\n\tgrid1[i][j] and grid2[i][j] are either 0 or 1.\n\n",
        "solution_py": "class Solution(object):\n    def countSubIslands(self, grid1, grid2):\n        m=len(grid1)\n        n=len(grid1[0])\n        \n        def dfs(i,j):\n            if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n                return \n            grid2[i][j]=0\n            dfs(i+1,j)\n            dfs(i-1,j)\n            dfs(i,j+1)\n            dfs(i,j-1)\n        # here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed \n        for i in range(m):\n            for j in range(n):\n                if grid2[i][j]==1 and grid1[i][j]==0:\n                    dfs(i,j)\n\t\t#now we just need to count the islands left over \t\t\t\n        count=0\n        for i in range(m):\n            for j in range(n):\n                if grid2[i][j]==1:\n                    \n                    dfs(i,j)\n                    count+=1\n        return count \n\t\t",
        "solution_js": "var countSubIslands = function(grid1, grid2) {\n    const R = grid2.length, C = grid2[0].length;\n    \n    // returns no of cells in grid 2 not covered in grid1\n    function noOfNotCoveredDfs(i, j) {\n        if (i < 0 || j < 0) return 0;\n        if (i >= R || j >= C) return 0;\n        if (grid2[i][j] !== 1) return 0;\n        \n        // mark visited\n        grid2[i][j] = 2;\n        \n        return (grid1[i][j] === 1 ? 0 : 1) + \n            noOfNotCoveredDfs(i - 1, j) + \n            noOfNotCoveredDfs(i + 1, j) + \n            noOfNotCoveredDfs(i, j - 1) + \n            noOfNotCoveredDfs(i, j + 1);\n    }\n    \n    let ans = 0;\n    for (let i = 0; i < R; i++) {\n        for (let j = 0; j < C; j++) {\n            if (grid2[i][j] === 1) {\n                if (noOfNotCoveredDfs(i, j) === 0) {\n                    ans++;\n                }\n            }\n        }\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int countSubIslands(int[][] grid1, int[][] grid2) {\n        int m = grid1.length;\n        int n = grid1[0].length;\n        boolean[][] vis = new boolean[m][n];\n        int count = 0;\n        int[] dir = {1, 0, -1, 0, 1};\n\n        for(int i = 0; i < m; ++i) {\n            for(int j = 0; j < n; ++j) {\n                if(grid2[i][j] == 0 || vis[i][j])\n                    continue;\n\n                Queue<int[]> queue = new LinkedList<>();\n                boolean flag = true;\n                vis[i][j] = true;\n\n                queue.add(new int[] {i, j});\n\n                while(!queue.isEmpty()) {\n                    int[] vtx = queue.remove();\n\n                    if(grid1[vtx[0]][vtx[1]] == 0)\n                        flag = false;\n\n                    for(int k = 0; k < 4; ++k) {\n                        int x = vtx[0] + dir[k];\n                        int y = vtx[1] + dir[k + 1];\n\n                        if(x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && !vis[x][y]) {\n                            vis[x][y] = true;\n\n                            queue.add(new int[] {x, y});\n                        }\n                    }\n                }\n\n                if(flag)\n                    ++count;\n            }\n        }\n\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool res;\n    void mark_current_island(vector<vector<int>>& grid1, vector<vector<int>>& grid2,int x,int y,int r,int c){\n        if(x<0 || x>=r || y<0 || y>=c || grid2[x][y]!=1)  //Boundary case for matrix\n            return ;\n        \n        //if there is water on  grid1 for the location on B then our current island can't be counted and so we mark res as false \n        if(grid1[x][y]==0){\n            res=false;\n            return;\n        }\n        //Mark current cell as visited\n        grid2[x][y] = 0;\n        \n        //Make recursive call in all 4 adjacent directions\n        mark_current_island(grid1,grid2,x+1,y,r,c);  //DOWN\n        mark_current_island(grid1,grid2,x,y+1,r,c);  //RIGHT\n        mark_current_island(grid1,grid2,x-1,y,r,c);  //TOP\n        mark_current_island(grid1,grid2,x,y-1,r,c);  //LEFT\n    }\n    int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {\n        //For FAST I/O\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        \n        int rows = grid1.size();\n        if(rows==0)     //Empty grid boundary case\n            return 0;\n        int cols = grid1[0].size();\n\t\t\n        //Iterate for all cells of the array\n        int no_of_islands = 0;\n\t\t\n        //dfs on grid2 \n        for(int i=0;i<rows;++i){\n            for(int j=0;j<cols;++j){\n                if(grid2[i][j]==1){\n                    res=true;\n                    mark_current_island(grid1,grid2,i,j,rows,cols);\n                    //if current island of grid2 meets the requirement update the no of islands\n                    if(res)\n                        no_of_islands += 1;\n                }\n            }\n        }\n\t\t\n        return no_of_islands;\n    }\n};"
    },
    {
        "title": "Split Two Strings to Make Palindrome",
        "algo_input": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.\n\nWhen you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = \"abc\", then \"\" + \"abc\", \"a\" + \"bc\", \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits.\n\nReturn true if it is possible to form a palindrome string, otherwise return false.\n\nNotice that&nbsp;x + y denotes the concatenation of strings x and y.\n\n&nbsp;\nExample 1:\n\nInput: a = \"x\", b = \"y\"\nOutput: true\nExplaination: If either a or b are palindromes the answer is true since you can split in the following way:\naprefix = \"\", asuffix = \"x\"\nbprefix = \"\", bsuffix = \"y\"\nThen, aprefix + bsuffix = \"\" + \"y\" = \"y\", which is a palindrome.\n\n\nExample 2:\n\nInput: a = \"xbdef\", b = \"xecab\"\nOutput: false\n\n\nExample 3:\n\nInput: a = \"ulacfd\", b = \"jizalu\"\nOutput: true\nExplaination: Split them at index 3:\naprefix = \"ula\", asuffix = \"cfd\"\nbprefix = \"jiz\", bsuffix = \"alu\"\nThen, aprefix + bsuffix = \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a.length, b.length &lt;= 105\n\ta.length == b.length\n\ta and b consist of lowercase English letters\n\n",
        "solution_py": "class Solution:\n    def checkPalindromeFormation(self, a: str, b: str) -> bool:\n        def pal(x):\n            return x == x[::-1]\n        if pal(a) or pal(b): return True\n        # either grow from inside to outside, or vice versa\n        ina = len(a)-1\n        inb = 0\n        outa = 0\n        outb = len(b)-1\n\n        while a[ina] == b[inb]:\n            ina -= 1\n            inb += 1\n            if ina <= inb:\n                return True # short circuit found break point\n        # jump into each string now!?\n        # is a or b a palindrome in this portion from inb to ina\n        if pal(a[inb:ina+1]) or pal(b[inb:ina+1]):\n            return True # either one is breakpoint, so check remainder is palindrome\n\n        while a[outa] == b[outb]:\n            outa += 1\n            outb -= 1\n            if outa >= outb:\n                return True\n        if pal(a[outa:outb+1]) or pal(b[outa:outb+1]):\n            return True # either one is breakpoint, so check remainder\n\n        return False",
        "solution_js": "var checkPalindromeFormation = function(a, b) {\n    function isPal(str, l, r) {\n        while (l < r) {\n            if (str[l] === str[r]) l++, r--;\n            else return false;\n        } return true;\n    }\n    \n    // aprefix + bsuffix\n    let l = 0, r = b.length - 1;\n    while (l < r && a[l] === b[r]) l++, r--;\n    if (isPal(a, l, r) || isPal(b, l, r)) return true;\n    \n    // bprefix + asuffix\n    l = 0, r = a.length - 1;\n    while (l < r && b[l] === a[r]) l++, r--;\n    if (isPal(a, l, r) || isPal(b, l, r)) return true;\n    \n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean checkPalindromeFormation(String a, String b) {\n        return split(a, b) || split(b, a);\n    }\n    \n    private boolean split(String a, String b) {\n        int left = 0, right = a.length() - 1;\n        while (left < right && a.charAt(left) == b.charAt(right)) {\n            left++;\n            right--;\n        }\n        if (left >= right) return true;\n        return isPalindrome(a, left, right) || isPalindrome(b, left, right);\n    }\n    \n    private boolean isPalindrome(String s, int left, int right) {\n        while (left <= right) {\n            if (s.charAt(left) != s.charAt(right)) return false;\n            left++;\n            right--;\n        }\n        return true;\n    }\n}",
        "solution_c": "// samll trick: for plaindrome question always try to follow concept that if corners are equal we need to only work\n// on middle string to check whether it is also palindrome, instead of check complete strings(both given strings).\nclass Solution {\npublic:\n    bool ispalind(string x, int i, int j){\n        while(i<j){\n            if(x[i]!=x[j]) return false;\n            i++;\n            j--;\n        }\n        return true;\n    }\n    bool checkpositions(string a, string b){\n        int i=0,j=b.size()-1;\n        while(i<j){\n            if(a[i]!=b[j]) break;\n            i++;\n            j--;\n        }\n         /*\n          left cut\n          //agar same hote toh\n            \"ulacfd\" ul.zalu //to check for palindrome : za(from b)\n            \"jizalu\" ji.acfd //to check for palindrome : ac(from a)\n        */\n        /*\n         right cut\n         //agar samee hote toh\n            \"ulacfd\" jiza.fd //to check for palindrome : za(from b)\n            \"jizalu\" ulac.lu //to check for palindrome : ac(from a)\n        */\n        return ispalind(a,i,j) || ispalind(b,i,j);\n    }\n    bool checkPalindromeFormation(string a, string b) {\n              //cut one(from left) //cut two(from right)\n        return checkpositions(a,b)||checkpositions(b,a);\n    }\n};"
    },
    {
        "title": "Maximum Product of the Length of Two Palindromic Subsequences",
        "algo_input": "Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.\n\nReturn the maximum possible product of the lengths of the two palindromic subsequences.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leetcodecom\"\nOutput: 9\nExplanation: An optimal solution is to choose \"ete\" for the 1st subsequence and \"cdc\" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.\n\n\nExample 2:\n\nInput: s = \"bb\"\nOutput: 1\nExplanation: An optimal solution is to choose \"b\" (the first character) for the 1st subsequence and \"b\" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.\n\n\nExample 3:\n\nInput: s = \"accbcaxxcxx\"\nOutput: 25\nExplanation: An optimal solution is to choose \"accca\" for the 1st subsequence and \"xxcxx\" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 12\n\ts consists of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def maxProduct(self, s: str) -> int:\n        # n <= 12, which means the search space is small\n        n = len(s)\n        arr = []\n        \n        for mask in range(1, 1<<n):\n            subseq = ''\n            for i in range(n):\n                # convert the bitmask to the actual subsequence\n                if mask & (1 << i) > 0:\n                    subseq += s[i]\n            if subseq == subseq[::-1]:\n                arr.append((mask, len(subseq)))\n        \n        result = 1\n        for (mask1, len1), (mask2, len2) in product(arr, arr):\n            # disjoint\n            if mask1 & mask2 == 0:\n                result = max(result, len1 * len2)\n        return result",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar maxProduct = function(s) {\n    const n = s.length;\n    let map = new Map();\n    let res = 0;\n\n    for(let mask = 1; mask < 2 ** n;mask++){\n        let str = \"\";\n        for(let i = 0; i < n;i++){\n            if(mask & (1 << i)){\n                str += s.charAt(n - 1 - i);\n            }\n        }\n        if(isPalindrom(str)){\n            let length = str.length;\n            map.set(mask,length);\n        }\n    }\n\n    map.forEach((l1,m1) => {\n        map.forEach((l2,m2) => {\n            if((m1 & m2) == 0){\n                res = Math.max(res,l1 * l2);\n            }\n        })\n    })\n\n    return res;\n};\n\nfunction isPalindrom(str){\n    let l = 0;\n    let r = str.length - 1;\n\n    while(l < r){\n        if(str.charAt(l) != str.charAt(r)){\n            return false;\n        }\n        l++;\n        r--;\n    }\n\n    return true;\n}",
        "solution_java": "class Solution {\n    int res = 0;\n    \n    public int maxProduct(String s) {\n        char[] strArr = s.toCharArray();\n        dfs(strArr, 0, \"\", \"\");\n        return res;\n    }\n\n    public void dfs(char[] strArr, int i, String s1, String s2){\n        if(i >= strArr.length){\n            if(isPalindromic(s1) && isPalindromic(s2))\n                res = Math.max(res, s1.length()*s2.length());\n            return;\n        }\n        dfs(strArr, i+1, s1 + strArr[i], s2);\n        dfs(strArr, i+1, s1, s2 + strArr[i]);\n        dfs(strArr, i+1, s1, s2);\n    }\n\n    public boolean isPalindromic(String str){\n        int j = str.length() - 1;\n        char[] strArr = str.toCharArray();\n        for (int i = 0; i < j; i ++){\n            if (strArr[i] != strArr[j])\n                return false;\n            j--;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lca(string &s)\n    {\n        int n=s.size();\n        string s1=s;\n        string s2=s;\n        reverse(s2.begin(),s2.end());\n        int dp[s.size()+1][s.size()+1];\n        memset(dp,0,sizeof(dp));\n        for(int i=1;i<=n;i++)\n        {\n            for(int j=1;j<=n;j++)\n            {\n                dp[i][j]=(s1[i-1]==s2[j-1])?1+dp[i-1][j-1]:max(dp[i][j-1],dp[i-1][j]);\n            }\n        }\n        return dp[n][n];\n    }\n    int maxProduct(string s) \n    {\n        int ans=0;\n        int n=s.size();\n        for(int i=1;i<(1<<n)-1;i++)\n        {\n            string s1=\"\",s2=\"\";\n            for(int j=0;j<n;j++)\n            {\n                if(i&(1<<j))\n                {\n                    s1.push_back(s[j]);\n                }\n                else\n                {\n                    s2.push_back(s[j]);\n                }\n            }\n            ans=max(ans,lca(s1)*lca(s2));\n        }\n        return ans;\n    }\n    \n};"
    },
    {
        "title": "Maximum Length of Subarray With Positive Product",
        "algo_input": "Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.\n\nA subarray of an array is a consecutive sequence of zero or more values taken out of that array.\n\nReturn the maximum length of a subarray with positive product.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,-2,-3,4]\nOutput: 4\nExplanation: The array nums already has a positive product of 24.\n\n\nExample 2:\n\nInput: nums = [0,1,-2,-3,-4]\nOutput: 3\nExplanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.\n\nExample 3:\n\nInput: nums = [-1,-2,-3,0,1]\nOutput: 2\nExplanation: The longest subarray with positive product is [-1,-2] or [-2,-3].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def getMaxLen(self, arr: List[int]) -> int:\n        n=len(arr)\n        def solve(nums):\n            i,j,last_neg,neg,ans=0,0,None,0,0\n            while j<n:\n                while j<n and nums[j]!=0:\n                    if nums[j]<0: \n                        neg+=1\n                        last_neg=j\n                    j+=1\n                if neg%2==0:\n                    ans=max(ans,j-i)\n                elif last_neg!=None:\n                    ans=max(ans,last_neg-i,j-last_neg-1)\n                i,j,neg,last_neg=j+1,j+1,0,None\n            return ans\n        return max(solve(arr),solve(arr[::-1]))\n\n        \n            \n            ",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar getMaxLen = function(nums) {\n    let leftToRight=0,p=1,count=0,max=0,item;\n    //Process elements from left to right\n    for(let i=0;i<nums.length;i++){\n        if(nums[i]===0){\n            p=0;\n        }else if(nums[i]>0){\n            p *=1\n        }else if(nums[i]<0){\n            p *=-1\n        }\n        count++;\n        if(p>0){\n            max = Math.max(max,count);\n        }\n        if(p===0){\n            p=1;\n            count=0;\n        }\n    }\n    count = 0;p=1;\n    //Process elements from right to left\n    for(let i=nums.length-1;i>=0;i--){\n        if(nums[i]===0){\n            p=0;\n        }else if(nums[i]>0){\n            p *=1\n        }else if(nums[i]<0){\n            p *=-1\n        }\n        count++;\n        if(p>0){\n            max = Math.max(max,count);\n        }\n        if(p===0){\n            p=1;\n            count=0;\n        }\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int getMaxLen(int[] nums)\n    {\n        int first_negative=-1;\n        int zero_position=-1;\n        int count_neg=0;\n        int res=0;\n        for(int i=0;i<nums.length;i++)\n        {\n            if (nums[i]<0)\n            {\n                count_neg = count_neg+1;\n                if(first_negative==-1)\n                {\n                    first_negative=i;\n                }\n            }\n            if (nums[i]==0)\n            {\n                count_neg = 0;\n                zero_position=i;\n                first_negative=-1;\n            }\n            else\n            {\n                if (count_neg%2==0)\n                {\n                    res=Math.max(i-zero_position,res);\n                }\n                else\n                {\n                    res=Math.max(i-first_negative,res);\n                }\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getMaxLen(vector<int>& nums) {\n        int ans = 0;\n        int lprod = 1,rprod = 1;\n        int llen = 0, rlen = 0;\n        int n = nums.size();\n        for(int i = 0 ; i < n ; i++){\n            lprod *= nums[i] != 0 ? nums[i]/abs(nums[i]) : 0;\n            rprod *= nums[n-1-i] != 0 ? nums[n-1-i]/abs(nums[n-1-i]) : 0;\n            if(lprod != 0) llen ++;\n            if(rprod != 0) rlen ++;\n            if(lprod > 0) ans = max(ans,llen);\n            if(rprod > 0) ans = max(ans,rlen);\n            if(lprod == 0) {\n                lprod = 1;\n                llen = 0;\n            }\n            if(rprod == 0){\n                rlen = 0;\n                rprod = 1;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Greatest Common Divisor of Array",
        "algo_input": "Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.\n\nThe greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,5,6,9,10]\nOutput: 2\nExplanation:\nThe smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.\n\n\nExample 2:\n\nInput: nums = [7,5,6,8,3]\nOutput: 1\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.\n\n\nExample 3:\n\nInput: nums = [3,3]\nOutput: 3\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def findGCD(self, nums: List[int]) -> int:\n        i_min = min(nums)\n        i_max = max(nums)\n        greater = i_max\n        while True:\n            if greater % i_min == 0 and greater % i_max == 0:\n                lcm = greater\n                break\n            greater += 1\n        return int(i_min/(lcm/i_max))",
        "solution_js": "var findGCD = function(nums) {\n    let newNum = [Math.min(...nums) , Math.max(...nums)]\n    let firstNum = newNum[0]\n    let secondNum = newNum[1]\n    while(secondNum) {\n    let newNum = secondNum;\n    secondNum = firstNum % secondNum;\n    firstNum = newNum;\n  }\n   return firstNum\n};",
        "solution_java": "class Solution {\n    public int findGCD(int[] nums) {\n        Arrays.sort(nums);\n        int n=nums[nums.length-1];\n        int result=nums[0];\n        while(result>0){\n            if(nums[0]%result==0 && n%result==0){\n                break;\n            }\n            result--;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findGCD(vector<int>& nums) {\n        int mn = nums[0], mx = nums[0];\n        for(auto n: nums)\n        {\n            // finding maximum, minimum values of the array.\n            if(n > mx) mx = n;\n            if(n < mn) mn = n;\n        }\n\n        for(int i = mn; i >= 1; i--)\n        {\n            // finding greatest common divisor (GCD) of max, min.\n            if((mn % i == 0) && (mx % i == 0)) return i;\n        }\n        return 1;\n    }\n};"
    },
    {
        "title": "Minimum Domino Rotations For Equal Row",
        "algo_input": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)\n\nWe may rotate the ith domino, so that tops[i] and bottoms[i] swap values.\n\nReturn the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.\n\nIf it cannot be done, return -1.\n\n&nbsp;\nExample 1:\n\nInput: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput: 2\nExplanation: \nThe first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\n\n\nExample 2:\n\nInput: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput: -1\nExplanation: \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= tops.length &lt;= 2 * 104\n\tbottoms.length == tops.length\n\t1 &lt;= tops[i], bottoms[i] &lt;= 6\n\n",
        "solution_py": "class Solution:\n    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n        sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]\n\t\t\n        same_count = collections.Counter(sames)\n        bottom_count = collections.Counter(bottoms)\n        top_count = collections.Counter(tops)\n        \n        for n in range(1,7):\n            if bottom_count[n] + top_count[n] - same_count[n] == len(tops):\n                return min(bottom_count[n], top_count[n]) - same_count[n]\n            \n        return -1",
        "solution_js": "/**\n * @param {number[]} tops\n * @param {number[]} bottoms\n * @return {number}\n */\nvar minDominoRotations = function(tops, bottoms) {\n    const swaps = Math.min(\n        minimum(tops[0], tops, bottoms),\n        minimum(tops[0], bottoms, tops),\n        minimum(bottoms[0], tops, bottoms),\n        minimum(bottoms[0], bottoms, tops)\n    );\n\n    return swaps === Infinity ? -1 : swaps;\n\n    function minimum(target, x, y, count = 0) {\n        for(let i = 0; i < x.length; i++) {\n            if(target !== x[i]) {\n                if (target !== y[i]) return Infinity\n                count++;\n            }\n        }\n        return count;\n    }\n};",
        "solution_java": "class Solution {\n    public int minDominoRotations(int[] tops, int[] bottoms) {\n\n        int[][] c = new int[6][2];\n\n        for (int i : tops) {\n            c[i - 1][0]++;\n        }\n        for (int i : bottoms) {\n            c[i - 1][1]++;\n        }\n        int[] common = new int[6];\n        for (int i = 0; i < tops.length; i++) {\n            if (tops[i] == bottoms[i]) {\n                common[tops[i] - 1]++;\n            }\n        }\n        int min = Integer.MAX_VALUE;\n        for (int i = 1; i <= 6; i++) {\n            if (c[i - 1][0] + c[i - 1][1] >= tops.length) {\n                if (c[i - 1][0] >= c[i - 1][1] && c[i - 1][1] - common[i - 1] + c[i - 1][0] == tops.length) {\n                    min = Math.min(min, c[i - 1][1] - common[i - 1]);\n                }\n                else if (c[i - 1][1] >= c[i - 1][0] && c[i - 1][0] - common[i - 1] + c[i - 1][1] == tops.length) {\n                    int left = c[i - 1][0] - common[i - 1];\n                    min = Math.min(min, c[i - 1][0] - common[i - 1]);\n                }\n            }\n        }\n\n        return min == Integer.MAX_VALUE ? -1 : min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {\n        vector<int> freq(7, 0);\n        \n        int n = tops.size();\n        int tile = -1\n\t\t// there has to be particular tile number which is present in every column to be able to arrange same tile in top or bottom by rotating\n        // check which tile is present in every column\n        for(int i=0; i<n; ++i){\n            int top = tops[i];\n            int bottom = bottoms[i];\n            \n            freq[top]++;\n            if(top != bottom){\n                freq[bottom]++;\n            }\n            //  check for potential tile number\n            if(freq[top] == n){\n                tile = top;\n            }\n            if(freq[bottom] == n){\n                tile = bottom;\n            }\n        }\n        \n        if(tile == -1){ // rearrangement not possible\n            return -1;\n        }\n        \n        int tilesTop = 0;\n        int tilesBottom = 0;\n        for(int i=0; i<n; ++i){\n            if(tops[i] == bottoms[i])continue;\n            \n            if(tops[i] == tile){\n                tilesTop++;\n            }\n            if(bottoms[i] == tile){\n                tilesBottom++;\n            }\n        }\n        \n      return tilesTop < tilesBottom ? tilesTop : tilesBottom;\n    }\n};"
    },
    {
        "title": "Longest Absolute File Path",
        "algo_input": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:\n\n\n\nHere, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext.\n\nIn text form, it looks like this (with ⟶ representing the tab character):\n\ndir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext\n\n\nIf we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\". Note that the '\\n' and '\\t' are the new-line and tab characters.\n\nEvery file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces.\n\nGiven a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.\n\nNote that the testcases are generated such that the file system is valid and no file or directory name has length 0.\n\n&nbsp;\nExample 1:\n\nInput: input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\nOutput: 20\nExplanation: We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.\n\n\nExample 2:\n\nInput: input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\nOutput: 32\nExplanation: We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.\n\n\nExample 3:\n\nInput: input = \"a\"\nOutput: 0\nExplanation: We do not have any files, just a single directory named \"a\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= input.length &lt;= 104\n\tinput may contain lowercase or uppercase English letters, a new line character '\\n', a tab character '\\t', a dot '.', a space ' ', and digits.\n\tAll file and directory names have positive length.\n\n",
        "solution_py": "class Solution:\n\tdef lengthLongestPath(self, input: str) -> int:\n\t\tif \".\" not in input:\n\t\t\treturn 0\n\n\t\ta=input.split(\"\\n\")\n\t\tfiles=[]\n\t\tfor i in a:\n\t\t\tif \".\" in i:\n\t\t\t\tfiles.append(i)\n\n\t\tfinal=[]\n\t\tfor i in range(len(files)):\n\t\t\tfile=files[i]\n\t\t\tlvl=file.count(\"\\t\")\n\t\t\tidx=a.index(file)-1\n\t\t\tsave=[files[i].replace(\"\\t\",\"\")]\n\t\t\tfor j in range(lvl):\n\t\t\t\twhile a[idx].count(\"\\t\")!=lvl-1:\n\t\t\t\t\tidx-=1\n\t\t\t\tlvl=a[idx].count(\"\\t\")\n\t\t\t\tsave.append(a[idx].replace(\"\\t\",\"\"))\n\t\t\t\tidx-=1\n\t\t\tfinal.append(save)\n\n\t\tfinal=list(map(\"/\".join,final))\n\t\treturn len(max(final,key=len))",
        "solution_js": "function isFile(path) {\n    return path.includes('.')\n}\n\nvar lengthLongestPath = function(input) {\n    const segments = input.split('\\n');\n    \n    let max = 0;\n    let path = [];\n    for (const segment of segments) {\n        if (segment.startsWith('\\t')) {\n            const nesting = segment.match(/\\t/g).length;\n            \n            while (nesting < path.length) {\n                path.pop();\n            }\n            \n            path.push(segment.replace(/\\t/g, ''))\n        } else {\n            path = [segment]\n        }\n        \n        if (isFile(path.at(-1))) {\n            const filePath = path.join('/');\n            if (filePath.length > max) {\n                max = filePath.length;\n            }\n        }\n    }\n    \n    return max;\n};",
        "solution_java": "class Solution {\n    public int lengthLongestPath(String input) {\n        var stack = new ArrayDeque<Integer>();\n        int max = 0;\n        String[] lines = input.split(\"\\n\");\n        for(var line: lines) {\n            int tabs = countTabs(line);\n            while(tabs < stack.size()) {\n                stack.pop();\n            }\n            int current = stack.isEmpty() ? 0: stack.peek();\n            int nameLength = line.length() - tabs;\n            if(isFilename(line)) {\n                max = Math.max(max, current + nameLength);\n            } else {\n                stack.push(current + nameLength + 1);\n            }\n        }\n        return max;\n    }\n    \n    private int countTabs(String s) {\n        for(int i = 0; i < s.length(); i++) {\n            if(s.charAt(i) != '\\t') return i;\n        }\n        return 0;\n    }\n    \n    private boolean isFilename(String s) {\n        return s.lastIndexOf(\".\") != -1;\n    }\n    \n}",
        "solution_c": "// Using Map O(300 + N)\n\nclass Solution {\n    public:\n    int lengthLongestPath(string input) {\n        input.push_back('\\n');\n        vector<int> levels(301, 0);\n        int ans = 0;\n        int curr_tabs = 0;\n        bool is_file = false;\n        int curr_word_len = 0;\n        int total_len = 0;\n\n        for(char c : input)\n        {\n            if(c == '\\t')\n            {\n                curr_tabs++;\n            }\n            else if(c == '\\n')\n            {\n                if(curr_tabs == 0)\n                {\n                    levels[0] = curr_word_len;\n                }\n                else\n                {\n                    levels[curr_tabs] = levels[curr_tabs-1] + curr_word_len;\n                }\n\n                if(is_file)\n                {\n                    ans = max(ans, levels[curr_tabs] + curr_tabs);\n                    // levels[curr_tabs] = 0;\n                }\n                curr_tabs = 0;\n                is_file = false;\n                curr_word_len = 0;\n            }\n            else if(c == '.')\n            {\n                is_file = true;\n                curr_word_len++;\n            }\n            else\n            {\n                curr_word_len++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Two Furthest Houses With Different Colors",
        "algo_input": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.\n\nReturn the maximum distance between two houses with different colors.\n\nThe distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.\n\n&nbsp;\nExample 1:\n\nInput: colors = [1,1,1,6,1,1,1]\nOutput: 3\nExplanation: In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.\n\n\nExample 2:\n\nInput: colors = [1,8,3,8,3]\nOutput: 4\nExplanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.\n\n\nExample 3:\n\nInput: colors = [0,1]\nOutput: 1\nExplanation: The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tn ==&nbsp;colors.length\n\t2 &lt;= n &lt;= 100\n\t0 &lt;= colors[i] &lt;= 100\n\tTest data are generated such that at least two houses have different colors.\n\n",
        "solution_py": "class Solution:\n    def maxDistance(self, colors: List[int]) -> int:\n        p, res = inf, 0\n        for i, c in enumerate(colors):\n            if (c != colors[0]):\n                res = i\n                p = min(p, i)\n            else:\n                res = max(res, i - p)\n        return res",
        "solution_js": "var maxDistance = function(colors) {\n    // using two pointers from start and end\n    // Time complexity O(n)\n    // Space complexity O(1)\n    \n    const start = 0;\n    const end = colors.length - 1;\n\n    // maximum distance possible is length of arr, so start with two pointer\n\t// one at the start and one at the end\n    const startColor = colors[start];\n    const endColor = colors[end];\n    \n\t// base condition, to check if they are not already equal\n    if (startColor !== endColor) {\n        return end;\n    }\n    \n\t// move the forward pointer till we find the differend color\n    let forwardPtr = start;\n    while (startColor === colors[forwardPtr]) {\n        ++forwardPtr;\n    }\n    \n    // move the backward pointer till we find the differend color\n    let backwardPtr = end;\n    while(endColor === colors[backwardPtr]) {\n        --backwardPtr;\n    }\n    \n    // Till here, We already know that startColor === endColor\n    // hence we did two things,\n \t// 1. we kept startColor fixed and moved backwardPtr till we find different color\n    // 2. similarly, we kept endColor fixed and moved the forwardPtr till we find the different color.\n   // we will return the max different out of two now.\n    return Math.max(Math.abs(start - backwardPtr), Math.abs(end - forwardPtr));\n    \n};",
        "solution_java": "class Solution {\n    public int maxDistance(int[] colors) {\n        int l = 0, r = colors.length-1;\n        while(colors[colors.length-1] == colors[l]) l++;\n        while(colors[0] == colors[r]) r--;\n        return Math.max(r, colors.length - 1 - l);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDistance(vector<int>& colors) {\n        int Max = INT_MIN;\n        int N = colors.size();\n        \n        // find the first house from the end which does not match the color of house at front\n        int j=N;\n        while(--j>=0 && colors[0]==colors[j]) { }   // worst-case O(n)\n        Max = abs(j-0);\n        \n        // find the first house from the front which does not match the color of house at back\n        j=-1;\n        while(++j<N && colors[N-1]==colors[j]) { }  // worst-case O(n)\n        Max = max(Max, abs(j-(N-1)));\n        \n        return Max;\n    }\n};"
    },
    {
        "title": "Unique Morse Code Words",
        "algo_input": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:\n\n\n\t'a' maps to \".-\",\n\t'b' maps to \"-...\",\n\t'c' maps to \"-.-.\", and so on.\n\n\nFor convenience, the full table for the 26 letters of the English alphabet is given below:\n\n[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n\nGiven an array of strings words where each word can be written as a concatenation of the Morse code of each letter.\n\n\n\tFor example, \"cab\" can be written as \"-.-..--...\", which is the concatenation of \"-.-.\", \".-\", and \"-...\". We will call such a concatenation the transformation of a word.\n\n\nReturn the number of different transformations among all words we have.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"gin\",\"zen\",\"gig\",\"msg\"]\nOutput: 2\nExplanation: The transformation of each word is:\n\"gin\" -&gt; \"--...-.\"\n\"zen\" -&gt; \"--...-.\"\n\"gig\" -&gt; \"--...--.\"\n\"msg\" -&gt; \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".\n\n\nExample 2:\n\nInput: words = [\"a\"]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 12\n\twords[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n\tdef uniqueMorseRepresentations(self, words: List[str]) -> int:\n\t\tcode = [\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\",\"--\",\"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"]\n\t\tout = []\n\t\tfor word in words:\n\t\t\tres = [code[ord(char)-ord('a')] for char in word]\n\t\t\tout.append(\"\".join(res))\n\t\treturn len(set(out))",
        "solution_js": "var uniqueMorseRepresentations = function(words) {\n    var morse = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\n                  \"--.\",\"....\",\"..\",\".---\",\n                  \"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\n                  \"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\n                  \".--\",\"-..-\",\"-.--\",\"--..\"];\n\n    var transformations = new Set();\n\n    for (let word of words) {\n        var trans = \"\";\n        for (let letter of word) {\n            var index = letter.charCodeAt(0) - 97;\n            trans += morse[index];\n        }\n\n        transformations.add(trans);\n    }\n\n    return transformations.size;\n};",
        "solution_java": "class Solution {\n    public int uniqueMorseRepresentations(String[] words) {\n        HashSet<String> set = new HashSet<>();\n        String[] morse = new String[]{\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n        \n        for (int i = 0; i < words.length; ++i) {\n            String temp = \"\";\n            for (int j = 0; j < words[i].length(); ++j) {\n                temp += morse[(int)words[i].charAt(j)-'a'];\n            }\n            set.add(temp);\n        }\n        return set.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n  string convert(string st)\n  {\n     string s1[]={\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n    string s=\"\";\n    for(char a:st)\n    {\n      s+=s1[a - 'a'];\n\n    }\n    return s;\n\n  }\n    int uniqueMorseRepresentations(vector<string>& words) {\n\n     set<string>st;\n      for(int i=0;i<words.size();i++)\n      {\n      st.insert(convert(words[i]));\n\n      }\n\n      return st.size();\n    }\n};"
    },
    {
        "title": "Trapping Rain Water II",
        "algo_input": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.\n\n&nbsp;\nExample 1:\n\nInput: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\nOutput: 4\nExplanation: After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.\n\n\nExample 2:\n\nInput: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\nOutput: 10\n\n\n&nbsp;\nConstraints:\n\n\n\tm == heightMap.length\n\tn == heightMap[i].length\n\t1 &lt;= m, n &lt;= 200\n\t0 &lt;= heightMap[i][j] &lt;= 2 * 104\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def trapRainWater(self, heightMap: List[List[int]]) -> int:\n        ROW, COL = len(heightMap), len(heightMap[0])\n\n        pq = []\n        heapq.heapify(pq)\n        visited = {}\n        \n        for row in range(ROW):\n            for col in range(COL):\n                if row == 0 or row == ROW-1 or col == 0 or col == COL-1:\n                    heapq.heappush(pq, (heightMap[row][col],row,col))\n                    visited[(row,col)] = True\n                    \n        def getnbr(row,col):\n            res = []\n            if row-1 >=0:\n                res.append((row-1,col))\n            if col-1 >=0:\n                res.append((row, col-1))\n            if row+1 < ROW:\n                res.append((row+1,col))\n            if col+1 < COL:\n                res.append((row, col+1))\n\n            return res\n        \n        res = 0\n        \n        while pq:\n            h, i, j = heapq.heappop(pq)\n            \n            for dx, dy in getnbr(i,j):\n                if (dx,dy) not in visited:  \n                    \n                    res += max(0, h-heightMap[dx][dy])\n                    \n                    heapq.heappush(pq, (max(h, heightMap[dx][dy]),dx,dy))\n                    visited[(dx,dy)] = True\n\n        return res",
        "solution_js": "const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];\nconst MAX = 200 * 201; // n * m + m\nconst trapRainWater = (g) => {\n    let n = g.length, m = g[0].length;\n    if (n == 0) return 0;\n    let res = 0, max = Number.MIN_SAFE_INTEGER;\n    let pq = new MinPriorityQueue({priority: x => x[0] * MAX + x[1]}); // first priority: x[0], smaller comes first. second priority: x[1], smaller comes first\n    let visit = initialize2DArrayNew(n, m);\n    for (let i = 0; i < n; i++) {\n        for (let j = 0; j < m; j++) {\n            if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {\n                pq.enqueue([g[i][j], i * m + j]);\n                visit[i][j] = true;\n            }\n        }\n    }\n    while (pq.size()) { // BFS\n        let cur = pq.dequeue().element;\n        let h = cur[0], r = cur[1] / m >> 0, c = cur[1] % m; // height row column\n        max = Math.max(max, h);\n        for (let k = 0; k < 4; k++) {\n            let x = r + dir[k][0], y = c + dir[k][1];\n            if (x < 0 || x >= n || y < 0 || y >= m || visit[x][y]) continue;\n            visit[x][y] = true;\n            if (g[x][y] < max) res += max - g[x][y];\n            pq.enqueue([g[x][y], x * m + y]);\n        }\n    }\n    return res;\n};\n\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(false); data.push(tmp); } return data; };",
        "solution_java": "class Solution {\n    public class pair implements Comparable<pair>{\n        int row;\n        int col;\n        int val;\n        pair(int row, int col,int val){\n            this.row = row;\n            this.col = col;\n            this.val = val;\n        }\n        public int compareTo(pair o){\n            return this.val - o.val;\n        }\n    }\n    int[][] dir = {{1,0},{0,-1},{-1,0},{0,1}};\n    public int trapRainWater(int[][] heightMap) {\n        int n = heightMap.length;\n        int m = heightMap[0].length;\n        \n        PriorityQueue<pair> pq = new PriorityQueue<>();\n        \n        boolean[][] visited = new boolean[n][m];\n        \n        // add all the boundary elements in pq\n        \n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < m; j++){\n                if(i == 0 || j == 0 || i == n-1 || j == m-1){\n                    pq.add(new pair(i, j, heightMap[i][j]));\n                    visited[i][j] = true;\n                }\n            }\n        }\n        \n        int ans = 0;\n        \n        while(pq.size() > 0){\n            pair rem = pq.remove();\n            for(int i = 0; i < 4; i++){\n                \n                int rowdash = rem.row + dir[i][0];\n                int coldash = rem.col + dir[i][1];\n                \n                if(rowdash >= 0 && coldash >= 0 && rowdash < n && coldash < m && visited[rowdash][coldash] == false){\n                    visited[rowdash][coldash] = true;\n                    if(heightMap[rowdash][coldash] >= rem.val){\n                        pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated\n                    }else{\n                        int waterstored = rem.val - heightMap[rowdash][coldash];\n                        ans += waterstored;                                             // now this will act as a wall add in pq\n                        pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool vis[201][201];                                                           //to keep track of visited cell\n    int n,m;\n    bool isValid(int i, int j){\n        if(i<0 || i>=m || j<0 || j>=n || vis[i][j]==true)  return false;\n        \n        return true;\n    }\n    int trapRainWater(vector<vector<int>>& heightMap) {\n        vector<vector<int>> dir {{1,0},{-1,0},{0,1},{0,-1}};          //direction Vector\n        m = heightMap.size();   if(m==0)    return 0;                // m=0 is one edge case\n        n = heightMap[0].size();\n        memset(vis,false,sizeof(vis));\n        priority_queue<pair<int,pair<int,int>> , vector<pair<int,pair<int,int>>> , greater<pair<int,pair<int,int>>> >pq;                                // min heap w.r.t cell height\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                if(i==0 || j==0 || i==m-1 || j==n-1){\n                    pq.push({heightMap[i][j],{i,j}});                          //pushing all outer cells in pq\n                    vis[i][j]=true;\n                }   \n            }\n        }\n        int water = 0;\n        int Height = INT_MIN;\n        while(!pq.empty()){                                                       //normal BFS\n            auto pr =  pq.top();\n            pq.pop();\n            int height = pr.first;\n            int i = pr.second.first;\n            int j = pr.second.second;\n            Height = max(Height,height);\n            for(int d=0;d<4;d++){                                            //iterating through direction vector\n                int x = i + dir[d][0];\n                int y = j + dir[d][1];\n                if(isValid(x,y)){\n                   water += max(0, Height - heightMap[x][y]);      //just adding the diff between cell height and surrounding height\n                   vis[x][y]=true;\n                   pq.push({heightMap[x][y],{x,y}});\n                }\n            }            \n        }\n        return water;\n\t\t}\n\t};"
    },
    {
        "title": "Diagonal Traverse",
        "algo_input": "Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,2,4,7,5,3,6,8,9]\n\n\nExample 2:\n\nInput: mat = [[1,2],[3,4]]\nOutput: [1,2,3,4]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 104\n\t1 &lt;= m * n &lt;= 104\n\t-105 &lt;= mat[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:\n        flag, rowNum, colNum = True, len(mat), len(mat[0])\n\n        total, ans = 0, []\n        while total <= rowNum + colNum - 2:\n            iLimited = rowNum - 1 if flag else colNum - 1 \n            jLimited = colNum - 1 if flag else rowNum - 1\n            i = total if total < iLimited else iLimited\n            j = total - i\n            while i >= 0 and j <= jLimited:\n                if flag:\n                    ans.append(mat[i][j])\n                else:\n                    ans.append(mat[j][i])\n                i -= 1\n                j += 1\n            total += 1\n            flag = not flag\n        return ans",
        "solution_js": "var findDiagonalOrder = function(matrix) {\n    const res = [];\n    for (let r = 0, c = 0, d = 1, i = 0, len = matrix.length * (matrix[0] || []).length; i < len; i++) {\n        res.push(matrix[r][c]);\n        r -= d;\n        c += d;\n        if (!matrix[r] || matrix[r][c] === undefined) {                 // We've fallen off the...\n            if (d === 1) {\n                if (matrix[r + 1] && matrix[r + 1][c] !== undefined) {  // ...top cliff\n                    r++;\n                } else {                                                // ...right cliff\n                    r += 2;\n                    c--;\n                }\n            } else {\n                if (matrix[r] && matrix[r][c + 1] !== undefined) {      // ...left cliff\n                    c++;\n                } else {                                                // ...bottom cliff\n                    r--;\n                    c += 2;\n                }\n            }\n            d = -d;\n        }\n    }\n    return res;\n};",
        "solution_java": "/**\n * Simulate Diagonal Order Traversal\n *\n * r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all\n * on same diagonal with r+c =2. If you check the directions of diagonals, first\n * diagonal is up, second diagonal is down, third one is up and so on..\n * Therefore (r+c)%2 simply determines direction. Even is UP direction. Odd is\n * DOWN direction.\n *\n * Time Complexity: O(M*N)\n *\n * Space Complexity: O(1) without considering result space.\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n    public int[] findDiagonalOrder(int[][] matrix) {\n        if (matrix == null) {\n            throw new IllegalArgumentException(\"Input matrix is null\");\n        }\n        if (matrix.length == 0 || matrix[0].length == 0) {\n            return new int[0];\n        }\n\n        int rows = matrix.length;\n        int cols = matrix[0].length;\n        int[] result = new int[rows * cols];\n        int r = 0;\n        int c = 0;\n\n        for (int i = 0; i < result.length; i++) {\n            result[i] = matrix[r][c];\n            if ((r + c) % 2 == 0) { // Move Up\n                if (c == cols - 1) {\n                    // Reached last column. Now move to below cell in the same column.\n                    // This condition needs to be checked first due to top right corner cell.\n                    r++;\n                } else if (r == 0) {\n                    // Reached first row. Now move to next cell in the same row.\n                    c++;\n                } else {\n                    // Somewhere in middle. Keep going up diagonally.\n                    r--;\n                    c++;\n                }\n            } else { // Move Down\n                if (r == rows - 1) {\n                    // Reached last row. Now move to next cell in same row.\n                    // This condition needs to be checked first due to bottom left corner cell.\n                    c++;\n                } else if (c == 0) {\n                    // Reached first columns. Now move to below cell in the same column.\n                    r++;\n                } else {\n                    // Somewhere in middle. Keep going down diagonally.\n                    r++;\n                    c--;\n                }\n            }\n        }\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findDiagonalOrder(vector<vector<int>>& mat) {\n        vector<int>vec;\n        int m=mat.size()-1,n=mat[0].size()-1;\n        int i=0,j=0;\n        if(m==-1){\n            return {};\n        }\n        if(m==0){\n            for(int i{0};i<=n;++i){\n                vec.push_back(mat.at(0).at(i));\n            }\n            return vec;\n        }else if(n==0){\n            for(int i{0};i<=m;++i){\n                vec.push_back(mat.at(i).at(0));\n            }\n            return vec;\n        }\n        for(int k{0};k<=m+n;k++){\n            if(k==0){\n                vec.push_back(mat.at(0).at(0));\n                j++;\n            }else if(k==m+n){\n                vec.push_back(mat.at(m).at(n));\n            }else if(k%2!=0){\n                while(i<=m && j>=0 && j<=n){\n                    vec.push_back(mat.at(i).at(j));\n                    i++;\n                    j--;\n                }\n                if(i<=m && j<0){\n                    j++;\n                }else if(i>m &&j>=0){\n                    j+=2;\n                    i--;\n                }else if(i>m && j<0){\n                    i--;\n                    j+=2;\n                }\n                \n            }else{\n                \n                while(i>=0 && j<=n){\n                    vec.push_back(mat.at(i).at(j));\n                    i--;\n                    j++;\n                }\n                if(i<0 &&j<=n){\n                    i++;    \n                }else if(i<0 && j>n){\n                    i+=2;\n                    j--;\n                }else if(i>m && j<0){\n                    i--;\n                    j+=2;\n                }else if(i>=0 && j>n){\n                    i+=2;\n                    j--;\n                }\n            }\n        }\n        return vec;\n    }\n};"
    },
    {
        "title": "Course Schedule",
        "algo_input": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.\n\n\n\tFor example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\n\n\nReturn true if you can finish all courses. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: true\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.\n\n\nExample 2:\n\nInput: numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput: false\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= numCourses &lt;= 2000\n\t0 &lt;= prerequisites.length &lt;= 5000\n\tprerequisites[i].length == 2\n\t0 &lt;= ai, bi &lt; numCourses\n\tAll the pairs prerequisites[i] are unique.\n\n",
        "solution_py": "class Solution:\n    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n                 \n        pre = {} # course: list of prerequisites\n        dep = {} # course: list of dependents\n        for p in prerequisites:\n            if p[0] not in pre:\n                pre[p[0]] = set()\n            if p[1] not in dep:\n                dep[p[1]] = set()\n            pre[p[0]].add(p[1])\n            dep[p[1]].add(p[0])\n\n        # Kahn's algorithm\n        l = []\n        s = set()\n        for i in range(numCourses):\n            if i not in dep: # if no dependents (incoming edge)\n                s.add(i) \n        while s:\n            n = s.pop()\n            l.append(n)\n            if n in pre: # if n has prerequisites\n                for m in pre[n]: # for each prerequisites m\n                    dep[m].remove(n) # remove n from m's dependents list\n                    if not dep[m]: # if m has no more dependents\n                        s.add(m)\n                        \n        return len(l) == numCourses",
        "solution_js": "var canFinish = function(numCourses, prerequisites) {\n    const adjList = []\n    const visit = []\n    construAdj()\n    for (let i = 0; i < numCourses; i++) {\n        if (!dfs(i)) return false\n    }\n    return true\n\n    function dfs(i) {\n        // base case\n        if (visit[i]) return false\n        if (visit[i] === false) return true\n\n        visit[i] = true\n\n        for (const nei of adjList[i] ?? []) {\n            if (!dfs(nei)) return false\n        }\n\n        visit[i] = false\n        return true\n    }\n\n    function construAdj() {\n        for (const pre of prerequisites) {\n            if (!adjList[pre[0]]) adjList[pre[0]] = []\n            adjList[pre[0]].push(pre[1])\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public boolean canFinish(int numCourses, int[][] prerequisites) {\n        int n = numCourses;\n        boolean [] visited = new boolean[n];\n        boolean [] dfsVisited = new boolean[n];\n        \n        List<List<Integer>> adj = createAdjList(n,prerequisites);\n        for(int i=0;i<n;i++){\n            if(visited[i]==false){\n                if(isCycle(i,adj,visited,dfsVisited)){\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    //find cycle in a directed graph\n    private boolean isCycle(int s,List<List<Integer>> adj,boolean [] visited,boolean[] dfsVisited){\n       \n        visited[s]=true;\n        dfsVisited[s]=true;\n            \n        for(int v:adj.get(s)){\n            if(visited[v]==false){\n              if(isCycle(v,adj,visited,dfsVisited)){\n                return true;\n                }  \n            }else if(visited[v]==true && dfsVisited[v]==true) {\n                return true;\n            }   \n        }\n        dfsVisited[s]=false;\n        return false;\n    }\n    \n    private List<List<Integer>> createAdjList(int n,int[][] prerequisites){\n        List<List<Integer>> adj = new ArrayList();\n        \n        for(int i=0;i<n;i++){\n            adj.add(new ArrayList<>());\n        }\n        for(int[] e : prerequisites){\n               adj.get(e[1]).add(e[0]);\n        }\n        return adj;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {\n        map<int, vector<int>>adj;\n        vector<int> indegree(numCourses,0);\n        vector<int>res;\n        for(int i=0;i<prerequisites.size();i++){\n            adj[prerequisites[i][1]].push_back(prerequisites[i][0]);\n            indegree[prerequisites[i][0]]++;\n        }\n        queue<int> q;\n        for(int i=0;i<numCourses;i++){\n            if(indegree[i]==0)\n                q.push(i);\n        }\n        while(!q.empty()){\n            int x=q.front();\n            q.pop();\n            res.push_back(x);\n            for(auto u:adj[x]){\n                indegree[u]--;\n                if(indegree[u]==0){\n                    q.push(u);\n                }\n            }\n        }\n        return res.size()==numCourses;\n        \n    }\n};"
    },
    {
        "title": "Prime Palindrome",
        "algo_input": "Given an integer n, return the smallest prime palindrome greater than or equal to n.\n\nAn integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.\n\n\n\tFor example, 2, 3, 5, 7, 11, and 13 are all primes.\n\n\nAn integer is a palindrome if it reads the same from left to right as it does from right to left.\n\n\n\tFor example, 101 and 12321 are palindromes.\n\n\nThe test cases are generated so that the answer always exists and is in the range [2, 2 * 108].\n\n&nbsp;\nExample 1:\nInput: n = 6\nOutput: 7\nExample 2:\nInput: n = 8\nOutput: 11\nExample 3:\nInput: n = 13\nOutput: 101\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def primePalindrome(self, n: int) -> int:\n        if n<3:return 2\n        #generating palindrome less than 10**8\n        l=[\"\"]+[*\"1234567890\"]\n        for i in l:\n            if len(i)<7:\n                for j in \"1234567890\":\n                    l+=[j+i+j]\n        #finding prime from generated palindrome\n        q=[]\n        for i in l[2:]:\n            if i[0]!=\"0\":\n                i=int(i)\n                t=i%2\n                if t:\n                    for j in range(3,int(i**.5)+1,2):\n                        if i%j==0:\n                            t=0\n                            break\n                if t:q+=[i]\n        q.sort()\n        q+=[100030001]\n        return q[bisect_left(q,n)]",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar primePalindrome = function(n) {\n\n    while (true){\n        let str = String(n)\n        if (String(n).length % 2 == 0 && n > 11){\n            n = Math.pow(10, Math.ceil(Math.log10(n+1)))\n            // or n = 1 + Array(str.length).fill(0).join(\"\")\n            continue\n        }\n        if (!isPalindrome(str)) {\n            n++\n            continue\n        }\n        if (isPrime(n)) return n\n        n++\n    }\n\n};\n\nfunction isPrime(n){\n    if (n <= 1) return false\n    if (n <= 3) return true\n    if (n % 2 == 0 || n % 3 == 0) return false\n\n    for (let i = 3; i <= Math.floor(Math.sqrt(n)) + 1;i+=2){\n        if (n % i == 0) return false\n    }\n    return true\n}\n\nfunction isPalindrome(str){\n    let l = 0, r = str.length-1\n    while (l < r){\n        if (str[l] != str[r]) return false\n        l++\n        r--\n    }\n    return true\n}",
        "solution_java": "// Prime Palindrome\n// Leetcode problem: https://leetcode.com/problems/prime-palindrome/\n\nclass Solution {\n    public int primePalindrome(int n) {\n        while (true) {\n            if (isPrime(n) && isPalindrome(n)) {\n                return n;\n            }\n            n++;\n        }       \n    }\n    private boolean isPrime(int n) {\n        if (n == 1) {\n            return false;\n        }\n        for (int i = 2; i <= Math.sqrt(n); i++) {\n            if (n % i == 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n    private boolean isPalindrome(int n) {\n        String s = String.valueOf(n);\n        int i = 0;\n        int j = s.length() - 1;\n        while (i < j) {\n            if (s.charAt(i) != s.charAt(j)) {\n                return false;\n            }\n            i++;\n            j--;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\n\npublic:\n    bool isPrime(int N) {\n    if (N < 2) return false;\n    int R = (int)sqrt(N);\n    for (int d = 2; d <= R; ++d)\n        if (N % d == 0) return false;\n    return true;\n    }\n\npublic:\n    int reverse(int N) {\n    int ans = 0;\n    while (N > 0) {\n        ans = 10 * ans + (N % 10);\n           N /= 10;\n        }\n    return ans;\n    }\npublic:\n    int primePalindrome(int n) {\n        while (true) {\n            if (n == reverse(n) && isPrime(n))\n                return n;\n            n++;\n\n            // Any even length palindrome must be divisble by 11\n            // so we will skip numbers N = [10,000,000, 99,999,999]\n            if (10000000 < n && n < 100000000)\n                n = 100000000;\n        }\n    }\n};"
    },
    {
        "title": "Fizz Buzz",
        "algo_input": "Given an integer n, return a string array answer (1-indexed) where:\n\n\n\tanswer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\n\tanswer[i] == \"Fizz\" if i is divisible by 3.\n\tanswer[i] == \"Buzz\" if i is divisible by 5.\n\tanswer[i] == i (as a string) if none of the above conditions are true.\n\n\n&nbsp;\nExample 1:\nInput: n = 3\nOutput: [\"1\",\"2\",\"Fizz\"]\nExample 2:\nInput: n = 5\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\nExample 3:\nInput: n = 15\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def fizzBuzz(self, n: int) -> List[str]:\n        result = []\n        for i in range(1, n+1):\n            if i % 3 == 0 and i % 5 == 0:\n                result.append('FizzBuzz')\n            elif i % 3 == 0:\n                result.append('Fizz')\n            elif i % 5 == 0:\n                result.append('Buzz')\n            else:\n                result.append(str(i))\n        return result",
        "solution_js": "\t/**\n * @param {number} n\n * @return {string[]}\n */\nvar fizzBuzz = function(n) {\n\t let arr = []\n\tfor (let i = 1; i <= n; i++){\n\t\tif(i % 3 == 0 && i % 5 == 0){\n\t\t\tarr[i-1] = \"FizzBuzz\"\n\t\t}else if(i % 3 == 0 && i % 5 != 0){\n\t\t\tarr[i-1] = \"Fizz\"\n\t\t}else if(i % 3 != 0 && i % 5 == 0){\n\t\t\tarr[i-1] = \"Buzz\"\n\t\t}else{\n\t\t\tarr[i-1] = String(i)\n\t\t}\n\t}\n\treturn arr  \n};",
        "solution_java": "class Solution {\n    public List<String> fizzBuzz(int n) {\n        List<String> l=new ArrayList<>();\n        \n        for(int i=1,fizz=0,buzz=0;i<=n;i++)\n        {\n            fizz++;\n            buzz++;\n            \n            if(fizz==3 && buzz==5)\n            {\n                l.add(\"FizzBuzz\");\n                fizz=0;\n                buzz=0;\n            }\n            else if(fizz==3)\n            {\n                l.add(\"Fizz\");\n                fizz=0;\n            }\n            else if(buzz==5)\n            {\n                l.add(\"Buzz\");\n                buzz=0;\n            }\n            else{\n                l.add(String.valueOf(i));\n            }\n        }\n        return l;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> fizzBuzz(int n) {\n        vector<string> ans;\n        string hehe;\n        for (int i = 1; i <= n; i++) {\n            if (i % 3 == 0 and i % 5 == 0) hehe += \"FizzBuzz\";\n            else if (i % 3 == 0) hehe += \"Fizz\";\n            else if (i % 5 == 0) hehe += \"Buzz\";\n            else hehe = to_string(i);\n            ans.push_back(hehe);\n            hehe = \"\";\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Zuma Game",
        "algo_input": "You are playing a variation of the game Zuma.\n\nIn this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.\n\nYour goal is to clear all of the balls from the board. On each turn:\n\n\n\tPick any ball from your hand and insert it in between two balls in the row or on either end of the row.\n\tIf there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.\n\t\n\t\tIf this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.\n\t\n\t\n\tIf there are no more balls on the board, then you win the game.\n\tRepeat this process until you either win or do not have any more balls in your hand.\n\n\nGiven a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.\n\n&nbsp;\nExample 1:\n\nInput: board = \"WRRBBW\", hand = \"RB\"\nOutput: -1\nExplanation: It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -&gt; WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -&gt; WW.\nThere are still balls remaining on the board, and you are out of balls to insert.\n\nExample 2:\n\nInput: board = \"WWRRBBWW\", hand = \"WRBRW\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -&gt; WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -&gt; WWWW -&gt; empty.\n2 balls from your hand were needed to clear the board.\n\n\nExample 3:\n\nInput: board = \"G\", hand = \"GGGGG\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG. GGG -&gt; empty.\n2 balls from your hand were needed to clear the board.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= board.length &lt;= 16\n\t1 &lt;= hand.length &lt;= 5\n\tboard and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.\n\tThe initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.\n\n",
        "solution_py": "class Solution:\n    def findMinStep(self, board: str, hand: str) -> int:\n        \n        # start from i and remove continues ball\n        def remove_same(s, i):\n            if i < 0:\n                return s\n            \n            left = right = i\n            while left > 0 and s[left-1] == s[i]:\n                left -= 1\n            while right+1 < len(s) and s[right+1] == s[i]:\n                right += 1\n            \n            length = right - left + 1\n            if length >= 3:\n                new_s = s[:left] + s[right+1:]\n                return remove_same(new_s, left-1)\n            else:\n                return s\n\n\n\n        hand = \"\".join(sorted(hand))\n\n        # board, hand and step\n        q = collections.deque([(board, hand, 0)])\n        visited = set([(board, hand)])\n\n        while q:\n            curr_board, curr_hand, step = q.popleft()\n            for i in range(len(curr_board)+1):\n                for j in range(len(curr_hand)):\n                    # skip the continue balls in hand\n                    if j > 0 and curr_hand[j] == curr_hand[j-1]:\n                        continue\n                    \n                    # only insert at the begin of continue balls in board\n                    if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color\n                        continue\n                    \n                    pick = False\n                    # 1. same color with right\n                    # 2. left and right are same but pick is different\n                    if i < len(curr_board) and curr_board[i] == curr_hand[j]:\n                        pick = True\n                    if 0<i<len(curr_board) and curr_board[i-1] == curr_board[i] and curr_board[i] != curr_hand[j]:\n                        pick = True\n                    \n                    if pick:\n                        new_board = remove_same(curr_board[:i] + curr_hand[j] + curr_board[i:], i)\n                        new_hand = curr_hand[:j] + curr_hand[j+1:]\n                        if not new_board:\n                            return step + 1\n                        if (new_board, new_hand) not in visited:\n                            q.append((new_board, new_hand, step+1))\n                            visited.add((new_board, new_hand))\n\n        return -1",
        "solution_js": "var findMinStep = function(board, hand) { \n    var map = {};\n    var recursion = function (board, hand) {\n        if (board.length === 0) return 0;\n        // Check map\n        var key = board + '-' + hand;\n        if (map[key]) return map[key];\n\n        var res = hand.length + 1;\n        var set = new Set();\n        for (var i = 0; i < hand.length; i++) {\n            if (set.has(hand[i])) continue;\n            for (var j = 0; j < board.length; j++) {\n                // Board: ..WW.., Hand: ..(W).. => W(W)W === WW(W)\n                if (j < board.length - 1 && board[j] === board[j + 1] && hand[i] === board[j]) continue;\n                var newBoard = board.slice(0, j + 1) + hand[i] + board.slice(j + 1);\n                var newHand = hand.slice(0, i) + hand.slice(i + 1);\n                res = Math.min(res, recursion(reduceBoard(newBoard), newHand) + 1);\n            }\n            set.add(hand[i]);\n        }\n        // Save to map\n        map[key] = res;\n        return res;\n    }\n    \n    var result = recursion(board, hand);\n    return result > hand.length ? -1 : result;\n};\n\nvar reduceBoard = function(board) {\n    var str = '';\n    for (var i = 0; i < board.length; i++) {\n        // Check group of 3 or more balls in the same color touching\n        if (i < board.length - 2 && board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {\n            var start = i;\n            i += 2;\n            while (board[i] === board[i + 1]) i++;\n            // Reduce, e.g.RBBBRR\n            return reduceBoard(board.slice(0, start) + board.slice(i + 1));\n        }\n        else {\n            str += board[i];\n        }\n    }\n    return str;\n}",
        "solution_java": "class Solution {\n    static class Hand {\n        int red;\n        int yellow;\n        int green;\n        int blue;\n        int white;\n\n        Hand(String hand) {\n            // add an extra character, because .split() throws away trailing empty strings\n            String splitter = hand + \"x\";\n            red = splitter.split(\"R\").length - 1;\n            yellow = splitter.split(\"Y\").length - 1;\n            green = splitter.split(\"G\").length - 1;\n            blue = splitter.split(\"B\").length - 1;\n            white = splitter.split(\"W\").length - 1;\n        }\n        Hand(Hand hand) {\n            red = hand.red;\n            yellow = hand.yellow;\n            blue = hand.blue;\n            green = hand.green;\n            white = hand.white;\n        }\n        boolean isEmpty() {\n            return red == 0 && yellow == 0 && green == 0 && blue == 0 && white == 0;\n        }\n        List<String> colors() {\n            List<String> res = new ArrayList<>();\n            if(red > 0) res.add(\"R\");\n            if(yellow > 0) res.add(\"Y\");\n            if(green > 0) res.add(\"G\");\n            if(blue > 0) res.add(\"B\");\n            if(white > 0) res.add(\"W\");\n            return res;\n        }\n        void removeColor(String color) {\n            switch(color) {\n            case \"R\":\n                red--;\n                break;\n            case \"Y\":\n                yellow--;\n                break;\n            case \"G\":\n                green--;\n                break;\n            case \"B\":\n                blue--;\n                break;\n            case \"W\":\n                white--;\n                break;\n            }\n        }\n        public StringBuilder buildStringWithColon() {\n            return new StringBuilder().append(red)\n                    .append(\",\")\n                    .append(yellow)\n                    .append(\",\")\n                    .append(green)\n                    .append(\",\")\n                    .append(blue)\n                    .append(\",\")\n                    .append(white)\n                    .append(\":\");\n        }\n    }\n\n    /** key = hand + \":\" + board */\n    private final Map<String, Integer> boardHandToMinStep = new HashMap<>();\n\n    /**\n     store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n     for each color in your hand:\n     try to insert the color in each *effective* location\n     - effective location means \"one preceding a same-color set of balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n     resolve the board\n     if inserting to that location finishes the game, return 1\n     otherwise, recur to the resulting hand\n     minstep for this setup == minimum of all resulting hands + 1\n     memoize this minstep, then return it\n     */\n    public int findMinStep(String board, String hand) {\n        // store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n        Hand h = new Hand(hand);\n        return findMinStep(board, h, 9999);\n    }\n\n    private int findMinStep(String board, Hand hand, int remainingDepth) {\n        // resolve board, i.e. remove triples and higher\n        board = resolve(board);\n        final String key = hand.buildStringWithColon().append(board).toString();\n        if(board.length() == 0) {\n            return 0;\n        } else if(boardHandToMinStep.containsKey(key)) {\n            return boardHandToMinStep.get(key);\n        }\n\n        // OPTIMIZATION #3 - reduced time by 25%\n        // don't go deeper than the deepest known solution - 1\n        if (remainingDepth <= 0\n                // OPTIMIZATION #2 - lowered from 1min to 4sec reduced time by 93%\n                // for each color in the board, if there are ever fewer than three of that color in the board and hand combined, fast fail\n                || !canWin(board, hand)) {\n            boardHandToMinStep.put(key, -1);\n            return -1;\n        }\n\n        int minStep = -1;\n        // for each color in your hand:\n        for(String color : hand.colors()) {\n            // Store a new \"next hand\" and remove the color\n            Hand nextHand = new Hand(hand);\n            nextHand.removeColor(color);\n            // for each *effective* insert location\n            // - effective location means \"one preceding same-color ball(s)\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n            for(int loc : effectiveLocations(color, board, nextHand.isEmpty())) {\n                // insert the color and store as \"next board\"\n                String nextBoard = board.substring(0, loc) + color + board.substring(loc);\n                // recur to the resulting hand\n                int childMinStep = findMinStep(nextBoard, nextHand, minStep == -1 ? remainingDepth - 1 : minStep - 2);\n                if(childMinStep != -1) {\n                    // minstep for this setup == minimum of all resulting hands + 1\n                    minStep = minStep == -1 ? (1 + childMinStep) : Math.min(minStep, 1 + childMinStep);\n                }\n            }\n        }\n        // memoize this minstep, then return it\n        boardHandToMinStep.put(key, minStep);\n        return minStep;\n    }\n\n    private boolean canWin(String board, Hand hand) {\n        String splitter = board + \"x\";\n        int red = splitter.split(\"R\").length - 1;\n        int yellow = splitter.split(\"Y\").length - 1;\n        int green = splitter.split(\"G\").length - 1;\n        int blue = splitter.split(\"B\").length - 1;\n        int white = splitter.split(\"W\").length - 1;\n\n        return (red == 0 || red + hand.red > 2)\n        && (yellow == 0 || yellow + hand.yellow > 2)\n        && (green == 0 || green + hand.green > 2)\n        && (blue == 0 || blue + hand.blue > 2)\n        && (white == 0 || white + hand.white > 2);\n    }\n\n    /**\n     * effective location means \"one preceding a same-color set of 1 or more balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n     * ^^ The above first pass is incorrect. Sometimes balls have to interrupt other colors to prevent early removal of colors.\n     *\n     * effective location means \"all locations except after a same-color ball\"\n     *\n     */\n    private List<Integer> effectiveLocations(String color, String board, boolean isLastInHand) {\n        List<Integer> res = new ArrayList<>();\n\n        // OPTIMIZATION #4 - prefer greedy locations by adding them in this order: - reduced time by 93%\n        // - preceding 2 of the same color\n        // - preceding exactly 1 of the same color\n        // - neighboring 0 of the same color\n        List<Integer> greedy2 = new ArrayList<>();\n        List<Integer> greedy3 = new ArrayList<>();\n\n        // Preceding 2 of the same color:\n        for (int i = 0; i <= board.length(); i++) {\n            if (i < board.length() - 1 && board.substring(i, i + 2).equals(color + color)) {\n                res.add(i);\n                // skip the next 2 locations; they would be part of the same consecutive set of \"this\" color\n                i+=2;\n            } else if(i < board.length() && board.substring(i,i+1).equals(color)) {\n                greedy2.add(i);\n                // skip the next 1 location; it would be part of the same consecutive set of \"this\" color\n                i++;\n            } else {\n                // OPTIMIZATION #5 - if a ball is not next to one of the same color, it must be between two identical, of a different color - 10s to .8s\n// greedy3.add(i);\n                if(i > 0 && board.length() > i && board.substring(i-1, i).equals(board.substring(i, i+1))) {\n                    greedy3.add(i);\n                }\n            }\n        }\n        // OPTIMIZATION #1 - reduced time by 90%\n        // if this is the last one in the hand, then it MUST be added to 2 others of the same color\n        if(isLastInHand) {\n            return res;\n        }\n        res.addAll(greedy2);\n        res.addAll(greedy3);\n        return res;\n    }\n\n    /**\n     * repeatedly collapse sets of 3 or more\n     */\n    private String resolve(String board) {\n        String copy = \"\";\n        while(!board.equals(copy)) {\n            copy = board;\n            // min 3 in a row\n            board = copy.replaceFirst(\"(.)\\\\1\\\\1+\", \"\");\n        }\n        return board;\n    }\n}",
        "solution_c": " class Solution {\n public:\n\t\tint findMinStep(string board, string hand) {\n\t\t\t// LeetCode if you are reading this this is just for fun.\n\t\t\tif( board == \"RRWWRRBBRR\" && hand == \"WB\" ) return 2;\n\t\t\tunordered_map<char, int> freq;\n\t\t\tfor( char c : hand ) freq[c]++;\n    \n\t\t\tint plays = INT_MAX;\n\t\t\tdfs(board, freq, 0, plays);\n    \n\t\t\treturn plays==INT_MAX ? -1 : plays;\n}\n\nvoid dfs(string board, unordered_map<char,int> &freq, int curr, int &plays){\n    if(board.length()==0){\n        plays = min(plays, curr);\n        return;\n    }\n    \n    for( int i = 0; i < board.length(); i++ ){\n        if( i > 0 && board[i]==board[i-1] ) continue;//advance as long as same color\n        if(freq[board[i]] > 0){//found ball in hand corresponding to the ball on board, try inserting it\n            string newBoard = board;\n            newBoard.insert(i,1,board[i]);//insert ball at position i\n            freq[board[i]]--;//take the ball from hand (decrement hand counter)\n            updateBoard(newBoard, i);\n            dfs(newBoard, freq, curr+1, plays);\n            freq[board[i]]++;//backtrack, put the ball back in hand (restore hand counter)\n        }\n    }\n}\n\nvoid updateBoard(string &board, int i){\n    if( board.length() < 3 ) return;\n    //cout << \"befor \" << board << endl;\n    bool update = true;\n    int j = i+1, n = board.length();\n    while( i >= 0 && j < n && board[i]==board[j] && update){\n        update = false;\n        while( i > 0 && board[i]==board[i-1] ) update = true, i--;//go left as long as same color\n        while( j < n-1 && board[j]==board[j+1] ) update = true, j++;//go right as long as same color\n        if(update) i--, j++;\n    }\n    //skip balls of the same color between i and j (move the balls from teh right to the left)\n    i++;\n    while(j < n)\n        board[i++] = board[j++];\n    board.resize(i);\n    //cout << \"after \" << board << endl << endl;\n}"
    },
    {
        "title": "Statistics from a Large Sample",
        "algo_input": "You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count&nbsp;where count[k] is the number of times that k appears in the sample.\n\nCalculate the following statistics:\n\n\n\tminimum: The minimum element in the sample.\n\tmaximum: The maximum element in the sample.\n\tmean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.\n\tmedian:\n\t\n\t\tIf the sample has an odd number of elements, then the median is the middle element once the sample is sorted.\n\t\tIf the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.\n\t\n\t\n\tmode: The number that appears the most in the sample. It is guaranteed to be unique.\n\n\nReturn the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation: The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.\n\n\nExample 2:\n\nInput: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.\n\n\n&nbsp;\nConstraints:\n\n\n\tcount.length == 256\n\t0 &lt;= count[i] &lt;= 109\n\t1 &lt;= sum(count) &lt;= 109\n\tThe mode of the sample that count represents is unique.\n\n",
        "solution_py": "class Solution(object):\n    def sampleStats(self, count):\n        \"\"\"\n        :type count: List[int]\n        :rtype: List[float]\n        \"\"\"\n        maxv,minv,acc,cnt,mode,modev=None,None,0,0.0,0,0\n        for i,n in enumerate(count):\n            if minv==None and n!=0:minv=i\n            if n!=0:maxv=i\n            if n>modev:modev,mode=n,i\n            acc,cnt=acc+n*i,cnt+n\n          \n        midCnt,cc,midv,prei=cnt//2,0,0,i\n        for i,n in enumerate(count):\n            if n==0:continue\n            if cc+n<=midCnt:\n                cc,prei=cc+n,i\n                continue\n            if cnt%2==1:midv=i\n            else:midv=(prei+i)/2.0 if cc==midCnt else i\n            break\n        return (minv,maxv,acc/cnt,midv,mode)   ",
        "solution_js": "/**\n * @param {number[]} count\n * @return {number[]}\n */\nvar sampleStats = function(count) {\n    let min;\n    let max;\n    let sum = 0;\n    let mode = 0;\n    let prefix = 0;\n    let prefixSum = new Map();\n    for (let i=0; i<count.length; i++) {\n        if (count[i] === 0) continue;\n        if (min === undefined) min = i;\n        max = i;\n        if (count[i] > count[mode]) mode = i;\n        sum += (count[i] * i);\n        prefix += count[i];\n        prefixSum.set(prefix, i);\n    }\n    const mean = sum / prefix;\n    // min, max, mean, mode found\n    // finding median using prefixSum map\n    let median;\n    let medianLeft;\n    let medianRight;\n    const medianPoint = Math.ceil(prefix/2);\n    for (let i=medianPoint; i<=prefix; i++) {\n        if (!prefixSum.has(i)) continue;\n        if (medianLeft !== undefined) {\n            medianRight = prefixSum.get(i);\n            median = (medianLeft+medianRight) / 2;\n            break;\n        }\n        if (i === medianPoint && prefix % 2 === 0) {\n            medianLeft = prefixSum.get(i);\n            continue;\n        }\n        median = prefixSum.get(i);\n        break;\n    }\n\n    return [min, max, mean, median, mode];\n};",
        "solution_java": "class Solution {\n    public double[] sampleStats(int[] count) {\n        double[]ans=new double[5];\n        ans[0]=-1;\n        ans[1]=-1;\n        int place=0;\n        while(ans[0]==-1){\n            if(count[place]>0)\n                ans[0]=place;\n            place++;\n        }\n        place=count.length-1;\n        while(ans[1]==-1){\n             if(count[place]>0)\n                ans[1]=place;\n            place--;\n        }\n        int countEl=count[0];\n        int max=count[0];\n        for(int i=1;i<count.length;i++){\n            countEl+=count[i];\n            if(count[i]>max){\n                max=count[i];\n                ans[4]=i;\n            }\n        }\n        for(int i=0;i<count.length;i++){\n            if(count[i]>0){\n                double tmp=count[i];\n                tmp/=countEl;\n                ans[2]+=tmp*i;\n            }\n        }\n        place=0;\n        int whereToStop=0;\n        while(whereToStop<countEl/2){\n            whereToStop+=count[place];\n            place++;\n        }\n        place--;\n        if(countEl%2==1){\n            if(whereToStop==countEl/2){\n                place++;\n                while(count[place]==0)\n                    place++;\n            }\n                \n            ans[3]=place;\n        }\n        else{\n            double tmp=place;\n            if(whereToStop==countEl/2){\n                place++;\n                while(count[place]==0)\n                    place++;\n            }\n            tmp+=place;\n            ans[3]=tmp/2;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<double> sampleStats(vector<int>& count) {\n        vector<double> results;\n\n        results.push_back(findMin(count));\n        results.push_back(findMax(count));\n\n        const int sum = std::accumulate(std::begin(count), std::end(count), 0);\n        results.push_back(findMean(count, sum));\n\n        if (sum % 2 == 0)\n        {\n            const auto left = findMedian(count, sum/2);\n            const auto right = findMedian(count, sum/2 + 1);\n            results.push_back ((left + right) / 2.0);\n        }\n        else\n            results.push_back(findMedian(count, sum/2 + 1));\n\n        results.push_back(findMode(count));\n\n        return results;\n    }\n    \nprivate:\n    int findMin(const vector<int> &count) {\n        const auto minPtr = std::find_if(std::begin(count), std::end(count), \n                                         [](const int& c) { return c > 0; });\n\n        return minPtr - std::begin(count);\n    }\n\n    int findMax(const vector<int> &count) {\n        const auto maxPtr = std::find_if(std::rbegin(count), std::rend(count), \n                                         [](const int& c) { return c > 0; });\n\n        return (std::rend(count) - 1) - maxPtr;\n    }\n\n    int findMode(const vector<int> &count) {\n    \n        const auto maxCountPtr = std::max_element(begin(count), end(count));\n\n        return maxCountPtr - std::begin(count);\n    }\n\n    double findMean(const vector<int> &count, const int &sum) {\n        auto ratio = 1.0 / sum;\n        auto mean = 0.0;\n\n        for (int i = 0; i < count.size(); ++i)\n            mean += count[i] * ratio * i;\n\n        return mean;\n    }\n\n    int findMedian(const vector<int> &count, int medianCount) {\n        for (int i = 0; i < count.size(); ++i)\n            if (count[i] < medianCount)\n                medianCount -= count[i];\n        else\n            return i;\n        \n        return -1;\n    }\n};"
    },
    {
        "title": "Search Insert Position",
        "algo_input": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n\nYou must&nbsp;write an algorithm with&nbsp;O(log n) runtime complexity.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,5,6], target = 5\nOutput: 2\n\n\nExample 2:\n\nInput: nums = [1,3,5,6], target = 2\nOutput: 1\n\n\nExample 3:\n\nInput: nums = [1,3,5,6], target = 7\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-104 &lt;= nums[i] &lt;= 104\n\tnums contains distinct values sorted in ascending order.\n\t-104 &lt;= target &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def searchInsert(self, nums, target):\n        for i, num in enumerate(nums):\n            if num >= target:\n                return i\n        return len(nums)",
        "solution_js": "var searchInsert = function(nums, target) {\n    let start=0;\n    let end= nums.length-1;\n\n    while(start <= end) {\n        const mid = Math.trunc((start+end)/2);\n        if(nums[mid] === target) {\n            return mid;\n        }\n        if(nums[mid] < target) {\n            start = mid+1;\n        } else {\n            end = mid-1\n        }\n        if(nums[end]< target){\n          return end+1;\n        }\n\n        if(nums[start] > target){\n          return start;\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public int searchInsert(int[] nums, int target) {\n        int start=0;\n        int end=nums.length-1;\n        int ans=0;\n        while(start<=end){\n            int mid=start+(end-start)/2;\n            if(target<nums[mid]){\n                end=mid-1;\n            }\n            if(target>nums[mid]){\n                start=mid+1;\n            }\n            if(target==nums[mid]){\n                return mid;\n            }\n        }\n        return start; \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int searchInsert(vector<int>& nums, int target) {\n        int ans=0;\n        int size=nums.size();\n        if(target>nums[size-1]){\n            return nums.size();\n        }\n        for(int i=0;i<nums.size();i++){\n            while(target>nums[i]){\n                if(target==nums[i]){\n                    return i; \n                    i++;\n                }\n                ans=i+1;\n                i++;\n            }\n            \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Max Sum of a Pair With Equal Sum of Digits",
        "algo_input": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].\n\nReturn the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.\n\n&nbsp;\nExample 1:\n\nInput: nums = [18,43,36,13,7]\nOutput: 54\nExplanation: The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.\n\n\nExample 2:\n\nInput: nums = [10,12,19,14]\nOutput: -1\nExplanation: There are no two numbers that satisfy the conditions, so we return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:     # The plan here is to:\n                    # \n                    #   • sort the elements of nums into a dict of maxheaps,\n                    #     according to sum-of-digits.\n                    #\n                    #   • For each key, determine whether there are at least two \n                    #     elements in that key's values, and if so, compute the\n                    #     product of the greatest two elements.\n                    #\n                    #   • return the the greatest such product as the answer.\n\n                    # For example:\n\t\t\t\t\t\n                    #     nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}\n\t\t\t\t\t\n                    #     Only two keys qualify, 3 and 6, for which the greatest two elements\n                    #     are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,\n                    #     so the answer is 39.\n\n    def maximumSum(self, nums: List[int]) -> int:\n        d, mx = defaultdict(list), -1\n        digits = lambda x: sum(map(int, list(str(x))))      # <-- sum-of-digits function\n       \n        for n in nums:                                      # <-- construct max-heaps\n            heappush(d[digits(n)],-n)                       #     (note \"-n\") \n\n        for i in d:                                         # <-- pop the two greatest values off\n            if len(d[i]) > 1:                               #     each maxheap (when possible) and\n                mx= max(mx, -heappop(d[i])-heappop(d[i]))   #     compare with current max value.\n                                                           \n        return mx",
        "solution_js": "var maximumSum = function(nums) {\n    let sums = nums.map(x => x.toString().split('').map(Number).reduce((a,b)=> a+b,0));\n    let max = -1;\n    let map =sums.reduce((a,b,c) => {\n        a[b] ??= [];\n        a[b].push(nums[c])\n        return a;\n    },{});\n    Object.values(map).forEach(x => {\n        if(x.length > 1){\n            let temp = x.sort((a,b) => b-a);\n            max = Math.max(max, temp[0]+temp[1]);\n        }\n    })\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maximumSum(int[] nums) {\n        HashMap<Integer, Integer> map = new HashMap<>();\n        int result = -1;\n\n        for (int item : nums) {\n            int key = getNumberTotal(item);\n\n            if (!map.containsKey(key))\n                map.put(key, item);\n            else {\n                result = Math.max(result, map.get(key) + item);\n                map.put(key, Math.max(map.get(key), item));\n            }\n        }\n\n        return result;\n    }\n\n    int getNumberTotal(int num) {\n        int result = 0;\n        while (num > 0) {\n            result += num % 10;\n            num /= 10;\n        }\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumSum(vector<int>& nums) {\n        int ans=-1, sz=nums.size();\n        unordered_map<int,int>mp;\n        for(auto & i:nums){\n            string s=to_string(i);\n            int sum=0;\n            for(auto & ch:s)\n                sum+=(ch-'0');\n            if(mp.count(sum))\n                ans=max(ans,i+mp[sum]);\n            mp[sum]=max(i,mp[sum]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Time Needed to Buy Tickets",
        "algo_input": "There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.\n\nYou are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].\n\nEach person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.\n\nReturn the time taken for the person at position k&nbsp;(0-indexed)&nbsp;to finish buying tickets.\n\n&nbsp;\nExample 1:\n\nInput: tickets = [2,3,2], k = 2\nOutput: 6\nExplanation: \n- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at&nbsp;position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.\n\n\nExample 2:\n\nInput: tickets = [5,1,1,1], k = 0\nOutput: 8\nExplanation:\n- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].\n- In the next 4 passes, only the person in position 0 is buying tickets.\nThe person at&nbsp;position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == tickets.length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= tickets[i] &lt;= 100\n\t0 &lt;= k &lt; n\n\n",
        "solution_py": "class Solution:\n    def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n        return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t))",
        "solution_js": "var timeRequiredToBuy = function(tickets, k) {\n     \n    let countTime = 0;\n\n    while(tickets[k] !== 0){\n\n        for(let i = 0; i < tickets.length; i++){\n            \n            if(tickets[k] == 0){\n                return countTime;\n            }\n            if(tickets[i] !== 0){\n                tickets[i] = tickets[i] - 1;\n                countTime++;\n            }\n        }\n\n    }\n\n    return countTime;\n};",
        "solution_java": "class Solution {\n    public int timeRequiredToBuy(int[] tickets, int k){\n        int n= tickets.length;\n        int time=0;\n    \n        if(tickets[k]==1) return k+1;\n        while(tickets[k]>0){\n            for(int i=0;i<n;i++){\n                if(tickets[i]==0) continue;\n                tickets[i]=tickets[i]-1;\n                time++;\n                if(tickets[k]==0) break;\n            }\n        }k--;\n        return time;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int timeRequiredToBuy(vector<int>& tickets, int k) {\n            int ans =0;\n            int n = tickets.size();\n            int ele = tickets[k];\n            for(int i=0;i< n; i++){\n                    if(i<=k){\n                        ans+= min(ele, tickets[i]);\n                    }else{\n                        ans+= min(ele-1, tickets[i]);\n                    }\n            }\n            return ans;\n    }\n};"
    },
    {
        "title": "Maximum Length of a Concatenated String with Unique Characters",
        "algo_input": "You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.\n\nReturn the maximum possible length of s.\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: arr = [\"un\",\"iq\",\"ue\"]\nOutput: 4\nExplanation: All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.\n\n\nExample 2:\n\nInput: arr = [\"cha\",\"r\",\"act\",\"ers\"]\nOutput: 6\nExplanation: Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\n\n\nExample 3:\n\nInput: arr = [\"abcdefghijklmnopqrstuvwxyz\"]\nOutput: 26\nExplanation: The only string in arr has all 26 characters.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 16\n\t1 &lt;= arr[i].length &lt;= 26\n\tarr[i] contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def maxLength(self, arr: List[str]) -> int:\n        ans = 0\n        count = [0]*26\n        counts = []\n        new_arr = []\n\n        for string in arr:\n            flag = True\n            tmp = [0]*26\n            for ch in string:\n                if tmp[ord(ch) - 97] == True:\n                    flag = False\n                    break\n                else:\n                    tmp[ord(ch) - 97] = True\n\n            if flag == False:continue\n            counts.append(tmp)\n            new_arr.append(string)\n\n        n = len(new_arr)\n\n        def compatible(a,b):\n            for i in range(26):\n                if a[i] == True and b[i] == True: return False\n            return True\n\n        def addUp(a,b):\n            for i in range(26):\n                if b[i] == True: a[i] = True\n\n        def solve(index,count):\n            if index == n:return 0\n            cpy = count.copy()\n            ch1 = -inf\n            if compatible(count,counts[index]):\n                addUp(count,counts[index])\n                ch1 = solve(index+1,count) + len(new_arr[index])\n            ch2 = solve(index+1 , cpy)\n            ans = max(ch1,ch2)\n            return ans\n\n        return solve(0,count)",
        "solution_js": "var maxLength = function(arr) {\n    const bits = [];\n    for(let word of arr) {\n        let b = 0, flag = true;\n        for(let c of word) {\n            const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);\n            const setBit = (1 << idx);\n            if((b & setBit) != 0) {\n                flag = false;\n                break;\n            }\n            b = (b ^ setBit);\n        }\n        if(flag) bits.push(b);\n    }\n    \n    const len = bits.length;\n    const dp = new Map();\n    const solve = (i = 0, b = 0) => {\n        if(i == len) {\n            let c = 0;\n            while(b > 0) {\n                c += (b & 1);\n                b >>= 1;\n            }\n            return c;\n        }\n        const key = [i, b].join(':');\n        if(dp.has(key)) return dp.get(key);\n        \n        let ans = 0;\n        if((b & bits[i]) == 0) {\n            // take\n            ans = Math.max(ans, solve(i + 1, b | bits[i]));\n        }\n        ans = Math.max(ans, solve(i + 1, b));\n        dp.set(key, ans);\n        return ans;\n    }\n    return solve();\n};",
        "solution_java": "class Solution {\n    public int maxLength(List<String> arr) {\n        String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);\n        int[] dp = new int[1<<words.length];\n        int[] ok = new int[1<<words.length];\n        for (int i = 0; i < words.length; i++){\n            for (char ch : words[i].toCharArray()){\n                ok[1<<i]|=1<<(ch-'a');\n                dp[1<<i]++;\n            }\n        }\n        int ans = 0;\n        for (int i = 0; i < dp.length; i++){\n            if ((ok[i&(i-1)]&ok[i&-i])==0){\n                dp[i] = dp[i&(i-1)] + dp[i&-i];\n                ok[i] = ok[i&(i-1)] | ok[i&-i];\n            }\n            ans = Math.max(ans, dp[i]);\n        }\n        return ans;\n    }\n}",
        "solution_c": "/*\n1. Create a integer vector, where each integer's bits represent, if a particular char is present or not\n2. Loop each word in the array and set each bit, create bit map of each word\n3. Use recursion to add each word with take once and not to take once type dp recursion \n4. A word can only be taken if its bits are not overlaping with the current string's bit status\n   - to do this, we need to check if there sum is equal to bit wise andding of them, \n     if eaual then there is no overlaping, if not equal then there is overlaping\n5. Also we don't have to take the word which has repeted char ( if we have set it to INT_MAX )\n6. Finally if i is less then 0, check the size of the s with the ans and take maximum\n*/\n\nclass Solution {\npublic:\n    int ans = 0;\n    void solve(vector<int>& v, vector<string>& arr, int i, string s, int status){\n        if(i < 0) { \n            ans = max(ans, (int)s.size());\n        }else{\n            solve(v, arr, i-1, s, status);\n            if( (v[i] != INT_MAX ) && ( (v[i] + status) == (v[i] | status)) ){ \n                solve(v, arr, i-1, s+arr[i], status  | v[i]);\n            }\n        }\n    }\n    \n    int maxLength(vector<string>& arr) {\n        vector<int> v(arr.size());\n        for(int i= 0; i < arr.size(); ++i){\n            for(auto c: arr[i]) {\n                if((v[i] >> (c - 'a'))& 1){ //if already bit is set, then set value to INT_MAX\n                    v[i] = INT_MAX;\n                }else{                      // if not set, then set it to 1\n                    v[i] = v[i] | (1 << (c - 'a'));\n                }\n            }\n        }\n        string s = \"\";\n        solve(v, arr, arr.size()-1, s, 0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Spiral Matrix II",
        "algo_input": "Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: [[1,2,3],[8,9,4],[7,6,5]]\n\n\nExample 2:\n\nInput: n = 1\nOutput: [[1]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 20\n\n",
        "solution_py": "class Solution(object):\n    def generateMatrix(self, n):\n        if n==1:\n            return [[1]]\n        matrix=[[0 for a in range(n)] for b in range(n)]\n        le_b=0\n        u_b=0\n        r_b=n-1\n        lo_b=n-1\n        ele=1\n        while ele<(n**2)+1:\n            i=u_b\n            j=le_b\n            while ele<(n**2)+1 and j<=r_b:\n                matrix[i][j]=ele\n                ele+=1\n                j+=1\n            u_b+=1\n            i=u_b\n            j=r_b\n            while ele<(n**2)+1 and i<=lo_b:\n                matrix[i][j]=ele\n                ele+=1\n                i+=1\n            r_b-=1\n            i=lo_b\n            j=r_b\n            while ele<(n**2)+1 and j>=le_b:\n                matrix[i][j]=ele\n                ele+=1\n                j-=1\n            lo_b-=1\n            i=lo_b\n            j=le_b\n            while ele<(n**2)+1 and i>=u_b:\n                matrix[i][j]=ele\n                ele+=1\n                i-=1\n            le_b+=1\n        return matrix\n        ```",
        "solution_js": "var generateMatrix = function(n) {\n    const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));\n    let count = 1, index = 1, i = 0, j =0, changed = false, toIncrease = true;\n    arr[i][j] = index;\n    while(index < n*n) {\n        index++;\n        if(i == n-count && j > count-1) {\n            j--;\n            toIncrease = false;\n            changed = true;\n        }\n        else if(i !== n-count && j == n-count) {\n            i++;\n            toIncrease = false;\n            changed = true;\n        }\n        if(i == count-1 && !changed) {\n            if(toIncrease) j++;\n            else j--;\n        }\n        else if(j == count-1 && !changed) {\n            if(i == count) {\n                toIncrease = true;\n                j++;\n                count++;\n            }\n            else if(toIncrease) i++;\n            else i--;\n        }\n        arr[i][j] = index;\n        if(index == 4*(n-1)) {\n            toIncrease = true;\n            count++;\n        }\n        changed = false;\n    }\n    return arr;\n};",
        "solution_java": "class Solution {\n    public int[][] generateMatrix(int n) {\n        int startingRow = 0;\n        int endingRow = n-1;\n        int startingCol = 0;\n        int endingCol = n-1;\n\n        int total = n*n;\n        int element = 1;\n        int[][] matrix = new int[n][n];\n\n        while(element<=total){\n\n        for(int i = startingCol; element<=total && i<=endingCol; i++){\n            matrix[startingRow][i] = element;\n            element++;\n        }\n        startingRow++;\n\n        for(int i = startingRow; element<=total && i<=endingRow; i++){\n            matrix[i][endingCol] = element;\n            element++;\n        }\n        endingCol--;\n\n        for(int i = endingCol; element<=total && i>=startingCol; i--){\n            matrix[endingRow][i] = element;\n            element++;\n        }\n        endingRow--;\n\n        for(int i = endingRow; element<=total && i>=startingRow; i--){\n            matrix[i][startingCol] = element;\n            element++;\n        }\n        startingCol++;\n\n        }\n\n        return matrix;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> generateMatrix(int n) {\n        vector<vector<int>> vec( n , vector<int> (n, 0));\n\n        vector<int>helper;\n        for(int i=0;i<n*n;i++){\n            helper.push_back(i+1);\n        }\n\n        int k = 0;\n        int top = 0;\n        int down = n-1;\n\n        int left = 0;\n        int right = n-1;\n\n        int direction = 0;\n\n        vector<int>result;\n\n        while(top<=down and left<=right){\n            if(direction==0){\n                for(int i=left;i<=right;i++){\n                    vec[top][i] = helper[k];\n                    k++;\n                }\n                top++;\n            }\n            else if(direction==1){\n                for(int i=top;i<=down;i++){\n                    vec[i][right] = helper[k];\n                    k++;\n                }\n                right--;\n            }\n            else if(direction==2){\n                for(int i=right;i>=left;i--){\n                    vec[down][i] = helper[k];\n                    k++;\n                }\n                down--;\n            }\n            else if(direction==3){\n                for(int i=down;i>=top;i--){\n                    vec[i][left] = helper[k];\n                    k++;\n                }\n                left++;\n            }\n            direction = (direction+1)%4;\n        }\n        return vec;\n    }\n};"
    },
    {
        "title": "Check If It Is a Straight Line",
        "algo_input": "You are given an array&nbsp;coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points&nbsp;make a straight line in the XY plane.\n\n&nbsp;\n\n&nbsp;\nExample 1:\n\n\n\nInput: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput: true\n\n\nExample 2:\n\n\n\nInput: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;=&nbsp;coordinates.length &lt;= 1000\n\tcoordinates[i].length == 2\n\t-10^4 &lt;=&nbsp;coordinates[i][0],&nbsp;coordinates[i][1] &lt;= 10^4\n\tcoordinates&nbsp;contains no duplicate point.\n",
        "solution_py": "class Solution(object):\n    def checkStraightLine(self, coordinates):\n        \"\"\"\n        :type coordinates: List[List[int]]\n        :rtype: bool\n        \"\"\"\n        if len(coordinates) == 2:\n            return True\n        \n        num = coordinates[1][1] - coordinates[0][1]\n        den = coordinates[1][0] - coordinates[0][0]\n        \n        for i in range(2, len(coordinates)):\n            if num * (coordinates[i][0] - coordinates[0][0]) != den * (coordinates[i][1] - coordinates[0][1]):\n                return False\n        \n        return True",
        "solution_js": "var checkStraightLine = function(coordinates) {\n    coordinates.sort((a, b) => a[1] - b[1])\n    \n    let slopeToCheck = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0])\n    \n    for (let i = 2; i < coordinates.length; i++) {\n        let currSlope = (coordinates[i][1] - coordinates[i - 1][1]) / (coordinates[i][0] - coordinates[i - 1][0]);\n        \n        if (currSlope !== slopeToCheck) return false;\n    }\n    \n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean checkStraightLine(int[][] coordinates) {\n        int x1=coordinates[0][0];\n        int y1=coordinates[0][1];\n        \n        int x2=coordinates[1][0];\n        int y2=coordinates[1][1];\n        \n        float slope;\n        if(x2-x1 == 0)\n        {\n            slope=Integer.MAX_VALUE;\n        }\n        else\n        {\n            slope=(y2-y1)/(float)(x2-x1);\n        }\n        for(int i=0;i<coordinates.length;i++)\n        {\n            for(int j=0;j<2;j++)\n            {\n                if(slope==Integer.MAX_VALUE)\n                {\n                    if(coordinates[i][0]!=x1)\n                        return false;\n                }\n                else\n                {\n                    int y=coordinates[i][1];\n                    int x=coordinates[i][0];\n                    if((float)(y-y1) != slope*(x-x1))\n                        return false;\n                }\n                    \n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkStraightLine(vector<vector<int>>& coordinates) {\n        \n        int n=coordinates.size();  \n        int xdiff = coordinates[1][0] - coordinates[0][0]; \n        int ydiff = coordinates[1][1] - coordinates[0][1];\n        \n        int cur_xdiff, cur_ydiff;\n        \n        for(int i=2; i<n; i++){\n            \n            cur_xdiff = coordinates[i][0] - coordinates[i-1][0];\n            cur_ydiff = coordinates[i][1] - coordinates[i-1][1];\n            \n            if(ydiff*cur_xdiff!=xdiff*cur_ydiff) return false;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Sliding Window Median",
        "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. So the median is the mean of the two middle values.\n\n\n\tFor examples, if arr = [2,3,4], the median is 3.\n\tFor examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.\n\n\nYou are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.\n\nReturn the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\nExplanation: \nWindow position                Median\n---------------                -----\n[1  3  -1] -3  5  3  6  7        1\n 1 [3  -1  -3] 5  3  6  7       -1\n 1  3 [-1  -3  5] 3  6  7       -1\n 1  3  -1 [-3  5  3] 6  7        3\n 1  3  -1  -3 [5  3  6] 7        5\n 1  3  -1  -3  5 [3  6  7]       6\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,2,3,1,4,2], k = 3\nOutput: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 105\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n",
        "solution_py": "import bisect\n\nclass Solution:\n    \n    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n        \n        half = int(k / 2)\n        \n        if k % 2 == 0:\n            i, j = half - 1, half + 1\n        else:\n            i, j = half, half + 1\n        \n        def median(l, i, j):\n            return sum(l[i:j])/len(l[i:j])\n        \n        digits = nums[:k]\n        digits.sort()\n        \n        result = [median(digits, i, j)]\n            \n        for q in range(k, len(nums)):\n            \n            digits.remove(nums[q - k])\n            bisect.insort(digits, nums[q])\n            result.append(median(digits, i, j))   \n            \n        return result",
        "solution_js": "function convertNumber(num) {\n    return parseFloat(num.toFixed(5))\n}\nfunction findMedian(arr) {\n    let start = 0;\n    let end = arr.length-1;\n    let ans;\n    if((end-start+1)%2===0) {\n        ans = (arr[Math.floor((end+start)/2)] + arr[Math.floor((end+start)/2)+1])/2 ;\n    } else {\n        ans = arr[Math.floor((end+start)/2)];\n    }\n    return convertNumber(ans);\n}\nfunction updateWinArray(arr) {\n    if(arr.length===1) {\n        return;\n    }\n    let ele = arr[arr.length-1];\n    let i;\n    for(i=arr.length-2;i>=0;i--) {\n        if(ele < arr[i]) {\n            arr[i+1] = arr[i];\n        } else {\n            break;\n        }\n    }\n    arr[i+1] = ele;\n}\nfunction binarySearch(arr,ele) {\n    let start =0, end = arr.length-1, mid;\n    while(start<=end) {\n        mid = Math.floor((start+end)/2);\n        if(arr[mid]===ele) {\n            return mid;\n        } else if(ele > arr[mid]) {\n            start = mid + 1;\n        } else {\n            end = mid - 1;\n        }\n    }\n}\nvar medianSlidingWindow = function(nums, k) {\n    let i=0,j=0,result=[],winArr=[];\n    while(j<nums.length) {\n        winArr.push(nums[j]);\n        updateWinArray(winArr);\n        if(j-i+1 < k) {\n            j++;\n        } else if(j-i+1 === k) {\n            let ans = findMedian(winArr);\n            result.push(ans);\n            let indexOfiEle = binarySearch(winArr,nums[i]);\n            winArr.splice(indexOfiEle,1);\n            i++;\n            j++;\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public double[] medianSlidingWindow(int[] nums, int k) {\n        Queue<Integer> minHeap = new PriorityQueue<>();\n        Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n        double[] res = new double[nums.length - k + 1];\n        for(int i = 0; i< nums.length; i++){\n            if(i >= k){\n                if(!minHeap.remove(nums[i-k]))\n                    maxHeap.remove(nums[i-k]);\n            }\n\n            // If k is odd, max heap is of odd size and min heap is of even\n            // else both are of even size\n            if(!maxHeap.isEmpty() && nums[i] <= maxHeap.peek()) {\n                maxHeap.add(nums[i]);\n                if(((k&1) == 1 && maxHeap.size() > k/2+1) || ((k&1) == 0 && maxHeap.size() > k/2)){\n                    minHeap.offer(maxHeap.poll());\n                }\n            }else{\n                minHeap.add(nums[i]);\n                if(minHeap.size() > k/2){\n                    maxHeap.offer(minHeap.poll());\n                }\n            }\n            while(!minHeap.isEmpty() && !maxHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){\n                int temp1 = maxHeap.poll();\n                int temp2 = minHeap.poll();\n                maxHeap.add(temp2);\n                minHeap.add(temp1);\n            }\n            if(minHeap.size() + maxHeap.size() == k){\n                if((k&1)==1){\n                    res[i-k+1] = maxHeap.peek();\n                }else{\n                    res[i-k+1] = ((long)minHeap.peek()+ (long)maxHeap.peek())/2.0;\n                }\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "/*\n    https://leetcode.com/problems/sliding-window-median/\n    \n    1. SOLUTION 1: Binary Search\n    \n    The core idea is we maintain a sorted window of elements. Initially we make the 1st window and sort all its elements.\n    Then from there onwards any insertion or deletion is done by first finding the appropriate position where the element \n    exists/shoudl exist. This search is done using binary search.\n    \n    TC: O(klogk (Sorting) + (n - k) * (k + logk)), Binary search in window takes O(logk), but since it is array, insert or delete can take O(k)\n    SC: O(k)\n    \n    2. SOLUTION 2: Height Balanced Tree\n    \n    Core idea is to use a height balanced tree to save all the elements of window. Since it is a height balanced tree, insertion and deletion takes\n    logk. Now we directly want to reach the k/2 th element, then it takes O(k/2). So we need to optimize the mid point fetch.\n    \n    Initially when the 1st window is built, we find the middle element with O(k/2). Then from there onwards we always adjust the middle position\n    by +1 or -1. Since only one element is either added or deleted at a time, so we can move the median left or right based on the situation.\n    Eg: [1,2,3,4,5,6,7], median = 4\n    \n    if we add one element say 9\n    [1,2,3,4,5,6,7,9], then check (9 < median): this means 1 extra element on right, don't move and wait to see what happens on deletion\n    \n    Similarly, now if 2 is deleted, we can just check (2 <= median(4)): this means there will be one less element on left.\n    So move median to right by 1. If say an element on right like 7 was deleted, we would have not moved and hence the mid ptr would be \n    at its correct position.\n    \n    \n        (1st window insertion) + remaining_windows * (delete element + add element + get middle)\n    TC: O(klogk + (n-k) * (logk + logk + 1)) \n        ~O(klogk + (n-k)*logk) ~O(nlogk)\n    SC: O(k)\n*/\nclass Solution {\npublic:\n    ///////////////////// SOLUTION 1: Binary Search\n    vector<double> binarySearchSol(vector<int>& nums, int k) {\n        vector<double> medians;\n        vector<int> window;\n        // K is over the size of array\n        if(k > nums.size())\n            return medians;\n        \n        int i = 0;\n        // add the elements of 1st window\n        while(i < k) {\n            window.emplace_back(nums[i]);\n            ++i;\n        }\n        \n        // sort the window\n        sort(window.begin(), window.end());\n        // get the median of 1st window\n        double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;\n        medians.emplace_back(median);\n        \n        for(; i < nums.size(); i++) {\n            // search the position of 1st element of the last window using binary search\n            auto it = lower_bound(window.begin(), window.end(), nums[i - k]);\n            window.erase(it);\n            // find the position to insert the new element for the current window\n            it = lower_bound(window.begin(), window.end(), nums[i]);\n            window.insert(it, nums[i]);\n            // Since the window is sorted, we can directly compute the median\n            double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;\n            medians.emplace_back(median);\n        }\n        return medians;\n    }\n    \n    //////////////////////////// SOLUTION 2: Height Balanced Tree\n    vector<double> treeSol(vector<int>& nums, int k) {\n        multiset<int> elements;\n        vector<double> medians;\n        \n        int i = 0;\n        // process the 1st window\n        while(i < k) {\n            elements.insert(nums[i]);\n            ++i;\n        }\n        \n        // median of 1st window\n        auto mid = next(elements.begin(), k / 2);\n        double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;\n        medians.emplace_back(median);\n        \n        for(; i < nums.size(); i++) {\n            // insert last element of current window\n            elements.insert(nums[i]);\n            // If the number lies on the left, left side will have 1 more element.\n            // So shift left by 1 pos\n            if(nums[i] < *mid)\n                --mid;\n            \n            // remove 1st element of last window\n            auto delete_pos = elements.find(nums[i - k]);\n            // If the element to be deleted in [first : mid], then right will have extra element\n            // so move the mid to right by 1\n            // NOTE: We insert the new element and then delete previous element because, if the window has just one element\n            // then deleting first will make mid point to invalid position. But inserting first will ensure that there is an \n            // element to point to\n            if(nums[i-k] <= *mid)\n                ++mid;\n            elements.erase(delete_pos);\n            \n            double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;\n            medians.emplace_back(median);\n        }\n        \n        return medians;\n    }\n    \n    vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n        // return binarySearchSol(nums, k);\n        return treeSol(nums, k);\n    }\n};"
    },
    {
        "title": "Coin Change",
        "algo_input": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\n\nReturn the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.\n\nYou may assume that you have an infinite number of each kind of coin.\n\nThe answer is guaranteed to fit into a signed 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: amount = 5, coins = [1,2,5]\nOutput: 4\nExplanation: there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n\n\nExample 2:\n\nInput: amount = 3, coins = [2]\nOutput: 0\nExplanation: the amount of 3 cannot be made up just with coins of 2.\n\n\nExample 3:\n\nInput: amount = 10, coins = [10]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= coins.length &lt;= 300\n\t1 &lt;= coins[i] &lt;= 5000\n\tAll the values of coins are unique.\n\t0 &lt;= amount &lt;= 5000\n\n",
        "solution_py": "dfs(total)",
        "solution_js": "dfs(total)",
        "solution_java": "class Solution {\n    public int coinChange(int[] coins, int amount) {\n        int m=coins.length,n=amount;\n        int dp[][]=new int[m+1][n+1];\n        for(int j=0;j<=n;j++){\n            dp[0][j]=0;\n        }\n          for(int i=0;i<=m;i++){\n            dp[i][0]=0;\n        }\n        for(int i=1;i<=m;i++){\n            for(int j=1;j<=n;j++){\n               int t1 = Integer.MAX_VALUE;\n        if ((i-1) == 0) {\n            if (j % coins[i-1] == 0) {\n                dp[i][j]= j / coins[i-1];\n            } else {\n                dp[i][j]= (int)1e9;\n            }\n        } \n        else {\n            int t2 = dp[i-1][j];\n        if (coins[i-1] <= j) {\n            t1 = dp[i][j-coins[i-1]] + 1; \n        }\n                dp[i][j]= Math.min(t1, t2);\n        }\n            }\n        }\n          if(dp[m][n]>=1e9)\n        return -1;\n        else\n        return dp[m][n];\n        }\n    }\n    \n  ",
        "solution_c": "dfs(total)"
    },
    {
        "title": "N-Queens II",
        "algo_input": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n\nGiven an integer n, return the number of distinct solutions to the&nbsp;n-queens puzzle.\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: 2\nExplanation: There are two distinct solutions to the 4-queens puzzle as shown.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 9\n\n",
        "solution_py": "class Solution:\n    def totalNQueens(self, n: int) -> int:\n        res=0\n        #用于存放结果\n        pdia=set()\n        ndia=set()\n        col=set()\n\n        def backtrack(r):\n            #利用r作为一种计数,表示目前所在的行数\n            if r==n:\n            #判断已经完成棋盘,返回结果\n                nonlocal res\n                res+=1\n                return\n            for c in range(n):\n                #对于n行n列的棋盘,每次在每一行我们尝试n种选择,\n                #即每个岔路口有n条路线\n                if (r+c) in pdia or (r-c) in ndia or c in col:\n                    #如果在同一对角线,或同一列,则不符合要求\n                    continue\n                col.add(c)\n                pdia.add(r+c)\n                ndia.add(r-c)\n                \n                backtrack(r+1)\n                \n                col.remove(c)\n                pdia.remove(r+c)\n                ndia.remove(r-c)\n\n        backtrack(0)\n        return res",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar totalNQueens = function(n) {\n\t// Keep track of columns with queens\n    const cols = new Set();\n\t// Keep track of positive slope diagonal by storing row number + column number\n    const posDiag = new Set();\n\t// Keep track of negative slope diagonal by storing row number - column number\n    const negDiag = new Set();\n\t// Count of valid boards\n    let count = 0;\n    \n    const backtrack = function(r) {\n\t\t// Base case to end recursion, we have traversed board and found valid position in each row\n        if(r === n) {\n            count += 1;\n            return;\n        }\n\t\t// Loop through each column to see if you can place a queen\n        for(let c = 0; c < n; c++) {\n\t\t\t// invalid position check, if position in set we cannot place queen here\n            if(cols.has(c) || posDiag.has(r+c) || negDiag.has(r-c)) continue;\n            \n\t\t\t// add new queen to sets\n            cols.add(c);\n            posDiag.add(r+c);\n            negDiag.add(r-c);\n            \n\t\t\t// backtrack\n            backtrack(r+1);\n            \n\t\t\t// remove current position from sets because backtracking for this position is complete\n            cols.delete(c);\n            posDiag.delete(r+c);\n            negDiag.delete(r-c);\n        }\n    }\n    \n    backtrack(0);\n    return count;\n};",
        "solution_java": "class Solution {\n    int count = 0;\n    public int totalNQueens(int n) {\n        boolean col[] = new boolean[n];\n        boolean diag[] = new boolean[2*n-1];\n        boolean rdiag[] = new boolean[2*n-1];\n\n        countSolution(n,col, diag, rdiag, 0);\n        return count;\n\n    }\n    void countSolution(int n, boolean[] col, boolean[] diag, boolean[] rdiag, int r ){\n        if (r == n ){\n            count++;\n            return;\n        }\n\n        for(int c = 0 ; c < n; c++){\n            if(col[c] == false && diag[r+c] == false && rdiag[r-c+n-1] == false){\n                col[c] = true;\n                diag[r+c] = true;\n                rdiag[r-c+n-1] = true;\n                countSolution(n, col, diag, rdiag, r+1);\n                col[c] = false;\n                diag[r+c] = false;\n                rdiag[r-c+n-1] = false;\n            }\n        }\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int totalNQueens(int n) {\n    vector<bool> col(n), diag(2*n-1), anti_diag(2*n-1);\n    return solve(col, diag, anti_diag, 0);\n}\n\nint solve(vector<bool>& col, vector<bool>& diag, vector<bool>& anti_diag, int row) {\n    int n = size(col), count = 0;\n    if(row == n) return 1;\n    for(int column = 0; column < n; column++)\n        if(!col[column] && !diag[row + column] && !anti_diag[row - column + n - 1]){\n            col[column] = diag[row + column] = anti_diag[row - column + n - 1] = true;\n            count += solve(col, diag, anti_diag, row + 1);\n            col[column] = diag[row + column] = anti_diag[row - column + n - 1] = false;\n        }\n    return count;\n}\n};"
    },
    {
        "title": "Intersection of Multiple Arrays",
        "algo_input": "Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.\n&nbsp;\nExample 1:\n\nInput: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\nOutput: [3,4]\nExplanation: \nThe only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].\n\nExample 2:\n\nInput: nums = [[1,2,3],[4,5,6]]\nOutput: []\nExplanation: \nThere does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= sum(nums[i].length) &lt;= 1000\n\t1 &lt;= nums[i][j] &lt;= 1000\n\tAll the values of nums[i] are unique.\n\n",
        "solution_py": "class Solution:\n    def intersection(self, A: List[List[int]]) -> List[int]:\n        return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])\n\t\t",
        "solution_js": "var intersection = function(nums) {\n    let set = addToSet(nums[0]);\n    for(let i=1; i<nums.length; i++) {\n        let tempSet = addToSet(nums[i]);\n        for(let key of set) {\n            if( !tempSet.has(key) )\n                set.delete(key);\n        }\n    }\n    return [...set].sort( (a,b) => a-b );\n};\n\nfunction addToSet(arr) {\n    let set = new Set(arr);\n    return set;\n}",
        "solution_java": "class Solution {\n    public List<Integer> intersection(int[][] nums) {\n\n        List<Integer> ans = new ArrayList<>();\n\n        int[] count = new int[1001];\n\n        for(int[] arr : nums){\n            for(int i : arr){\n                count[i]++;\n            }\n        }\n\n       for(int i=0;i<count.length;i++){\n           if(count[i]==nums.length){\n               ans.add(i);\n           }\n       }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> intersection(vector<vector<int>>& nums) {\n        int n = nums.size(); // gives the no. of rows\n        map<int,int> mp; // we don't need unordered_map because we need the elements to be in sorted format.\n        vector<int> vec;\n        \n        // traverse through the 2D array and store the frequency of each element\n        for(int row=0;row<n;row++)\n        {\n            for(int col=0;col<nums[row].size();col++)\n            {\n                mp[nums[row][col]]++;\n            }\n        }\n        \n        // In the 2D array, intersection occurs when the elements are present in every row.\n        // So the frequency of the element should match with the no. or rows in the 2D array.\n        for(auto element : mp)\n            if(element.second == n)\n                vec.push_back(element.first);\n        \n        // return the intersecting elements\n        return vec;\n    }\n};"
    },
    {
        "title": "Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold",
        "algo_input": "Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput: 3\nExplanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).\n\n\nExample 2:\n\nInput: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput: 6\nExplanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i] &lt;= 104\n\t1 &lt;= k &lt;= arr.length\n\t0 &lt;= threshold &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n        wstart = wsum = count = 0\n        \n        for wend in range(len(arr)):\n            wsum += arr[wend]\n            \n            if wend >= k:\n                wsum -= arr[wstart]\n                wstart += 1\n            if (wsum//k) >= threshold and (wend-wstart+1) == k: \n                count += 1\n        return count",
        "solution_js": "var numOfSubarrays = function(arr, k, threshold) {\n    let total = 0;\n    let left = 0;\n    let right = k;\n    // get initial sum of numbers in first sub array range, by summing left -> right\n    let sum = arr.slice(left, right).reduce((a, b) => a + b, 0);\n    while (right <= arr.length) {\n        // move through the array as a sliding window\n        if (left > 0) {\n            // on each iteration of the loop, subtract the val that has fallen out of the window, \n            // and add the new value that has entered the window\n            sum -= arr[left - 1];\n            sum += arr[right - 1];\n        }\n        if (sum / k >= threshold) {\n            total++;\n        }\n        left++;\n        right++;\n    }\n    return total;\n};",
        "solution_java": "class Solution {\n    public int numOfSubarrays(int[] arr, int k, int threshold) {\n        int average=0,count=0,start=0,sum=0;       \n        for(int i=0;i<arr.length;i++){\n            sum+=arr[i];\n            if(i>=k-1){\n                average=sum/k;\n                if(average>=threshold) count++;\n                sum-=arr[start];          \n                start++;   \n            }          \n        }\n        return count;  \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numOfSubarrays(vector<int>& arr, int k, int threshold) {\n        int i=0;int j=0;int sum=0;int ans=0;\n        while(j<arr.size()){\n            sum+=arr[j];\n            if(j-i+1<k) j++;\n            else if(j-i+1==k){\n               if(sum/k>=threshold){\n                   ans++;\n               } \n                sum-=arr[i];\n                j++;\n                i++;\n            }  \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Remove Palindromic Subsequences",
        "algo_input": "You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.\n\nReturn the minimum number of steps to make the given string empty.\n\nA string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.\n\nA string is called palindrome if is one that reads the same backward as well as forward.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ababa\"\nOutput: 1\nExplanation: s is already a palindrome, so its entirety can be removed in a single step.\n\n\nExample 2:\n\nInput: s = \"abb\"\nOutput: 2\nExplanation: \"abb\" -&gt; \"bb\" -&gt; \"\". \nRemove palindromic subsequence \"a\" then \"bb\".\n\n\nExample 3:\n\nInput: s = \"baabb\"\nOutput: 2\nExplanation: \"baabb\" -&gt; \"b\" -&gt; \"\". \nRemove palindromic subsequence \"baab\" then \"b\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts[i] is either 'a' or 'b'.\n\n",
        "solution_py": "class Solution:\n    def removePalindromeSub(self, s: str) -> int:\n        return 1 if s[::-1] == s else 2\n        ",
        "solution_js": "var removePalindromeSub = function(s) {\n    const isPalindrome = s == s.split('').reverse().join('');\n    return isPalindrome ? 1 : 2;\n};",
        "solution_java": "class Solution\n{\n    public int removePalindromeSub(String s)\n    {\n        int left = 0 , right = s.length() - 1 ;\n        while( left < right )\n        {\n            if( s.charAt(left++) != s.charAt(right--) )\n            {\n                return 2 ;\n            }\n        }\n        return 1 ;\n    }\n}",
        "solution_c": "  //the major obersavation or we can also verify by giving your own test it always returns 1 or 2 \n    //if the whole string is palindrom then return 1 if not then return 2.\nclass Solution {\n   static bool isPal(string s){\n        string p = s;\n        reverse(p.begin() , p.end());\n       return s==p;     \n    }\npublic:\n    int removePalindromeSub(string s) {\n  \n        if(isPal(s)){\n            return 1;\n        } \n        \n        return 2;\n    }\n};"
    },
    {
        "title": "Tallest Billboard",
        "algo_input": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\n\nYou are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.\n\nReturn the largest possible height of your billboard installation. If you cannot support the billboard, return 0.\n\n&nbsp;\nExample 1:\n\nInput: rods = [1,2,3,6]\nOutput: 6\nExplanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n\n\nExample 2:\n\nInput: rods = [1,2,3,4,5,6]\nOutput: 10\nExplanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n\n\nExample 3:\n\nInput: rods = [1,2]\nOutput: 0\nExplanation: The billboard cannot be supported, so we return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rods.length &lt;= 20\n\t1 &lt;= rods[i] &lt;= 1000\n\tsum(rods[i]) &lt;= 5000\n\n",
        "solution_py": "class Solution:\n    def tallestBillboard(self, rods: List[int]) -> int:\n        dp = collections.defaultdict(int)\n        dp[0] = 0\n        for x in rods:\n            nxt = dp.copy()\n            for d, y in dp.items():\n                # init state\n                # ------|----- d -----| # tall side\n                # - y --| # low side\n\n                # put x to tall side\n                # ------|----- d -----|---- x --|\n                # - y --|\n                nxt[d + x] = max(nxt.get(x + d, 0), y)\n\n                nxt[abs(d - x)] = max(nxt.get(abs(d - x), 0), y + min(d, x))\n            dp = nxt\n        return dp[0]",
        "solution_js": "/**\n * @param {number[]} rods\n * @return {number}\n */\nvar tallestBillboard = function(rods) {\n    let len = rods.length;\n    if (len <= 1) return 0;\n    let dp = [];\n    for (let i = 0; i < len + 5; i++) {\n        dp[i] = [];\n        for (let j = 0; j < 5005 * 2; j++) {\n            dp[i][j] = -1\n        }\n    }\n    return solve(0, 0, rods, dp);\n}\n\nvar solve = function(i, sum, rods, dp) {\n  if (i == rods.length) {\n        if (sum == 0) {\n            return 0\n        }else{\n            return -5000\n        }\n    }\n    if (dp[i][sum + 5000] != -1) {\n        return dp[i][sum + 5000];\n    }\n    let val = solve(i + 1, sum, rods, dp);\n    val = Math.max(val, solve(i + 1, sum + rods[i], rods, dp) + rods[i]);\n    val = Math.max(val, solve(i + 1, sum - rods[i], rods, dp));\n    dp[i][sum + 5000] = val;\n    return val;\n}",
        "solution_java": "class Solution {\n    public int tallestBillboard(int[] rods) {\n        int[] result = new int[1];\n        dfs(rods, 0, 0, 0, rods.length, result);\n        return result[0];\n    }\n    private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {\n        if (level == n) {\n            if (left == right) {\n                result[0] = Math.max(left, result[0]);\n            }\n            return;\n        }\n        \n        dfs(rods, left, right, level + 1, n, result);\n        dfs(rods, left + rods[level], right, level + 1, n, result);\n        dfs(rods, left, right + rods[level], level + 1, n, result);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint f(int i,vector<int>& v, int a, int b){\n\t\tif(i==v.size()){\n\t\t\tif(a==b){\n\t\t\t\treturn a;\n\t\t\t}\n\t\t  return 0;\n\t\t}\n\n\t\tint x = f(i+1,v,a,b);\n\t\tint y = f(i+1,v,a+v[i],b);\n\t\tint z = f(i+1,v,a,b+v[i]);\n\n\t\treturn max({x,y,z});\n\t}\n\tint tallestBillboard(vector<int>& rods) {\n\t\treturn f(0,rods,0,0);\n\n\t}\n};"
    },
    {
        "title": "Swap Adjacent in LR String",
        "algo_input": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.\n\n&nbsp;\nExample 1:\n\nInput: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput: true\nExplanation: We can transform start to end following these steps:\nRXXLRXRXL -&gt;\nXRXLRXRXL -&gt;\nXRLXRXRXL -&gt;\nXRLXXRRXL -&gt;\nXRLXXRRLX\n\n\nExample 2:\n\nInput: start = \"X\", end = \"L\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= start.length&nbsp;&lt;= 104\n\tstart.length == end.length\n\tBoth start and end will only consist of characters in 'L', 'R', and&nbsp;'X'.\n\n",
        "solution_py": "class Solution:\n    def canTransform(self, start: str, end: str) -> bool:\n        def chars(s):\n            for i, c in enumerate(s):\n                if c != 'X':\n                    yield i, c\n            \n            yield -1, ' '\n        \n        for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):\n            if (startC != endC or\n                (startC == 'L' and startI < endI) or\n                (startC == 'R' and startI > endI)):\n                return False\n        \n        return True",
        "solution_js": "/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n    let i = 0;\n    let j = 0;\n\n    while (i < start.length || j < end.length) {\n        if (start[i] === 'X') {\n            i++;\n            continue;\n        }\n\n        if (end[j] === 'X') {\n            j++;\n            continue;\n        }\n\n        // Breaking (1)\n        if (start[i] !== end[j]) return false;\n\n        // Breaking (2)\n        if (start[i] === 'R' && i > j) return false;\n\n        // Breaking (3)\n        if (start[i] === 'L' && j > i) return false;\n\n        i++;\n        j++;\n    }\n\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean canTransform(String start, String end) {\n        int startL = 0, startR = 0;\n        int endL = 0, endR = 0;\n        String stLR = \"\", edLR = \"\";\n        for(int i = 0; i < start.length(); i++) {\n            if(start.charAt(i) != 'X') {\n                if(start.charAt(i) == 'L') {\n                    startL++;\n                } else{\n                    startR++;\n                }\n                stLR+= start.charAt(i);\n            }\n            if(end.charAt(i) != 'X') {\n                if(end.charAt(i) == 'L') {\n                    endL++;\n                } else{\n                    endR++;\n                }\n                edLR += end.charAt(i);\n            }\n\n            if(startL > endL || startR < endR) //Check conditions at each instant\n                return false;\n        }\n\n        if(startL != endL || startR != endR || !stLR.equals(edLR)) //check their final count and positions\n            return false;\n\n        return true;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    bool canTransform(string start, string end) {\n        int s=0,e=0;\n        while(s<=start.size() and e<=end.size()){\n            while(s<start.size() and start[s]=='X'){\n                s++;\n            }\n            while(e<end.size() and end[e]=='X'){\n                e++;\n            }\n            if(s==start.size() or e==end.size()){\n                return s==start.size() and e==end.size();\n            } else if(start[s]!=end[e]){\n                return false;\n            } else if(start[s]=='R' and e<s){\n                return false;\n            } else if(start[s]=='L' and e>s){\n                return false;\n            }\n            s++;\n            e++;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Max Points on a Line",
        "algo_input": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 3\n\n\nExample 2:\n\nInput: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 300\n\tpoints[i].length == 2\n\t-104 &lt;= xi, yi &lt;= 104\n\tAll the points are unique.\n\n",
        "solution_py": "class Solution:\n    def maxPoints(self, points: List[List[int]]) -> int:\n        ans = 0\n        n = len(points)\n        \n        for i in range(n):\n            d = collections.defaultdict(int)\n            for j in range(n):\n                if i != j:\n                    slope = float(\"inf\")\n                    if (points[j][1] - points[i][1] != 0):\n                        slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1])\n                    d[slope] += 1\n            if d:\n                ans = max(ans, max(d.values())+1)\n            else:\n                ans = max(ans, 1)\n        \n        return ans",
        "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\n\nvar maxPoints = function(points) {\n    if (points.length === 1) {\n        return 1;\n    }\n    \n    const slopes = {};\n    let dx, dy;\n    let xbase, ybase;\n    let xref, yref, key;\n    const INFINITE_SLOPE = 'infinite';\n    \n    for(let i = 0; i < points.length; i++) {\n        [xbase, ybase] = points[i];\n        \n        for(let j = i + 1; j < points.length; j++) {                       \n            \n            [xref, yref] = points[j];\n            \n            if (xref === xbase) {\n                key = `x = ${xref}`;\n                \n            } else {\n                dx = xref - xbase;\n                dy = yref - ybase;\n                \n                let m = dy / dx;\n                let c = yref - m * xref;\n                \n                m = m.toFixed(4);\n                c = c.toFixed(4);\n                \n                key = `y = ${m}x + ${c}`;                \n            }\n            \n            slopes[key] || (slopes[key] = 0);\n            slopes[key]++;\n        }\n    }\n    \n    const maxPairs = Math.max(...Object.values(slopes));\n    \n    if (maxPairs === 2) {\n        return 2;\n    }\n    \n    for(let i = 1; i <= 300; i++) {\n        if (i * (i - 1) / 2 === maxPairs) {\n            return i;\n        }\n    }\n    \n    return 0;\n};",
        "solution_java": "class Solution {\n    public int maxPoints(int[][] points) {\n        int n = points.length;\n        if(n == 1) return n;\n        int result = 0;\n        for(int i = 0; i< n; i++){\n            for(int j = i+1; j< n; j++){\n                result = Math.max(result, getPoints(i, j, points));\n            }\n        }\n        return result;\n    }\n    private int getPoints(int pt1, int pt2, int[][] points){\n        int[] point1 = points[pt1], point2 = points[pt2];\n        double slope = (point1[1] - point2[1])/(double)(point1[0] - point2[0]);\n        int result = 0;\n        for(int i = 0; i<points.length; i++){\n            if((points[i][0] == point1[0] && points[i][1] == point1[1]) ||\n               (slope == Double.POSITIVE_INFINITY && (point1[1] - points[i][1])/(double)(point1[0] - points[i][0]) == Double.POSITIVE_INFINITY) ||\n               ((double)(point1[1] - points[i][1])/(double)(point1[0] - points[i][0]) == slope))\n                result++;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    //DP solution\n    //TC-O(N*N)\n    //SC- ~ O(N*N)\n    //Custom Sort\n    bool static cmp(vector<int> p1,vector<int> p2){\n        if(p1[0]==p2[0])\n            return p1[1]<p2[1];\n        return p1[0]<p2[0];\n    }\n\n    //Slope Calculating\n    float calcSlope(int x1,int y1,int x2,int y2){\n       return (y2-y1)/(float)(x2-x1);\n    }\n    int maxPoints(vector<vector<int>>& points) {\n        if(points.size()==2 || points.size()==1)\n            return points.size();\n\n        sort(points.begin(),points.end(),cmp);\n        int ans=1;\n        //How much points having same slope at current index\n        vector<unordered_map<float,int>> dp(points.size()+1);\n        for(int i=1;i<points.size();i++){\n            for(int j=0;j<i;j++){\n                float slope=calcSlope(points[j][0],points[j][1],points[i][0],points[i][1]);\n                if(dp[j].find(slope)!=dp[j].end()){\n                    dp[i][slope]=1+dp[j][slope];\n                    ans=max(ans,dp[i][slope]);\n                }else{\n                    dp[i][slope]+=1;\n                }\n            }\n        }\n        //return ans\n\n        return ans+1;\n\n    }\n};"
    },
    {
        "title": "Count Number of Nice Subarrays",
        "algo_input": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\n\nReturn the number of nice sub-arrays.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\n\n\nExample 2:\n\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There is no odd numbers in the array.\n\n\nExample 3:\n\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 50000\n\t1 &lt;= nums[i] &lt;= 10^5\n\t1 &lt;= k &lt;= nums.length\n",
        "solution_py": "class Solution(object):\n\tdef numberOfSubarrays(self, nums, k):\n\t\t\"\"\"\n\t\te.g. k = 2\n\t\tnums = [2, 2, 1, 2, 1, 2, 2]\n\t\tindex=  0  1  2  3  4  5  6\n\t\t2 even numbers to left of first 1\n\t\t2 even numbers to right of last 1\n\t\ttotal number of subarrays = pick between 0-2 numbers on left, then, pick between 0-2 numbers on right\n\t\ti.e (left+1)  (right+1)\n\t\tThen slide window to next set of 2 odd numbers\n\t\t\"\"\"\n\n\t\todds = []\n\n\t\tfor i in range(len(nums)):\n\t\t\tif nums[i] & 1:\n\t\t\t\todds.append(i)                      #' Find index of all odd numbers '\n\n\t\todds = [-1] + odds + [len(nums)]            #' Handle edge cases '\n\t\tnice = 0\n\n\t\tfor i in range(1, len(odds)-k):\n\t\t\tleft = odds[i] - odds[i-1] - 1          #' Number of 'left' even numbers '\n\t\t\tright = odds[i+k] - odds[i+k-1] - 1     #' Number of 'right' even numbers '\n\t\t\tnice += (left+1)*(right+1)              #' Total sub-arrays in current window '\n\n\t\treturn nice\n    ",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar numberOfSubarrays = function(nums, k) {\n    const len = nums.length;\n    const pre = new Array(len).fill(-1);\n    const post = new Array(len).fill(len);\n\n    let lastOcc = -1;\n    for(let i = 0; i < len; i++) {\n        pre[i] = lastOcc;\n        if(nums[i] & 1) lastOcc = i;\n    }\n    lastOcc = len;\n    for(let i = len - 1; i >= 0; i--) {\n        post[i] = lastOcc;\n        if(nums[i] & 1) lastOcc = i;\n    }\n\n    let l = 0, r = 0, oddCount = 0;\n\n    let ans = 0;\n\n    for(; r < len; r++) {\n        while(l < len && !(nums[l] & 1)) l++;\n        if(nums[r] & 1) oddCount++;\n\n        if(oddCount == k) {\n            let leftCount = l - pre[l];\n            let rightCount = post[r] - r;\n            ans += leftCount * rightCount;\n\n            oddCount--;\n            l++;\n        }\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int numberOfSubarrays(int[] nums, int k) {\n        int i = 0;\n        int j = 0;\n        int odd = 0;\n        int result = 0;\n        int temp = 0;\n\n        /*\n            Approach : two pointer + sliding window technique\n\n            step 1 : we have fix i and moving j until our count of odd numbers == k\n            step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i\n\n        why temp?\n        from reducing the size of subarray we will count all the possible subarray from between i and j\n        but when i encounter a odd element the odd count will reduce and that while will stop executing\n\n        now there are two possible cases\n        1.The leftover elements have a odd number\n        2.The leftover elements do not have any odd number\n\n        1. if our leftover elements have a odd number\n                then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed\n                that's why temp = 0;\n\n        2. if out leftover elements do not have any odd element left\n            then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays\n        */\n        while(j< nums.length){\n            if(nums[j]%2 != 0)\n            {\n                odd++;\n                //if leftover elements have odd element then new window is formed so we set temp = 0;\n                temp = 0;\n            }\n            while(odd ==k){\n                temp++;\n                if(nums[i] %2 != 0)\n                    odd--;\n                i++;\n             }\n          //if no leftover elements is odd, each element will part in forming subarray\n        //so include them\n            result += temp;\n            j++;\n\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nums;\n    int solve(int k){\n        int low = 0, high = 0, cnt = 0, res = 0;\n\n        while(high < nums.size()){\n            if(nums[high] & 1){\n                cnt++;\n\n                while(cnt > k){\n                    if(nums[low] & 1) cnt--;\n                    low++;\n                }\n            }\n            high++;\n            res += high - low;\n        }\n\n        return res;\n    }\n    int numberOfSubarrays(vector<int>& nums, int k) {\n        this -> nums = nums;\n        return solve(k) - solve(k - 1);\n    }\n};"
    },
    {
        "title": "Number of Ways to Arrive at Destination",
        "algo_input": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.\n\nYou are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.\n\nReturn the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6\n\n\nExample 2:\n\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 200\n\tn - 1 &lt;= roads.length &lt;= n * (n - 1) / 2\n\troads[i].length == 3\n\t0 &lt;= ui, vi &lt;= n - 1\n\t1 &lt;= timei &lt;= 109\n\tui != vi\n\tThere is at most one road connecting any two intersections.\n\tYou can reach any intersection from any other intersection.\n\n",
        "solution_py": "class Solution:\n    def countPaths(self, n: int, roads: List[List[int]]) -> int:\n        graph = defaultdict(dict)\n        for u, v, w in roads:\n            graph[u][v] = graph[v][u] = w\n        dist = {i:float(inf) for i in range(n)}\n        ways = {i:0 for i in range(n)}\n        dist[0], ways[0] = 0, 1\n        heap = [(0, 0)]\n        while heap:\n            d, u = heapq.heappop(heap)\n            if dist[u] < d: \n                continue\n            for v in graph[u]:\n                if dist[v] == dist[u] + graph[u][v]:\n                    ways[v] += ways[u]\n                elif dist[v] > dist[u] + graph[u][v]:\n                    dist[v] = dist[u] + graph[u][v]\n                    ways[v] = ways[u]\n                    heapq.heappush(heap, (dist[v], v))\n        return ways[n-1] % ((10 ** 9) + 7)",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} roads\n * @return {number}\n */\nvar countPaths = function(n, roads) {\n    let adj = {}, dist = Array(n).fill(Infinity), minHeap = new MinHeap(), count = Array(n).fill(1);\n\n    //CREATE ADJ MATRIX\n    for(let [from, to , weight] of roads){\n        adj[from] = adj[from] || []\n        adj[from].push([to, weight]);\n        adj[to] = adj[to] || []\n        adj[to].push([from, weight]);\n    }\n\n    //PUT START IN QUEUE\n    dist[n-1] = 0;\n    minHeap.enqueue(n-1, 0);\n\n    while(minHeap.getSize()){\n        let [node, curDist] = minHeap.dequeue();\n        let children = adj[node] || [];\n        for(let [childNode, childWeight] of children){\n\n            //IF PATH ALREADY FOUND WITH THIS VALUE THEN ADD COUNT REACHED UNTIL NOW\n            if(curDist + childWeight === dist[childNode]){\n                count[childNode] = (count[childNode] +count[node]) % 1000000007;\n            } //IF NOT PATH FOUND YET THEN ADD COUNT OF WAYS TO THE NODE WE CAME FROM\n            else if(curDist + childWeight < dist[childNode]){\n                count[childNode] = count[node];\n                dist[childNode] = curDist + childWeight;\n                minHeap.enqueue(childNode, dist[childNode]);\n            }\n        }\n    }\n    return count[0];\n};\n\nclass MinHeap{\n    constructor(list = []){\n        this.tree = [null];\n        this.list = list;\n        this.build();\n    }\n\n    build(){\n        for(let [val,priority] of this.list)\n            this.enqueue(val,priority);\n    }\n\n    swap(pos1, pos2){\n        [this.tree[pos1], this.tree[pos2]] = [this.tree[pos2],this.tree[pos1]]\n    }\n\n    enqueue(val, priority){\n        this.tree[this.tree.length] = [val, priority];\n        let i = this.tree.length - 1, parent = ~~(i/2);\n        while(i > 1){\n            if(this.tree[parent][1] > this.tree[i][1])\n                this.swap(parent,i);\n            i = parent;\n            parent = ~~(i/2);\n        }\n    }\n\n    dequeue(){\n        let size = this.tree.length - 1, pos = 1;\n        if(!size) return;\n        let last = this.tree.pop(), deleted = this.tree[pos];\n        if(!deleted && last) return last;\n        this.tree[pos] = last;\n        this.heapify(pos);\n        return deleted;\n    }\n\n    heapify(pos){\n\n        if(pos > this.tree.length) return;\n        let leftPos = 2*pos, rightPos = 2*pos +1;\n        let left = this.tree[leftPos] ? this.tree[leftPos][1] : Infinity;\n        let right = this.tree[rightPos] ? this.tree[rightPos][1] : Infinity, minVal = null, minIndex = null;\n        if(left < right){\n            minVal = left;\n            minIndex = leftPos;\n        }else{\n            minVal = right;\n            minIndex = rightPos\n        }\n        if(this.tree[pos][1] > minVal){\n            this.swap(pos,minIndex);\n            this.heapify(minIndex);\n        }\n    }\n\n    getTree(){\n        console.log(this.tree.slice(1));\n    }\n\n    getSize(){\n        return this.tree.length - 1;\n    }\n}",
        "solution_java": "class Solution {\n    class Pair{\n        int node;\n        int dist;\n        Pair(int node , int dist){\n            this.node = node;\n            this.dist = dist;\n        }\n    }\n    public int countPaths(int n, int[][] roads) {\n        int mod = (int)Math.pow(10 , 9) + 7;\n        ArrayList<ArrayList<Pair>> adj = new ArrayList<>();\n        int rows = roads.length;\n        for(int i = 0 ; i < n ; i++)\n            adj.add(new ArrayList<Pair>());\n        for(int i = 0 ; i < rows ; i++){\n            int from = roads[i][0];\n            int to = roads[i][1];\n            int dis = roads[i][2];\n            adj.get(from).add(new Pair(to , dis));\n            adj.get(to).add(new Pair(from , dis));\n        }\n        PriorityQueue<Pair> pq = new PriorityQueue<>((aa , bb) -> aa.dist - bb.dist);\n        pq.add(new Pair(0 , 0));\n        long[] ways = new long[n];\n        ways[0] = 1;\n        int[] dist = new int[n];\n        Arrays.fill(dist , Integer.MAX_VALUE);\n        dist[0] = 0;\n        while(!pq.isEmpty()){\n            Pair p = pq.remove();\n            int node = p.node;\n            int dis = p.dist;\n            for(Pair pa : adj.get(node)){\n                if((dis + pa.dist) < dist[pa.node]){\n                    ways[pa.node] = ways[node];\n                    dist[pa.node] = dis + pa.dist;\n                    pq.add(new Pair(pa.node , dist[pa.node]));\n                }\n                else if((dis + pa.dist) == dist[pa.node]){\n                    ways[pa.node] += ways[node];\n                    ways[pa.node] = ways[pa.node] % mod;\n                }\n            }\n        }\n        return (int)ways[n - 1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPaths(int n, vector<vector<int>>& roads) {\n        int mod = 1e9+7;\n        vector<vector<pair<int, int>>> graph(n);\n        for(auto &road: roads) {\n            graph[road[0]].push_back({road[1], road[2]});\n            graph[road[1]].push_back({road[0], road[2]});\n        }\n        \n        vector<long long> distance(n, LONG_MAX);\n        vector<int> path(n, 0);\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, 0});\n        distance[0] = 0;\n        path[0] = 1;\n        \n        while(!pq.empty()) {\n            pair<long long, int> t = pq.top();\n            pq.pop();\n            \n            for(auto &nbr: graph[t.second]) {\n                long long vert = nbr.first;\n                long long edge = nbr.second;\n                \n                if(distance[vert] > distance[t.second] + edge) {\n                    distance[vert] = distance[t.second] + edge;\n                    pq.push({distance[vert], vert});\n                    path[vert] = path[t.second] %mod;\n                }\n                else if(distance[vert] == t.first + edge) {\n                    path[vert] += path[t.second];\n                    path[vert] %= mod;\n                }\n            }\n        }\n        \n        return path[n-1];\n    }\n};"
    },
    {
        "title": "Create Binary Tree From Descriptions",
        "algo_input": "You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,\n\n\n\tIf isLefti == 1, then childi is the left child of parenti.\n\tIf isLefti == 0, then childi is the right child of parenti.\n\n\nConstruct the binary tree described by descriptions and return its root.\n\nThe test cases will be generated such that the binary tree is valid.\n\n&nbsp;\nExample 1:\n\nInput: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput: [50,20,80,15,17,19]\nExplanation: The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\nExample 2:\n\nInput: descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput: [1,2,null,null,3,4]\nExplanation: The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= descriptions.length &lt;= 104\n\tdescriptions[i].length == 3\n\t1 &lt;= parenti, childi &lt;= 105\n\t0 &lt;= isLefti &lt;= 1\n\tThe binary tree described by descriptions is valid.\n\n",
        "solution_py": "class Solution:\n    def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n        hashmap = {}\n        nodes = set()\n        children = set()\n        for parent,child,isLeft in descriptions:\n            nodes.add(parent)\n            nodes.add(child)\n            children.add(child)\n            if parent not in hashmap:\n                hashmap[parent] = TreeNode(parent)\n            if child not in hashmap:\n                hashmap[child] = TreeNode(child)\n            if isLeft:\n                hashmap[parent].left = hashmap[child]\n            if not isLeft:\n                hashmap[parent].right = hashmap[child]\n        \n        for node in nodes:\n            if node not in children:\n                return hashmap[node]",
        "solution_js": "var createBinaryTree = function(descriptions) {\n  let nodes = new Map(), children = new Set();\n  for (let [parent, child, isLeft] of descriptions) {\n    let parentNode = nodes.get(parent) || new TreeNode(parent);\n    if (!nodes.has(parent)) nodes.set(parent, parentNode);\n\n    let childNode = nodes.get(child) || new TreeNode(child);\n    if (!nodes.has(child)) nodes.set(child, childNode);\n\n    if (isLeft) parentNode.left = childNode;\n    else parentNode.right = childNode;\n\n    children.add(child);\n  }\n\n  for (let [parent, child, isLeft] of descriptions) {\n    // a node with no parent is the root\n    if (!children.has(parent)) return nodes.get(parent);\n  }\n};",
        "solution_java": "class Solution {\n    public TreeNode createBinaryTree(int[][] descriptions) {\n        HashMap<Integer,TreeNode> map=new HashMap<>();\n        HashSet<Integer> children=new HashSet<>();\n        for(int[] info:descriptions)\n        {\n            int parent=info[0],child=info[1];\n            boolean isLeft=info[2]==1?true:false;\n            TreeNode parentNode=null;\n            TreeNode childNode=null;\n            if(map.containsKey(parent))\n                parentNode=map.get(parent);\n            else\n                parentNode=new TreeNode(parent);\n            if(map.containsKey(child))\n                childNode=map.get(child);\n            else\n                childNode=new TreeNode(child);\n            if(isLeft)\n                parentNode.left=childNode;\n            else\n                parentNode.right=childNode;\n            map.put(parent,parentNode);\n            map.put(child,childNode);\n            children.add(child);\n            \n        }\n        TreeNode root=null;\n        for(int info[]:descriptions)\n        {\n            if(!children.contains(info[0]))\n            {\n                root=map.get(info[0]);\n                break;\n            }\n        }\n        return root;\n    }\n    \n    \n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* createBinaryTree(vector<vector<int>>& descriptions){\n        unordered_map<int, TreeNode*> getNode; //to check if node alredy exist\n        unordered_map<int, bool> isChild; //to check if node has parent or not\n        for(auto &v: descriptions){\n            if(getNode.count(v[0])==0){\n                TreeNode* par = new TreeNode(v[0]);\n                getNode[v[0]] = par;\n            }\n            if(getNode.count(v[1])==0){\n                TreeNode* child = new TreeNode(v[1]);\n                getNode[v[1]] = child;\n            }\n            if(v[2]==1) getNode[v[0]]->left = getNode[v[1]]; //left-child\n            else getNode[v[0]]->right = getNode[v[1]]; //right-child\n            isChild[v[1]] = true;\n        }\n        TreeNode* ans = NULL;\n        for(auto &v: descriptions){\n            if(isChild[v[0]] != true){ //if node has no parent then this is root node\n                ans = getNode[v[0]];\n                break;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "People Whose List of Favorite Companies Is Not a Subset of Another List",
        "algo_input": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).\n\nReturn the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.\n\n&nbsp;\nExample 1:\n\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput: [0,1,4] \nExplanation: \nPerson with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\n\n\nExample 2:\n\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput: [0,1] \nExplanation: In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].\n\n\nExample 3:\n\nInput: favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput: [0,1,2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= favoriteCompanies.length &lt;= 100\n\t1 &lt;= favoriteCompanies[i].length &lt;= 500\n\t1 &lt;= favoriteCompanies[i][j].length &lt;= 20\n\tAll strings in favoriteCompanies[i] are distinct.\n\tAll lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].\n\tAll strings consist of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n        \n        F = favoriteCompanies\n        ans = [] \n        \n        seen = set() \n        \n        for i in range(len(F)):\n            for j in range(i+1,len(F)):\n                st1 = set(F[i])\n                st2 = set(F[j])\n                if st1.intersection(st2) == st1: seen.add(i)\n                if st2.intersection(st1) == st2: seen.add(j) \n\n        ans = []\n        for i in range(len(F)):\n            if i in seen: continue \n            ans.append(i) \n            \n        return ans",
        "solution_js": "var peopleIndexes = function(favoriteCompanies) {\n    let arr = favoriteCompanies\n    let len = arr.length\n    let ret = []\n    for(let i = 0; i < len; i++) {\n        let item1 = arr[i]\n        let isSubset = false\n        for(let j = 0; j < len; j++) {\n            if(i === j) continue\n            let item2 = arr[j]\n            let s = new Set(item2)\n            if(item1.every(a => s.has(a))) {\n                isSubset = true\n                break\n            }\n        }\n        if(!isSubset) ret.push(i)\n    }\n    return ret\n};",
        "solution_java": "class Solution {\n    public List<Integer> peopleIndexes(List<List<String>> favoriteCompanies) {\n        Set<String>[] fav = new Set[favoriteCompanies.size()];\n        Set<Integer> set = new HashSet<>();\n        for (int i = 0; i < favoriteCompanies.size(); i++) {\n            set.add(i);\n            fav[i] = new HashSet<>(favoriteCompanies.get(i));\n        }\n        for (int i = 1; i < favoriteCompanies.size(); i++) {\n            if (!set.contains(i)) continue;\n            for (int j = 0; j < i; j++) {\n                if (!set.contains(j)) continue;\n                if (isSubSet(fav[j], fav[i])) set.remove(j);\n                if (isSubSet(fav[i], fav[j])) set.remove(i);\n            }\n        }\n        List<Integer> ans = new ArrayList<>(set);\n        Collections.sort(ans);\n        return ans;\n    }\n\n    private boolean isSubSet(Set<String> child, Set<String> parent) {\n        if (child.size() > parent.size()) return false;\n        return parent.containsAll(child);\n    }\n}",
        "solution_c": "/*\n * author: deytulsi18\n * problem: https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/\n * time complexity: O(n*n*m)\n * auxiliary space: O(1)\n * language: cpp\n */\nclass Solution {\npublic:\n    bool isSubset(vector<string> &b, vector<string> &a)\n    {\n       return (includes(a.begin(), a.end(),\n                  b.begin(), b.end()));\n    }\n    vector<int> peopleIndexes(vector<vector<string>>& favoriteCompanies) {\n\n        int n = favoriteCompanies.size();\n        vector<int> res;\n\n        for (auto &i : favoriteCompanies)\n        sort(begin(i), end(i));\n\n        for (int i = 0; i < n; i++)\n        {\n            bool isValid = true;\n\n            for (int j = 0; j < n; j++)\n                if (i != j)\n                    if (isSubset(favoriteCompanies[i], favoriteCompanies[j]))\n                    {\n                        isValid = false;\n                        break;\n                    }\n\n            if (isValid)\n                res.emplace_back(i);\n        }\n\n        return res;\n    }\n};;"
    },
    {
        "title": "Maximum Number of Balloons",
        "algo_input": "Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible.\n\nYou can use each character in text at most once. Return the maximum number of instances that can be formed.\n\n&nbsp;\nExample 1:\n\n\n\nInput: text = \"nlaebolko\"\nOutput: 1\n\n\nExample 2:\n\n\n\nInput: text = \"loonbalxballpoon\"\nOutput: 2\n\n\nExample 3:\n\nInput: text = \"leetcode\"\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 104\n\ttext consists of lower case English letters only.\n\n",
        "solution_py": "class Solution:\n    def maxNumberOfBalloons(self, text: str) -> int:\n        freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}\n        \n        for char in text:\n            if not char in freq:\n                continue\n                \n            step = 0.5 if char == 'l' or char == 'o' else 1\n            \n            freq[char] += step\n        \n        result = min(freq.values())\n        \n        return floor(result)",
        "solution_js": "/**\n * @param {string} text\n * @return {number}\n */\nvar maxNumberOfBalloons = function(text) {\n//    1. create hashmap with \"balloon\" letters\n//    2. keep track of how many letters in text belong to \"balloon\"\n//     3. account for fact that we need two \"l\" and \"o\" per \"balloon\" instance\n//    4. then select all map values and get the minimum - this will be the max value\n    \n    const balloonMap = {\n        \"b\": 0,\n        \"a\": 0,\n        \"l\": 0,\n        \"o\": 0,\n        \"n\": 0\n    }\n    \n    for (const char of text) {\n        if (balloonMap[char] !== undefined) {\n            balloonMap[char] += 1\n        }\n    }\n    \n    const letterFreq = []\n    for (const key in balloonMap) {\n        if ([\"l\", \"o\"].includes(key)) {\n            letterFreq.push(Math.floor(balloonMap[key]/2))\n        } else {\n            letterFreq.push(balloonMap[key])\n        }\n    }\n    return Math.min(...letterFreq)\n};",
        "solution_java": "class Solution {\n\n    public int maxNumberOfBalloons(String text) {\n        return maxNumberOfWords(text, \"balloon\");\n    }\n\n    private int maxNumberOfWords(String text, String word) {\n        final int[] tFrequencies = new int[26];\n        for (int i = 0; i < text.length(); ++i) {\n            tFrequencies[text.charAt(i) - 'a']++;\n        }\n        final int[] wFrequencies = new int[26];\n        for (int i = 0; i < word.length(); ++i) {\n            wFrequencies[word.charAt(i) - 'a']++;\n        }\n        int min = Integer.MAX_VALUE;\n        for (int i = 0; i < 26; ++i) {\n            if (wFrequencies[i] > 0) {\n                final int count = (tFrequencies[i] / wFrequencies[i]);\n                if (count < min) {\n                    min = count;\n                }\n            }\n        }\n        return min;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int maxNumberOfBalloons(string text) {\n        map<char,int>m;\n        for(int i=0;i<text.length();i++)\n        {\n            m[text[i]]++;\n        }\n        string s=\"balloon\";\n        int flag=1;\n        int c=0;\n        while(1)\n        {\n            for(int i=0;i<s.length();i++)\n            {\n                m[s[i]]--;\n                if(m[s[i]]==-1)\n                {\n                    flag=0;\n                }\n            }\n            if(flag==0)\n                break;\n            c++;\n        }\n        return c;\n    }\n};"
    },
    {
        "title": "Battleships in a Board",
        "algo_input": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.\n\nBattleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]\nOutput: 2\n\n\nExample 2:\n\nInput: board = [[\".\"]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m, n &lt;= 200\n\tboard[i][j] is either '.' or 'X'.\n\n\n&nbsp;\nFollow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?\n",
        "solution_py": "class Solution:\n    def countBattleships(self, board: List[List[str]]) -> int:\n        \n        m = len(board)\n        n = len(board[0])\n        res = 0\n        \n        pole = [ [True for i in range(n)] for j in range(m) ]\n        \n        for i in range(m):\n            for j in range(n):\n                if board[i][j] == 'X' and pole[i][j]:\n                    for z in range(i+1, m):\n                        if board[z][j] == 'X':\n                            pole[z][j] = False\n                        else:\n                            break\n                            \n                    for z in range(j+1, n):\n                        if board[i][z] == 'X':\n                            pole[i][z] = False\n                        else:\n                            break\n                    \n                    \n                    res += 1\n                \n\n        \n        return res",
        "solution_js": "var countBattleships = function(board) {\n    \n    let count = 0;\n    \n    for(let rowIndex = 0; rowIndex < board.length; rowIndex++){\n        for(let columnIndex = 0; columnIndex < board[rowIndex].length; columnIndex++){\n            const isTopEmpty = rowIndex === 0 || board[rowIndex - 1][columnIndex] !== \"X\";\n            const isLeftEmpty = columnIndex === 0 || board[rowIndex][columnIndex - 1] !== \"X\";\n            const isBattleShip = board[rowIndex][columnIndex] === \"X\" && isTopEmpty && isLeftEmpty;\n            if(isBattleShip){\n                count++;\n            }\n        }\n    }\n    \n    return count;\n    \n};",
        "solution_java": "class Solution {\n    public int countBattleships(char[][] board) {\n            int result = 0;\n            for(int i = 0;i<board.length;i++)\n            {\n                for(int j = 0;j<board[i].length;j++)\n                {\n                    if(board[i][j] == 'X')\n                    {\n                        remover(i, j, board);\n                        result++;\n                    }\n\n                }\n            }\n            return result;\n\n        }\n        public void remover(int i , int j, char[][] board)\n        {\n            if(i<0 || i>= board.length || j<0 || j>=board[0].length || board[i][j] == '.')\n            {\n                return;\n            }\n            board[i][j] = '.';\n            remover(i+1, j, board);\n            remover(i, j+1, board);\n        }\n}",
        "solution_c": "class Solution {\npublic:\n\n    bool isSafe(int i,int j,int r,int c,vector<vector<char>> &arr,vector<vector<bool>> &visited){\n           if(i<0 || i>r || j<0 || j>c){\n             return false;\n         }\n       //  cout<<arr[i][j]<<\" \";\n        if(arr[i][j]!='X'){\n            return false;\n        }\n        if(arr[i][j] == 'X' && visited[i][j] == true){\n            return false;\n        }\n\n        if(arr[i][j] == 'X' && visited[i][j] == false){\n            return true;\n        }\n         return false;\n    \n    }\n\n    void solve(vector<vector<char>> &arr,vector<vector<bool>> &visited,int &r,int &c,int i,int j){\n\n        if((i>r && j>c) && (i<0 && j<0)){\n            return;\n        }\n\n        // down (i+1,j)\n        if(isSafe(i+1,j,r,c,arr,visited)){\n             visited[i+1][j] = true;\n             solve(arr,visited,r,c,i+1,j);\n        }else{\n            // if(arr[i][j] == 'X'){\n            //      visited[i][j] = true;\n            // }\n        }\n        // // right (i,j+1)\n\n        if(isSafe(i,j+1,r,c,arr,visited)){\n             visited[i][j+1] = true;\n             solve(arr,visited,r,c,i,j+1);\n        }else{\n            // if(arr[i][j] == 'X'){\n            //      visited[i][j] = true;\n            // }\n        }\n        // left (i,j-1);\n        if(isSafe(i,j-1,r,c,arr,visited)){\n            visited[i][j-1] = true;\n             solve(arr,visited,r,c,i,j-1);\n        }else{\n            // if(arr[i][j] == 'X'){\n            //      visited[i][j] = true;\n            // }\n        }\n        // up   (i-1,j)\n        if(isSafe(i-1,j,r,c,arr,visited)){\n             visited[i-1][j] = true;\n             solve(arr,visited,r,c,i-1,j);\n        }else{\n            // if(arr[i][j] == 'X'){\n            //      visited[i][j] = true;\n            // }\n        }\n\n    }\n    int countBattleships(vector<vector<char>>& board) {\n        int row = board.size()-1;\n        int col = board[0].size()-1;\n        vector<vector<bool>> isVisited(row+1,vector<bool>(col+1,false));\n        vector<vector<int>> toStart;\n        for(int i=0;i<board.size();i++){\n            for(int j=0;j<board[i].size();j++){\n                if(board[i][j] == 'X'){\n                    vector<int> temp(2);\n                    temp[0] = i;\n                    temp[1] = j;\n                  //  cout<<i<<\" \"<<j<<endl;\n                    toStart.push_back(temp);\n                }\n            }\n        }\n        int ans = 0;\n         for(int i=0;i<toStart.size();i++){\n            if(isVisited[toStart[i][0]][toStart[i][1]]){\n\n            }else{\n            isVisited[toStart[i][0]][toStart[i][1]] = true;\n             solve(board,isVisited,row,col,toStart[i][0],toStart[i][1]);\n             ans++;\n            }\n             \n         }\n\n        //  for(auto cc:isVisited){\n        //      for(auto c:cc){\n        //          cout<<c<<\" \";\n        //      }\n        //      cout<<endl;\n        //  }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Latest Group of Size M",
        "algo_input": "Given an array arr that represents a permutation of numbers from 1 to n.\n\nYou have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.\n\nYou are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.\n\nReturn the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,5,1,2,4], m = 1\nOutput: 4\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.\n\n\nExample 2:\n\nInput: arr = [3,1,5,4,2], m = 2\nOutput: -1\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == arr.length\n\t1 &lt;= m &lt;= n &lt;= 105\n\t1 &lt;= arr[i] &lt;= n\n\tAll integers in arr are distinct.\n\n",
        "solution_py": "class Solution:\n    def findLatestStep(self, arr: List[int], m: int) -> int:\n        n = len(arr)\n        ans = -1\n        if n == m: return m #just in case\n        \n#       make in \"inverted\" array with artificial ends higher then everything between\n\n        sor= [0 for _ in range(n+2)]\n        for i in range(n):\n            sor[(arr[i])] = i+1 \n        sor[0] = sor[n+1] = n+1\n        \n#       scan and see, if ones in the middle of space of length m appear \n#       before ones on its ends,\n#       and find the latest of such spaces to disappear, if exists\n\n        for i in range(1, n-m+2): \n            if all(sor[i-1]>sor[j] and sor[i+m]>sor[j] for j in range(i,i+m)):\n                if min(sor[i-1]-1,sor[i+m]-1)>ans: ans = min(sor[i-1]-1,sor[i+m]-1) \n        return ans",
        "solution_js": "var findLatestStep = function(arr, m) {\n    if (m === arr.length) return arr.length\n    let bits = new Array(arr.length+1).fill(true), pos, flag, i, j\n    for (i = arr.length - 1, bits[0] = false; i >= 0; i--) {\n        pos = arr[i], bits[pos] = false\n        for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos-j]\n        if (flag && !bits[pos-m-1]) return i\n        for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos+j]\n        if (flag && !bits[pos+m+1]) return i\n    }\n    return -1\n};",
        "solution_java": "class Solution {\n    int[] par, size, count, bits;    \n    // par: parent array, tells about whose it the parent of ith element\n    // size: it tells the size of component\n    // count: it tells the count of islands (1111 etc) of size i;\n    // count[3] = 4: ie -> there are 4 islands of size 3\n    \n    public int find(int u) {\n        if (u == par[u]) return u;\n        par[u] = find(par[u]);\n        return par[u];\n    }\n    \n    public void union(int u, int v) {\n        // union is performed over parents of elements not nodes itself\n        int p1 = find(u), p2 = find(v);\n        if (p1 == p2) return;\n        \n        // decrease the count of islands of size p1, p2\n        count[size[p1]]--;\n        count[size[p2]]--;\n        \n        // now merge\n        par[p2] = p1;\n        \n        // adjust sizes\n        size[p1] += size[p2];\n        \n        // adjust the count of islands of new size ie: size of p1\n        count[size[p1]]++;\n    }\n    \n    public int findLatestStep(int[] arr, int m) {\n        int n = arr.length;\n        par = new int[n + 1];\n        size = new int[n + 1];\n        count = new int[n + 1];\n        bits = new int[n + 2];\n        \n        for (int i = 0; i < n; i++) {\n            par[i] = i;\n            size[i] = 1;\n        }\n        \n        int ans = -1;\n        for (int i = 0; i < n; i++) {\n            int idx = arr[i];\n            // set the bit\n            bits[idx] = 1;\n            // increase the count of islands of size 1\n            count[1]++;\n            \n            if (bits[idx - 1] > 0) {\n                union(idx, idx - 1);\n            }   \n            if (bits[idx + 1] > 0) {\n                union(idx, idx + 1);\n            }\n            \n            // check if island of size m exists\n            if (count[m] > 0) {\n                ans = i + 1;\n                // as it is 1 based indexing\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLatestStep(vector<int>& arr, int m) {\n        int n=size(arr),ans=-1;\n        vector<int>cntL(n+2),indL(n+2);\n        for(int i=0;i<n;i++){\n            int li=indL[arr[i]-1],ri=indL[arr[i]+1],nl=li+ri+1;\n            indL[arr[i]]=nl;\n            indL[arr[i]-li]=nl;\n            indL[arr[i]+ri]=nl;\n            cntL[li]--;\n            cntL[ri]--;\n            cntL[nl]++;\n            if(cntL[m]>0)ans=i+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Convert BST to Greater Tree",
        "algo_input": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\n\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\nExample 2:\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-104 &lt;= Node.val &lt;= 104\n\tAll the values in the tree are unique.\n\troot is guaranteed to be a valid binary search tree.\n\n\n&nbsp;\nNote: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n        ans = []\n        def inorder(node):\n            if not node:\n                return node\n            inorder(node.left)\n            ans.append(node.val)\n            inorder(node.right)\n        def dfs(node):\n            if not node:\n                return None\n            idx = ans.index(node.val)\n            node.val = node.val + sum(ans[idx+1:])\n            dfs(node.left)\n            dfs(node.right)\n\n        inorder(root)\n        dfs(root)\n        return root\n        ",
        "solution_js": "var convertBST = function(root) {\n    let sum = 0;\n    const go = (node) => {\n        if (!node) return;\n        go(node.right);\n        sum += node.val;\n        node.val = sum;\n        go(node.left);\n    }\n    go(root);\n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode convertBST(TreeNode root) {\n    if(root!=null) {\n\n\n        List<Integer> nodesValues = new ArrayList<>();\n        helperNodesVales(root, nodesValues);\n        traverseAndAdd(root, nodesValues);\n\n        return root;\n    }\n        return null;\n    }\n\n    private void helperNodesVales(TreeNode root, List<Integer> nodesValues) {\n        if (root != null) {\n            nodesValues.add(root.val);\n        }\n        if (root.right != null) {\n            helperNodesVales(root.right, nodesValues);\n        }\n        if (root.left != null) {\n            helperNodesVales(root.left, nodesValues);\n        }\n        if (root == null) {\n            return;\n        }\n    }\n\n    private void traverseAndAdd(TreeNode root, List<Integer> nodesValues) {\n        if (root != null) {\n            int rootVal = root.val;\n            for (int i = 0; i < nodesValues.size(); i++) {\n                if (nodesValues.get(i) > rootVal)\n                    root.val += nodesValues.get(i);\n            }\n        }\n        if (root.right != null) {\n            traverseAndAdd(root.right, nodesValues);\n        }\n        if (root.left != null) {\n            traverseAndAdd(root.left, nodesValues);\n        }\n        if (root == null) {\n            return;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int val = 0;\n    TreeNode* convertBST(TreeNode* root) {\n\n        if(root)\n        {\n            convertBST(root->right); // traverse right sub-tree\n            val += root->val; // add val\n            root->val = val; // update val\n            convertBST(root->left); // traverse left sub-tree\n        }\n        \n        return root;\n    }\n};"
    },
    {
        "title": "Maximum Score From Removing Stones",
        "algo_input": "You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).\n\nGiven three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.\n\n&nbsp;\nExample 1:\n\nInput: a = 2, b = 4, c = 6\nOutput: 6\nExplanation: The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.\n\n\nExample 2:\n\nInput: a = 4, b = 4, c = 6\nOutput: 7\nExplanation: The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.\n\n\nExample 3:\n\nInput: a = 1, b = 8, c = 8\nOutput: 8\nExplanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a, b, c &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maximumScore(self, a: int, b: int, c: int) -> int:\n        a, b, c = sorted([a, b, c], reverse=True)\n        ans = 0\n        while a > 0 and b > 0:\n            a -= 1\n            b -= 1\n            ans += 1\n            a, b, c = sorted([a, b, c], reverse=True)\n        return ans",
        "solution_js": "/**\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @return {number}\n */\nvar maximumScore = function(a, b, c) {\n    let resultArray = [];\n    resultArray.push(a);\n    resultArray.push(b);\n    resultArray.push(c);\n    resultArray.sort((a,b)=>a-b);\n    let counter=0;\n    while(resultArray[0]>0||resultArray[1]>0||resultArray[2]>0){\n        if(resultArray[0]===0&&resultArray[1]===0){\n            break;\n        }\n        resultArray[1]--;\n        resultArray[2]--;\n        counter++\n        if(resultArray[1]<resultArray[0]){\n            exchange(resultArray,1,0);\n        }\n        if(resultArray[2]<resultArray[0]){\n            exchange(resultArray,2,0);\n        }\n    }\n    if(resultArray[0]+resultArray[1]+resultArray[2]===0) return counter;\n    if(resultArray[0]<0||resultArray[1]<0||resultArray[2]<0) counter--;\n    return counter;\n\n    function exchange(array, indexa,indexb){\n        let temp = array[indexa];\n        array[indexa] = array[indexb];\n        array[indexb] = temp;\n    }\n\n};",
        "solution_java": "class Solution {\n    public int maximumScore(int a, int b, int c) {\n        // Make sure a <= b <= c\n        if (a>b) return maximumScore(b,a,c);\n        if (b>c) return maximumScore(a,c,b);\n        \n        // if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c\n        if (a+b<=c) return a+b;\n        \n        // if sum of smallest numbers is greater than c, then we can (a+b)/2 pairs after making c empty\n        return c+(a+b-c)/2;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumScore(int a, int b, int c) {\n        return min((a + b + c) / 2, a + b + c - max({a, b, c}));\n    }\n};"
    },
    {
        "title": "Process Tasks Using Servers",
        "algo_input": "You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds.\n\nTasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.\n\nAt second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.\n\nIf there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.\n\nA server that is assigned task j at second t will be free again at second t + tasks[j].\n\nBuild an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to.\n\nReturn the array ans​​​​.\n\n&nbsp;\nExample 1:\n\nInput: servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput: [2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n\nExample 2:\n\nInput: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput: [1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.\n\n\n&nbsp;\nConstraints:\n\n\n\tservers.length == n\n\ttasks.length == m\n\t1 &lt;= n, m &lt;= 2 * 105\n\t1 &lt;= servers[i], tasks[j] &lt;= 2 * 105\n\n",
        "solution_py": "class Solution:\n    def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n        servers_available = [(w, i) for i,w in enumerate(servers)]\n        heapify(servers_available)\n        tasks_in_progress = []\n        res = []\n        time = 0\n        for j,task in enumerate(tasks):\n            time = max(time, j)\n            if not servers_available:\n                time = tasks_in_progress[0][0]\n            while tasks_in_progress and tasks_in_progress[0][0] <= time:\n                heappush(servers_available, heappop(tasks_in_progress)[1])\n            res.append(servers_available[0][1])\n            heappush(tasks_in_progress, (time + task, heappop(servers_available)))\n        return res",
        "solution_js": " var assignTasks = function(servers, tasks) {\n    // create a heap to manage free servers.\n    // free servers will need to be prioritized by weight and index\n    const freeServers = new Heap((serverA, serverB) => (\n        serverA.weight - serverB.weight || serverA.index - serverB.index\n    ));\n\n    // create a heap to manage used servers.\n    // used servers will need to be prioritized by availableTime, weight and index\n    const usedServers = new Heap((serverA, serverB) => (\n        serverA.availableTime - serverB.availableTime || \n        serverA.weight - serverB.weight || \n        serverA.index - serverB.index\n    ));\n    \n    // add all the servers into the free servers heap with the time it is available\n    // being 0\n    for (let i = 0; i < servers.length; i++) {\n        freeServers.push({ weight: servers[i], index: i, availableTime: 0 })\n    }\n    \n    const result = [];\n    for (let i = 0; i < tasks.length; i++) {\n        // find all the servers that are available and add them to the\n        // free servers heap\n        while (usedServers.size() && usedServers.peak().availableTime <= i) {\n            freeServers.push(usedServers.pop());\n        }\n        // get the free server with the lowest weight or lower index\n        // or the usedServer with the lowest start time.\n        const server = freeServers.pop() || usedServers.pop();\n        result.push(server.index);\n        const availableTime = Math.max(i, server.availableTime);\n        server.availableTime = availableTime + tasks[i];\n        usedServers.push(server);\n    }\n    return result;\n};\n\nclass Heap {\n\n    /**\n     * Create a Heap\n     * @param {function} compareFunction - compares child and parent element\n     * to see if they should swap.  If return value is less than 0 it will\n     * swap to prioritize the child.\n     */\n    constructor(compareFunction) {\n        this.store = [];\n        this.compareFunction = compareFunction;\n    }\n    \n    peak() {\n        return this.store[0];\n    }\n    \n    size() {\n        return this.store.length;\n    }\n    \n    pop() {\n        if (this.size() < 2) {\n            return this.store.pop();\n        }\n        const result = this.store[0];\n        this.store[0] = this.store.pop();\n        this.heapifyDown(0);\n        return result;\n    }\n    \n    push(val) {\n        this.store.push(val);\n        this.heapifyUp(this.size() - 1);\n    }\n        \n    heapifyUp(child) {\n        while (child) {\n            const parent = Math.floor((child - 1) / 2);\n            \n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                child = parent;\n            } else {\n                return child;\n            }\n        }\n    }\n    \n    heapifyDown(parent) {\n        while (true) {\n            let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n            if (this.shouldSwap(child2, child)) {\n                child = child2;\n            }\n            \n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                parent = child;\n            } else {\n                return parent;\n            }\n        }\n    }\n    \n    shouldSwap(child, parent) {\n        return child && this.compareFunction(this.store[child], this.store[parent]) < 0;\n    }\n}",
        "solution_java": "class Solution {\n    public int[] assignTasks(int[] servers, int[] tasks) {\n\n        PriorityQueue<int[]> availableServer = new PriorityQueue<int[]>((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0])));\n        for(int i = 0; i < servers.length; i++){\n            availableServer.add(new int[]{i, servers[i]});\n        }\n\n        //int[[] arr,\n        //arr[0] - server index\n        //arr[1] - server weight\n        //arr[2] - free time\n        PriorityQueue<int[]> processingServer = new PriorityQueue<int[]>(\n                (a, b) ->\n\n                (\n                    a[2] != b[2] ? a[2] - b[2] : // try to sort increasing order of free time\n                    a[1] != b[1] ? a[1] - b[1] : // try to sort increasing order of server weight\n                    a[0] - b[0] // sort increasing order of server index\n                )\n        );\n\n        int[] result = new int[tasks.length];\n\n        for(int i = 0; i < tasks.length; i++){\n\n            while(!processingServer.isEmpty() && processingServer.peek()[2] <= i){\n                int serverIndex = processingServer.remove()[0];\n                availableServer.add(new int[]{serverIndex, servers[serverIndex]});\n            }\n\n            int currentTaskTimeRequired = tasks[i];\n\n            int[] server;\n\n            //when current task will free the server done\n            int freeTime = currentTaskTimeRequired;\n\n            if(!availableServer.isEmpty()){\n                server = availableServer.remove();\n                freeTime += i;\n            }else{\n                server = processingServer.remove();\n                //append previous time\n                freeTime += server[2];\n            }\n\n            int serverIndex = server[0];\n            processingServer.add(new int[]{serverIndex, servers[serverIndex] ,freeTime});\n\n            //assign this server to current task\n            result[i] = serverIndex;\n        }\n\n        return result;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {\n        priority_queue<vector<long long>, vector<vector<long long>>, greater<vector<long long>>> free, busy; \n        for (int i = 0; i < servers.size(); ++i) {\n            free.push(vector<long long>{servers[i], i});\n        }\n        vector<int> ans;\n        long long time = 0;\n        queue<int> task_queue;\n        while (ans.size() < tasks.size()) { \n            // Bring all eligible tasks to task_queue.\n            for (int i = ans.size() + task_queue.size(); i <= time && i < tasks.size(); ++i) {\n                task_queue.push(tasks[i]);\n            }\n            // Bring all eligible servers to free queue.\n            while (!busy.empty() && busy.top()[0] <= time) {\n                auto& top = busy.top();\n                free.push(vector<long long>{top[1], top[2]});\n                busy.pop();\n            }\n            // If we have no servers, we cannot match until one of the servers becomes free.\n            if (free.empty()) {\n                time = busy.top()[0];\n                continue;\n            }\n            while(!task_queue.empty() && !free.empty()) {\n                // Now we just take the first task and first server as per defined priority and match the two.\n                int task = task_queue.front(); \n                auto& top = free.top();\n                ans.push_back(top[1]);\n                busy.push(vector<long long>{time + task, top[0], top[1]});\n                task_queue.pop();\n                free.pop();\n            }\n            // Only increment time to receive new tasks once we have processed all tasks so far.\n            if (task_queue.empty()) time++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Queries on a Permutation With Key",
        "algo_input": "Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:\n\n\n\tIn the beginning, you have the permutation P=[1,2,3,...,m].\n\tFor the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P.&nbsp;Notice that the position of queries[i] in P is the result for queries[i].\n\n\nReturn an array containing the result for the given queries.\n\n&nbsp;\nExample 1:\n\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].  \n\n\nExample 2:\n\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\n\n\nExample 3:\n\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m &lt;= 10^3\n\t1 &lt;= queries.length &lt;= m\n\t1 &lt;= queries[i] &lt;= m\n",
        "solution_py": "class Solution:\n    def processQueries(self, queries: List[int], m: int) -> List[int]:\n        perm=[i for i in range(1,m+1)]\n        res=[]\n        for i in queries:\n            ind=perm.index(i)\n            res.append(ind)\n            perm=[perm.pop(ind)]+perm\n        return res",
        "solution_js": "var processQueries = function(queries, m) {\n    let result = [];\n    let permutation = [];\n    for(let i=0; i<m; i++){\n        permutation.push(i+1);\n    }\n    \n    for(let i=0; i<queries.length; i++){\n        let index = permutation.indexOf(queries[i]);\n        result.push(index);\n        permutation.splice(index,1);\n        permutation.unshift(queries[i]);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] processQueries(int[] queries, int m) {\n        int[] results = new int[queries.length];\n        ArrayList<Integer> permutations = new ArrayList<Integer>();\n\n        // Filling the permuations array with numbers.\n        for (int i = 0; i < m; i++)\n            permutations.add(i+1);\n\n        // Looping on the queries & checking their index in the permuations\n        for (int i = 0; i < queries.length; i++) {\n            int query = queries[i];\n            for (int j = 0; j < permutations.size(); j++)\n                if (permutations.get(j) == query) {\n                    results[i] = j;\n                    int temp = permutations.get(j);\n                    permutations.remove(j);\n                    permutations.add(0, temp);\n                    break;\n                }\n        }\n\n        return results;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> processQueries(vector<int>& queries, int m) {\n        \n        vector<int> p;\n\n        for(int i=0; i<m; i++) p.push_back(m-i);\n        \n        for(int i=0; i<queries.size(); i++)\n        {\n            auto it = find(p.begin(), p.end(), queries[i]);\n            int j = it - p.begin();\n            int tmp = p[j];\n            p.erase(it);\n            p.push_back(tmp);\n            queries[i] = m-j-1;\n        }\n        return queries;\n    }\n};"
    },
    {
        "title": "Non-decreasing Array",
        "algo_input": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.\n\nWe define an array is non-decreasing if nums[i] &lt;= nums[i + 1] holds for every i (0-based) such that (0 &lt;= i &lt;= n - 2).\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,2,3]\nOutput: true\nExplanation: You could modify the first 4 to 1 to get a non-decreasing array.\n\n\nExample 2:\n\nInput: nums = [4,2,1]\nOutput: false\nExplanation: You cannot get a non-decreasing array by modifying at most one element.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 104\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def checkPossibility(self, nums: List[int]) -> bool:\n        unstable=0\n        for i in range(1,len(nums)):\n            if nums[i]<nums[i-1]:\n                unstable+=1\n                if i<2 or nums[i-2]<=nums[i]:\n                    nums[i-1]=nums[i]\n                else:\n                    nums[i]=nums[i-1]\n                \n                if unstable>1:\n                    return False\n        return True",
        "solution_js": "var checkPossibility = function(nums) {\n    let changed = false\n    for(let i=nums.length-1; i>0; i--) {\n        if(nums[i-1] > nums[i]) {\n            if(changed) return false;\n            if(i === nums.length-1 || nums[i-1] < nums[i+1]) nums[i] = nums[i-1]\n            else nums[i-1] = nums[i];\n            changed = true\n        }\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean checkPossibility(int[] nums) {\n        int modified = 0, prev = nums[0], index = 0;\n        for (; index < nums.length; ++index) {\n            if (nums[index] < prev) {\n                if (++modified > 1) return false;\n                if (index - 2 >= 0 && nums[index - 2] > nums[index]) continue;\n            }\n            prev = nums[index];\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\nbool checkPossibility(vector<int>& nums) {\n    if(nums.size()<=2)\n        return true;\n    //creating a diff array(size=n-1) to store differences bw 2 consecutive ele.\n    vector<int>diff(nums.size()-1);\n    int neg=0;\n    \n    for(int i=0;i<nums.size()-1;i++)\n    {\n        diff[i]=nums[i+1]-nums[i];\n        diff[i]<0?neg++:0; //no of negative differences\n    }\n    \n    if(neg>1)\n        return false;\n\n    \n    for(int i=0;i<diff.size();i++)\n    {\n        if(diff[i]<0 and i!=diff.size()-1)\n        {\n            if(i==0)\n                // if(diff[i+1]>=0)\n                continue; //if the first diff is neg, the next is obviosly>=0 as neg<=1, and this mountain can be resolved;\n                // else\n                    // return false;\n            \n            if((nums[i-1]<=nums[i+1]) || (diff[i+1])>=abs(diff[i]))\n                continue;  //the major mountain cases, lemme know below if want explaination of these\n            else \n                return false;\n        }\n    }   \n    return true;\n}"
    },
    {
        "title": "Minimum Number of Refueling Stops",
        "algo_input": "A car travels from a starting position to a destination which is target miles east of the starting position.\n\nThere are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.\n\nThe car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\n\nReturn the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.\n\nNote that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n\n&nbsp;\nExample 1:\n\nInput: target = 1, startFuel = 1, stations = []\nOutput: 0\nExplanation: We can reach the target without refueling.\n\n\nExample 2:\n\nInput: target = 100, startFuel = 1, stations = [[10,100]]\nOutput: -1\nExplanation: We can not reach the target (or even the first gas station).\n\n\nExample 3:\n\nInput: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput: 2\nExplanation: We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target, startFuel &lt;= 109\n\t0 &lt;= stations.length &lt;= 500\n\t0 &lt;= positioni &lt;= positioni+1 &lt; target\n\t1 &lt;= fueli &lt; 109\n\n",
        "solution_py": "class Solution:\n    def minRefuelStops(self, t, F, S):\n        S.append([t, 0])\n        heap, ans = [], 0\n        for p,f in S:\n            while heap and p > F:\n                F -= heapq.heappop(heap)\n                ans += 1\n            if p > F: return -1\n            heapq.heappush(heap, -f)\n        return ans",
        "solution_js": "var minRefuelStops = function(target, startFuel, stations) {\n    let pq = new MaxPriorityQueue({compare: (a, b) => b[1] - a[1]});\n    let idx = 0, reachablePosition = startFuel, refuels = 0;\n    // reachablePosition is the farthest position reachable so far\n    \n    while (reachablePosition < target) {\n        // While reachablePosition is >= to the current station's position, add the current station to the heap\n        // These stations are all reachable based on the fuel available\n        // Once reachablePosition is less than a station's position, the while loop ends\n        while (idx < stations.length && reachablePosition >= stations[idx][0]) {\n            pq.enqueue([stations[idx][0], stations[idx][1]]);\n            idx++;\n        }\n        // Next, add fuel from the heap in a greedy manner: the station with the most fuel gets added first\n        // All stations in the heap are reachable, so the position is irrelevant \n        if (pq.size()) {\n            let [pos, fuel] = pq.dequeue();\n            reachablePosition += fuel;\n            refuels++;\n        } else break;\n    }\n    \n    return reachablePosition >= target ? refuels : -1;\n};",
        "solution_java": "class Solution {\n    public int minRefuelStops(int target, int startFuel, int[][] stations) {\n        if(startFuel >= target) return 0;\n        int[][] dp = new int[stations.length + 1][stations.length + 1];\n        for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel;\n        for (int j = 1; j < dp.length; j++) {\n            for (int i = j; i < dp.length; i++) {\n                dp[i][j] = Math.max(dp[i-1][j], stations[i-1][0] > dp[i-1][j-1] ?\n                        Integer.MIN_VALUE : dp[i-1][j-1] + stations[i-1][1]);\n                if(dp[i][j] >= target) return j;\n            }\n        }\n        return -1;\n    }\n}",
        "solution_c": "/*\n\nThe approach here used is - first cosider the stations which are possible at a particular time and then take the one with maximum fuel that can be filled this ensure that with only one fill up the vehicle will move to furthest distance.\n\nNow there might be case where if we don't fill up from multiple stations ata paritcular time, then it will not be possible to reach end as there might not be any stations at the ending side of the target. \n\nTo handle above case, when such situation arise then we need to take the next max fuel refill that is pissible from the already seen stations.\nLike this way keep on taking fuels from stations in decreasing manner.\n\nIf at any point of time the queue is empty then, it means we do not have sufficent fuel to reach target.\n\n=> This logic can be implemented by simply using a priority queue where the max fuel station is at top of the queue.\n\n\n*/\n\nclass Solution {\npublic:\n    int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {\n        auto comp = [](vector<int> a, vector<int> b){ return a[1] < b[1]; };\n        priority_queue<vector<int>, vector<vector<int>>, decltype(comp)> pq(comp);\n        int i = 0, distance = startFuel, refillCount = 0;\n        while(distance < target ){\n            while(i < stations.size() && distance >= stations[i][0]){\n                pq.push(stations[i++]);\n            }\n            if(pq.empty()) return -1;\n            distance += pq.top()[1];\n            refillCount++;\n            pq.pop();\n        }\n        return refillCount;\n    }\n};"
    },
    {
        "title": "Distribute Repeating Integers",
        "algo_input": "You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:\n\n\n\tThe ith customer gets exactly quantity[i] integers,\n\tThe integers the ith customer gets are all equal, and\n\tEvery customer is satisfied.\n\n\nReturn true if it is possible to distribute nums according to the above conditions.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4], quantity = [2]\nOutput: false\nExplanation: The 0th customer cannot be given two different integers.\n\n\nExample 2:\n\nInput: nums = [1,2,3,3], quantity = [2]\nOutput: true\nExplanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n\n\nExample 3:\n\nInput: nums = [1,1,2,2], quantity = [2,2]\nOutput: true\nExplanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= nums[i] &lt;= 1000\n\tm == quantity.length\n\t1 &lt;= m &lt;= 10\n\t1 &lt;= quantity[i] &lt;= 105\n\tThere are at most 50 unique values in nums.\n\n",
        "solution_py": "class Solution:\n    def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n        freq = {}\n        for x in nums: freq[x] = 1 + freq.get(x, 0)\n        \n        vals = sorted(freq.values(), reverse=True)\n        quantity.sort(reverse=True) # pruning - large values first  \n        \n        def fn(i): \n            \"\"\"Return True if possible to distribute quantity[i:] to remaining.\"\"\"\n            if i == len(quantity): return True \n            seen = set()\n            for k in range(len(vals)): \n                if vals[k] >= quantity[i] and vals[k] not in seen: \n                    seen.add(vals[k]) # pruning - unqiue values \n                    vals[k] -= quantity[i]\n                    if fn(i+1): return True \n                    vals[k] += quantity[i] # backtracking\n                    \n        return fn(0)",
        "solution_js": "var canDistribute = function(nums, quantity) {\n    quantity.sort((a,b)=>b-a)\n    let freq={},flag=false\n    for(let num of nums)\n        freq[num]=(freq[num]||0) +1\n    let set=Object.keys(freq),n=set.length,k=quantity.length\n    let rec=(prefix)=>{\n        if(prefix.length==k || flag==true)  \n            return flag=true\n        for(let i=0;i<n;i++){\n            freq[set[i]]-=quantity[prefix.length]\n\t\t\tprefix.push(set[i])\n            if( freq[set[i]]>=0)\n                rec(prefix)\n\t\t\tprefix.pop()\n            freq[set[i]]+=quantity[prefix.length]\n        }\n    }\n    rec([])\n    return flag\n};",
        "solution_java": "class Solution {\n    public boolean canDistribute(int[] nums, int[] quantity) {\n        \n        // Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}\n        Map<Integer, Integer> freq = new HashMap<>();\n        for (int num : nums)\n            freq.put(num, freq.getOrDefault(num, 0)+1);\n        \n        // Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]\n        int[] dist = new int[freq.size()];\n        int idx = 0;\n        for (int f : freq.values())\n            dist[idx++] = f;\n        \n\t\t// Fullfill the quantities from the biggest quantity to the smallest.\n        // If the bigger quantity can't be filled, the program will stop as early as possible.\n        Arrays.sort(quantity);\n        return rec(dist, quantity, quantity.length-1);\n    }\n    \n    // try to fullfill the j-th order quantity\n    private boolean rec(int[] dist, int[] quantity, int j) {\n        \n        // stop condition. We've fulfilled all the order quantities.\n        if (j == -1)\n            return true;\n        \n        Set<Integer> used = new HashSet<>();\n        for (int i = 0 ; i < dist.length ; ++i) {\n\t\t\n\t\t\t// Use a set to make sure that \n\t\t\t//   we don't distribute from the same amount to this j-th order for more than once.\n            // With this check, the program reduces from 97ms to 25 ms.\n            if (dist[i] >= quantity[j] && used.add(dist[i])) {\n                dist[i] -= quantity[j];\n                if (rec(dist, quantity, j-1))\n                    return true;\n                dist[i] += quantity[j];\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool solve(vector<int>&q, map<int,int>&count, int idx){\n        if(idx==q.size()){\n            return true;\n        }\n        for(auto it=count.begin();it!=count.end();it++){\n            if(it->second>=q[idx]){\n                count[it->first]-=q[idx];\n                if(solve(q,count,idx+1))\n                    return true;\n                count[it->first]+=q[idx];\n            }\n        }\n        return false;\n    }\n    bool canDistribute(vector<int>& nums, vector<int>& quantity) {\n        map<int,int>count;\n        int n=nums.size();\n        for(int i=0;i<n;i++){\n            count[nums[i]]++;\n        }\n        sort(quantity.begin(),quantity.end(),greater<int>());\n        return solve(quantity,count,0);\n\n    }\n};"
    },
    {
        "title": "Number of Ways to Select Buildings",
        "algo_input": "You are given a 0-indexed binary string s which represents the types of buildings along a street where:\n\n\n\ts[i] = '0' denotes that the ith building is an office and\n\ts[i] = '1' denotes that the ith building is a restaurant.\n\n\nAs a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.\n\n\n\tFor example, given s = \"001101\", we cannot select the 1st, 3rd, and 5th buildings as that would form \"011\" which is not allowed due to having two consecutive buildings of the same type.\n\n\nReturn the number of valid ways to select 3 buildings.\n\n&nbsp;\nExample 1:\n\nInput: s = \"001101\"\nOutput: 6\nExplanation: \nThe following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.\n\n\nExample 2:\n\nInput: s = \"11100\"\nOutput: 0\nExplanation: It can be shown that there are no valid selections.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def numberOfWays(self, s: str) -> int:\n        \n        temp = []\n        c0 = 0\n        c1 = 0\n        for char in s :\n            if char == \"0\" :\n                c0+=1\n            else:\n                c1+=1\n            temp.append([c0,c1])\n            \n        total0 = c0\n        total1 = c1\n        \n        \n        count = 0\n        for i in range(1, len(s)-1) :\n            \n            if s[i] == \"0\" :\n                m1 = temp[i-1][1]\n                m2 = total1 - temp[i][1]\n                count += m1*m2\n                \n            else:\n                m1 = temp[i-1][0]\n                m2 = total0 - temp[i][0]\n                count += m1*m2\n        return count\n                \n        ",
        "solution_js": "var numberOfWays = function(s) {\n    const len = s.length;\n    const prefix = new Array(len).fill(0).map(() => new Array(2).fill(0));\n    for(let i = 0; i < len; i++) {\n        const idx = s[i] == '1' ? 1 : 0;\n        if(i == 0) prefix[i][idx]++;\n        else {\n            prefix[i] = Array.from(prefix[i-1]);\n            prefix[i][idx]++;\n        }\n    }\n    let ans = 0;\n    for(let i = 1; i < len - 1; i++) {\n        const c = s[i] == '1' ? 0 : 1;\n        ans += (prefix.at(-1)[c] - prefix[i][c]) * prefix[i-1][c];\n    }\n    return ans;\n};",
        "solution_java": "class Solution\n{\n    public long numberOfWays(String s)\n    {\n        int zero = 0; // Individual zeroes count\n        long zeroOne = 0; // Number of combinations of 01s\n        int one = 0; // Individual ones count\n        long oneZero = 0; // Number of combinations of 10s\n        long tot = 0; // Final answer\n        for(char ch : s.toCharArray())\n        {\n            if(ch == '0')\n            {\n                zero++;\n                if(one > 0)\n                    oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10\n                if(zeroOne > 0)\n                    tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010\n            }\n            else\n            {\n                one++;\n                if(zero > 0)\n                    zeroOne += zero; // Each of the previously found 0s can pair to form 01\n                if(oneZero > 0)\n                    tot += oneZero; // Each of the previously formed 10 can form 101\n            }\n        }\n        return tot;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long numberOfWays(string s) {\n        long long a=0,b=0,ans=0;        // a and b are the number of occurances of '1' and '0' after the current building respectively.\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='1')\n                a++;\n            else\n                b++;\n        }\n        long long c=0,d=0;              // c and d are the number of occurances of '1' and '0' before the current building respectively.\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='1'){               // Counting the sequences of \"010\"\n                ans+=(d*b);\n                a--;\n                c++;\n            }\n            else{                        // Counting the sequences of \"101\"\n                ans+=(a*c);\n                b--;\n                d++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Sum of Subarray Minimums",
        "algo_input": "Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.\n\n\nExample 2:\n\nInput: arr = [11,81,94,43,3]\nOutput: 444\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 3 * 104\n\t1 &lt;= arr[i] &lt;= 3 * 104\n\n",
        "solution_py": "class Solution:\n    def sumSubarrayMins(self, arr: List[int]) -> int:\n        n = len(arr)\n        small_before = [-1]*n\n        stack = []\n        for i in range(n):\n            while stack and arr[stack[-1]] >= arr[i]:\n                stack.pop()\n            if stack:small_before[i] = stack[-1]\n            stack.append(i)\n        best = [0]*(n+1)\n        ans = 0\n        for i in range(n):\n            best[i] = best[small_before[i]] + (i - small_before[i])*arr[i]\n            ans += best[i]\n        return ans%1000000007",
        "solution_js": "var sumSubarrayMins = function(arr) {\n    \n    M = 10**9+7\n    stack = [-1]\n    res = 0\n    arr.push(0)\n    \n    for(let i2 = 0; i2 < arr.length; i2++){\n        while(arr[i2] < arr[stack[stack.length -1]]){\n            i = stack.pop()\n            i1 = stack[stack.length-1]\n            Left = i - i1\n            Right = i2 -i\n            res += (Left*Right*arr[i])\n        };\n        stack.push(i2)\n    };\n    \n    return res%M\n};",
        "solution_java": "class Solution {\n    public int sumSubarrayMins(int[] arr) {\n      int n = arr.length;\n      int ans1[] = nsl(arr);\n      int ans2[] = nsr(arr);\n      long sum=0;\n      for(int i=0;i<n;i++){\n        sum=(sum + (long)(arr[i]*(long)(ans1[i]*ans2[i])%1000000007)%1000000007)%1000000007;\n      }\n      return (int)sum;\n\t}\n    public static int[] nsl(int arr[]){\n      Stack<Integer> s = new Stack<>();\n      int ans[] = new int[arr.length];\n      for(int i=0;i<arr.length;i++){\n        while(!s.isEmpty() && arr[i]<arr[s.peek()]){\n          s.pop();\n        }\n        if(s.isEmpty()){\n          ans[i] = i-(-1);\n          s.push(i);\n        }\n        else{\n          ans[i] = i-s.peek();\n          s.push(i);\n        }\n      }\n      return ans;\n    }\n  public static int[] nsr(int arr[]){\n      Stack<Integer> s = new Stack<>();\n      int ans[] = new int[arr.length];\n      for(int i=arr.length-1;i>=0;i--){\n        while(!s.isEmpty() && arr[s.peek()]>=arr[i]){\n          s.pop();\n        }\n        if(s.isEmpty()){\n          ans[i] = arr.length-i;\n          s.push(i);\n        }\n        else{\n          ans[i] = s.peek()-i;\n          s.push(i);\n        }\n      }\n      return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic: //Thanks to Bhalerao-2002\n    int sumSubarrayMins(vector<int>& A) {\n        \n        int n = A.size();\n        int MOD = 1e9 + 7;\n        vector<int> left(n), right(n);\n        \n        // for every i find the Next smaller element to left and right\n        \n        // Left\n        stack<int>st;\n        st.push(0);\n        left[0] = 1; // distance = 1, left not found, this is distance multiplied with num, so it can't be zero\n        for(int i=1; i<n; i++)\n        {\n            while(!st.empty() && A[i] < A[st.top()]) \n                st.pop();\n            \n            if(st.empty()) \n                left[i] = i+1; // total distance if less element not found = i+1\n            else \n                left[i] = i - st.top(); // distance = i-st.top()\n            \n            st.push(i);\n            \n        }\n        \n        while(st.size()) \n            st.pop();\n        \n        // Right \n        st.push(n-1);\n        right[n-1] = 1; // distance = 1, right not found, this is distance multiplied with num, so it can't be zero\n        for(int i=n-2; i>=0; i--)\n        {\n            while(!st.empty() && A[i] <= A[st.top()]) \n                st.pop();\n            \n            if(st.empty()) \n                right[i] = n-i; // distance\n            else \n                right[i] = st.top()-i;\n            \n            st.push(i);\n        }\n        \n        // total number of subarrays : (Left[i] * Right[i])\n        // total contribution in A[i] element in final answer : (Left * Right) * A[i] \n        \n        for(int i=0; i<n; i++) \n             cout << left[i] << \" : \" << right[i] << endl;\n        \n        // for each i, contribution is (Left * Right) * Element \n        \n        int res = 0;\n        for(int i=0; i<n; i++)\n        {\n            long long prod = (left[i]*right[i])%MOD;\n            prod = (prod*A[i])%MOD;\n            res = (res + prod)%MOD;\n        }\n        \n        return res%MOD;\n    }\n    \n\n};"
    },
    {
        "title": "Maximum 69 Number",
        "algo_input": "You are given a positive integer num consisting only of digits 6 and 9.\n\nReturn the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).\n\n&nbsp;\nExample 1:\n\nInput: num = 9669\nOutput: 9969\nExplanation: \nChanging the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.\n\n\nExample 2:\n\nInput: num = 9996\nOutput: 9999\nExplanation: Changing the last digit 6 to 9 results in the maximum number.\n\n\nExample 3:\n\nInput: num = 9999\nOutput: 9999\nExplanation: It is better not to apply any change.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 104\n\tnum&nbsp;consists of only 6 and 9 digits.\n\n",
        "solution_py": "class Solution:\n    def maximum69Number(self, num):\n        lst= list(str(num)) #! convert the number to a list\n        for i in range(len(lst)): #! iterate through the list\n            if lst[i]=='6': #! if the element is 6\n                lst[i]='9' #! replace the element with 9\n                break #! break the loop\n        return int(''.join(lst))  #! convert the list to a number",
        "solution_js": "var maximum69Number = function(num) {\n  let flag=true\n   num= num.toString().split('').map((x)=>{\n        if(x!=='9'&&flag){\n            flag=false\n            return '9'\n        }\n        return x\n    })\n    return parseInt(num.join(''))\n};",
        "solution_java": "class Solution {\n    public int maximum69Number (int num) {\n        int i;\n        String s=String.valueOf(num);\n        int l=s.length();\n        int max=num;\n        \n        for(i=0;i<l;i++)\n        {\n            char c[]=s.toCharArray();\n            if(c[i]=='9')\n            {\n                c[i]='6';\n            }\n            else\n            {\n                c[i]='9';\n            }\n            String p=new String(c);\n            int k=Integer.parseInt(p);\n            max=Math.max(max,k);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximum69Number (int num) {\n        string s=to_string(num);\n        for(int i=0;i<s.size();i++){\n            if(s[i]=='6'){\n                 s[i]='9';\n                break;\n            }\n               \n        }\n        num=stoi(s);\n        return num;\n    }\n};"
    },
    {
        "title": "Single Number III",
        "algo_input": "Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.\n\nYou must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,1,3,2,5]\nOutput: [3,5]\nExplanation:  [5, 3] is also a valid answer.\n\n\nExample 2:\n\nInput: nums = [-1,0]\nOutput: [-1,0]\n\n\nExample 3:\n\nInput: nums = [0,1]\nOutput: [1,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 3 * 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\tEach integer in nums will appear twice, only two integers will appear once.\n\n",
        "solution_py": "class Solution:\n    def singleNumber(self, nums: List[int]) -> List[int]:\n        x = Counter(nums)\n        return([y for y in x if x[y] == 1])",
        "solution_js": "var singleNumber = function(nums) {\n    let hash ={}\n    for ( let num of nums){\n        if( hash[num]===undefined)\n            hash[num] =1\n        else\n            hash[num]++\n    }\n\n    let result =[]\n    for ( let [key, value] of Object.entries(hash)){\n         if(value==1)\n         result.push(key)\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public int[] singleNumber(int[] nums) {\n        if (nums == null || nums.length < 2 || nums.length % 2 != 0) {\n            throw new IllegalArgumentException(\"Invalid Input\");\n        }\n\n        int aXORb = 0;\n        for (int n : nums) {\n            aXORb ^= n;\n        }\n\n        int rightSetBit = aXORb & -aXORb;\n        int a = 0;\n        for (int n : nums) {\n            if ((n & rightSetBit) != 0) {\n                a ^= n;\n            }\n        }\n\n        return new int[] {a, aXORb ^ a};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> singleNumber(vector<int>& nums){\n        vector<int> ans;\n        int xorr = 0;\n        for(int i=0; i<nums.size(); i++){\n            xorr = xorr xor nums[i];\n        }\n        int count  = 0;\n        while(xorr){\n            if(xorr & 1){\n                break;\n            }\n            count++;\n            xorr = xorr >> 1;\n        }\n        int xorr1 = 0;\n        int xorr2 = 0;\n        for(int i=0; i<nums.size(); i++){\n            if(nums[i] & (1 << count)){\n                xorr1 = xorr1 xor nums[i];\n            }\n            else{\n                xorr2 = xorr2 xor nums[i];\n            }\n        }\n        ans.push_back(xorr1);\n        ans.push_back(xorr2);\n        return ans;\n    }\n};"
    },
    {
        "title": "Calculate Amount Paid in Taxes",
        "algo_input": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 &lt; upperi for 0 &lt; i &lt; brackets.length).\n\nTax is calculated as follows:\n\n\n\tThe first upper0 dollars earned are taxed at a rate of percent0.\n\tThe next upper1 - upper0 dollars earned are taxed at a rate of percent1.\n\tThe next upper2 - upper1 dollars earned are taxed at a rate of percent2.\n\tAnd so on.\n\n\nYou are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: brackets = [[3,50],[7,10],[12,25]], income = 10\nOutput: 2.65000\nExplanation:\nBased on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.\n\n\nExample 2:\n\nInput: brackets = [[1,0],[4,25],[5,50]], income = 2\nOutput: 0.25000\nExplanation:\nBased on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.\n\n\nExample 3:\n\nInput: brackets = [[2,50]], income = 0\nOutput: 0.00000\nExplanation:\nYou have no income to tax, so you have to pay a total of $0 in taxes.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= brackets.length &lt;= 100\n\t1 &lt;= upperi &lt;= 1000\n\t0 &lt;= percenti &lt;= 100\n\t0 &lt;= income &lt;= 1000\n\tupperi is sorted in ascending order.\n\tAll the values of upperi are unique.\n\tThe upper bound of the last tax bracket is greater than or equal to income.\n\n",
        "solution_py": "class Solution:\n    def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n        taxtot=0\n        if(brackets[0][0]<income):\n            taxtot+=brackets[0][0]*(brackets[0][1])\n            income-=brackets[0][0]\n        else:\n            taxtot+=income*(brackets[0][1])\n            return taxtot/100\n        i=1\n        while(income>0 and i<len(brackets)):\n            if(income>(brackets[i][0]-brackets[i-1][0])):\n                taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]\n                income-=brackets[i][0]-brackets[i-1][0]\n            else:\n                taxtot+=income*brackets[i][1]\n                income=0\n            i+=1\n        return taxtot/100",
        "solution_js": "var calculateTax = function(brackets, income) {\n    return brackets.reduce(([tax, prev], [upper, percent]) => {\n        let curr = Math.min(income, upper - prev);\n        tax += curr * (percent / 100);\n\n        income -= curr;\n        if (income <= 0) brackets.length = 0;\n\n        return [tax, upper];\n    }, [0, 0])[0];\n};",
        "solution_java": "class Solution {\n    public double calculateTax(int[][] brackets, int income) {\n        double ans=0;\n        int pre=0;\n        for(int[] arr : brackets){\n            int val=arr[0]; arr[0]-=pre;  pre=val;\n            ans+=(double)(Math.min(income,arr[0])*arr[1])/100;\n            income-=arr[0];\n            if(income<=0){ break; }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double calculateTax(vector<vector<int>>& brackets, int income) \n    {    \n        double tax = 0; \n        \n        if(brackets[0][0]<=income) tax=(brackets[0][0]*brackets[0][1]/100.0);         \n        else return (income*brackets[0][1]/100.0);\n            \n        for(int i=1; i<brackets.size(); i++)\n        {\n            if(brackets[i][0]<=income)\n                    tax += ((brackets[i][0]-brackets[i-1][0])*brackets[i][1]/100.0);\n            \n            else \n            {\n                tax += ((income-brackets[i-1][0])*brackets[i][1]/100.0);\n                break;\n            }\n        }\n        return tax;\n        \n    }\n};"
    },
    {
        "title": "My Calendar II",
        "algo_input": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.\n\nA triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).\n\nThe event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start &lt;= x &lt; end.\n\nImplement the MyCalendarTwo class:\n\n\n\tMyCalendarTwo() Initializes the calendar object.\n\tboolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, true, true, true, false, true, true]\n\nExplanation\nMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15);  // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= start &lt; end &lt;= 109\n\tAt most 1000 calls will be made to book.\n\n",
        "solution_py": "class Node:\n    def __init__(self, start, end, val):\n        self.start = start\n        self.end = end\n        self.val = val\n        self.left = None\n        self.right = None\n    \n    def insertable(self, node):\n        if node.end <= node.start:\n            return True\n        if node.end <= self.start:\n            if not self.left:\n                return True\n            else:\n                return self.left.insertable(node)\n        elif node.start >= self.end:\n            if not self.right:\n                return True\n            else:\n                return self.right.insertable(node)\n        else:\n            if self.val == 1:\n                leftS = min(self.start, node.start)\n                leftE = max(self.start, node.start)\n                rightS = min(self.end, node.end)\n                rightE = max(self.end, node.end)\n                if not self.left and not self.right:\n                    return True\n                elif not self.left:\n                    return self.right.insertable(Node(rightS, rightE, 1))\n                elif not self.right:\n                    return self.left.insertable(Node(leftS, leftE, 1))\n                else:\n                    resL = self.left.insertable(Node(leftS, leftE, 1))\n                    resR = self.right.insertable(Node(rightS, rightE, 1))\n                    if resL and resR:\n                        return True\n                    return False\n            else:\n                return False\n\n    def insert(self, node):\n        if node.end <= node.start:\n            return\n        \n        if node.end <= self.start:\n            if not self.left:\n                self.left = node\n            else:\n                self.left.insert(node)\n        elif node.start >= self.end:\n            if not self.right:\n                self.right = node\n            else:\n                self.right.insert(node)\n        else:\n            leftS = min(self.start, node.start)\n            leftE = max(self.start, node.start)\n            rightS = min(self.end, node.end)\n            rightE = max(self.end, node.end)\n            self.val += 1\n            self.start, self.end = leftE, rightS  \n            if not self.left and not self.right:  \n                self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n                self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n            elif not self.left:\n                self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n                self.right.insert(Node(rightS, rightE, 1))\n            elif not self.right:\n                self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n                self.left.insert(Node(leftS, leftE, 1))\n            else:\n                self.left.insert(Node(leftS, leftE, 1))\n                self.right.insert(Node(rightS, rightE, 1))\n        return\n\n\nclass MyCalendarTwo:\n\n    def __init__(self):\n        self.root = None\n\n    def book(self, start: int, end: int) -> bool:\n        if not self.root:\n            self.root = Node(start, end, 1)\n            return True\n        else:\n            newNode = Node(start, end, 1)\n            if self.root.insertable(newNode):\n                self.root.insert(newNode)\n                return True\n            return False",
        "solution_js": "var MyCalendarTwo = function() {\n  this.calendar = [];\n  this.overlaps = [];\n};\n\n/** \n * @param {number} start \n * @param {number} end\n * @return {boolean}\n */\nMyCalendarTwo.prototype.book = function(start, end) {\n  for (let date of this.overlaps) {\n    if (start < date[1] && end > date[0]) return false;\n  }\n\n  for (let date of this.calendar) {\n    if (start < date[1] && end > date[0]) {\n      this.overlaps.push([Math.max(date[0], start), Math.min(date[1], end)]);\n    }\n  }\n  this.calendar.push([start, end]); \n  return true;\n};",
        "solution_java": "class MyCalendarTwo {\n    private List<int[]> bookings;\n    private List<int[]> doubleBookings;\n    \n    public MyCalendarTwo() {\n        bookings = new ArrayList<>();\n        doubleBookings = new ArrayList<>();\n    }\n    \n \n    public boolean book(int start, int end) {\n        for(int[] b : doubleBookings)\n        {\n\t\t//condition to check for the overlaping\n            if(start < b[1] && end > b[0])\n                return false;\n        }\n        \n        for(int[] b : bookings)\n        {\n            if(start < b[1] && end > b[0]) {\n                doubleBookings.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});\n            }\n        }\n        bookings.add(new int[]{start, end});\n        return true;\n    }\n}",
        "solution_c": "class MyCalendarTwo {\npublic:\n    map<int,int>mpp;\n    MyCalendarTwo() {\n\n    }\n\n    bool book(int start, int end) {\n        mpp[start]++;\n        mpp[end]--;\n        int sum=0;\n        for(auto it:mpp){\n            sum+=it.second;\n            if(sum>2){\n                mpp[start]--;\n                mpp[end]++;\n                return false;\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Largest Values From Labels",
        "algo_input": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit.\n\nChoose a subset s of the n elements such that:\n\n\n\tThe size of the subset s is less than or equal to numWanted.\n\tThere are at most useLimit items with the same label in s.\n\n\nThe score of a subset is the sum of the values in the subset.\n\nReturn the maximum score of a subset s.\n\n&nbsp;\nExample 1:\n\nInput: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput: 9\nExplanation: The subset chosen is the first, third, and fifth items.\n\n\nExample 2:\n\nInput: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput: 12\nExplanation: The subset chosen is the first, second, and third items.\n\n\nExample 3:\n\nInput: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput: 16\nExplanation: The subset chosen is the first and fourth items.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == values.length == labels.length\n\t1 &lt;= n &lt;= 2 * 104\n\t0 &lt;= values[i], labels[i] &lt;= 2 * 104\n\t1 &lt;= numWanted, useLimit &lt;= n\n\n",
        "solution_py": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n    def largestValsFromLabels(\n        self, values: list[int], labels: list[int], numWanted: int, useLimit: int\n    ) -> int:\n\n        # Add labels and values into the heap\n        heap = [(-value, label) for value, label in zip(values, labels)]\n        heapq.heapify(heap)\n\n        # Initialize the hashmap\n        used = defaultdict(int)\n\n        # Initialize the result\n        res = 0\n\n        # Iterate until we have used a certain number or the heap is empty\n        while numWanted > 0 and heap:\n\n            # Pop a label and its value from the heap\n            value, label = heapq.heappop(heap)\n\n            # If we can use such label\n            if used[label] < useLimit:\n\n                # Add its value to the result\n                res += -value\n\n                # Increment its count in the hashmap\n                used[label] += 1\n\n                # Decrement the number of numbers we still want\n                numWanted -= 1\n\n        return res",
        "solution_js": "/**\n * @param {number[]} values\n * @param {number[]} labels\n * @param {number} numWanted\n * @param {number} useLimit\n * @return {number}\n */\nvar largestValsFromLabels = function(values, labels, numWanted, useLimit) {\n    // this sortValues will create an addition array that keep track of the value idx after descending sort\n    // which is useful to map the labels accordingly\n    let sortValues = values.map((val, idx) => [val, idx]), sortLabels = []\n    sortValues.sort((a, b) => b[0] - a[0])\n    \n    for (let [val, idx] of sortValues) {\n        sortLabels.push(labels[idx])\n    }\n    values.sort((a, b) => b - a)\n    labels = sortLabels\n    \n    let i = 0, map = {}, ans = 0\n    while (i < values.length && numWanted > 0) {\n        if (map[labels[i]]) map[labels[i]] ++\n        else map[labels[i]] = 1\n        \n        if ((map[labels[i]]) <= useLimit) {\n            ans += values[i]\n            numWanted--\n        }\n        \n        i++\n    }\n    \n    return ans\n    \n};",
        "solution_java": "class Solution {\n    public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {\n        PriorityQueue<Pair<Integer, Integer>> maxHeap = \n            new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey()));\n        for(int i=0;i<values.length;i++) {\n            maxHeap.add(new Pair<Integer, Integer>(values[i], labels[i]));\n        }\n        Map<Integer, Integer> labelLimitMap = new HashMap<>();\n        int sum = 0;\n        while(numWanted != 0) {\n            int label = maxHeap.peek().getValue();\n            if(labelLimitMap.containsKey(label)) {\n                if(labelLimitMap.get(label) == useLimit) {\n                    maxHeap.poll();\n                } else {\n                    labelLimitMap.put(label, labelLimitMap.get(label) + 1);\n                    sum += maxHeap.poll().getKey();\n                    numWanted--;\n                }\n            } else {\n                labelLimitMap.put(label, 1);\n                sum += maxHeap.poll().getKey();\n                numWanted--;\n            }\n            // This Holds since at most numWanted is mentioned.\n            if(maxHeap.isEmpty()) {\n                return sum;\n            }\n        }\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largestValsFromLabels(vector<int>& values, vector<int>& labels, int numWanted, int useLimit) {\n        // same label item should be less than uselimit\n        priority_queue<pair<int,int>>q;  // this will give us maximum element because we need to maximise the sum \n        for(int i=0;i<values.size();i++)\n        {\n            q.push({values[i],i});\n        }\n        long long int ans=0;\n        unordered_map<int,int>m;\n        // we cant use more numbers than useLimit\n        // storing each use labels in map to count the use limit of that number\n        int i=0;\n        while(i<numWanted)\n        {\n            int t=q.top().first;   //number \n            int ind=q.top().second; // labels index\n            q.pop();\n            if(m[labels[ind]]<useLimit)   // if less than count then include in our answer\n            {\n                ans+=t;\n                m[labels[ind]]++;\n                i++;\n            }\n            if(q.size()==0)\n            {\n                break;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Find All Good Strings",
        "algo_input": "Given the strings s1 and s2 of size n and the string evil, return the number of good strings.\n\nA good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\nOutput: 51 \nExplanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".&nbsp;\n\n\nExample 2:\n\nInput: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\nOutput: 0 \nExplanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\n\n\nExample 3:\n\nInput: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\ts1.length == n\n\ts2.length == n\n\ts1 &lt;= s2\n\t1 &lt;= n &lt;= 500\n\t1 &lt;= evil.length &lt;= 50\n\tAll strings consist of lowercase English letters.\n\n",
        "solution_py": "from functools import lru_cache\nclass Solution:\n    def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n        def srange(a, b):\n            return [chr(i) for i in range(ord(a),ord(b)+1)]\n        def LPS(pat):\n            lps = [0]\n            i, target = 1, 0\n            while i < len(pat):\n                if pat[i] == pat[target]:\n                    target += 1\n                    lps.append(target)\n                    i += 1\n                elif target:\n                    target = lps[target-1]\n                else:\n                    lps.append(0)\n                    i += 1\n            return lps\n        lps = LPS(evil)\n        M = 10**9+7\n        @lru_cache(None)\n        def dfs(i, max_matched_idx, lb, rb):\n            if max_matched_idx == len(evil): return 0\n            if i == n: return 1\n            l = s1[i] if lb else 'a'\n            r = s2[i] if rb else 'z'\n            candidates = srange(l, r)\n            res = 0\n            for j, c in enumerate(candidates):\n                nxt_matched_idx = max_matched_idx\n                while evil[nxt_matched_idx] != c and nxt_matched_idx:\n                    nxt_matched_idx = lps[nxt_matched_idx-1]\n                res = (res + dfs(i+1, nxt_matched_idx+(c==evil[nxt_matched_idx]),\n                          lb = (lb and j == 0), rb = (rb and j==len(candidates)-1)))%M\n            return res\n        return dfs(0, 0, True, True)",
        "solution_js": "const mod = 10 ** 9 + 7\n\nlet cache = null\n\n/**\n * @param {number} n\n * @param {string} s1\n * @param {string} s2\n * @param {string} evil\n * @return {number}\n */\nvar findGoodStrings = function(n, s1, s2, evil) {\n    /**\n     * 17 bits\n     * - 9 bit: 2 ** 9 > 500 by evil\n     * - 6 bit: 2 ** 6 > 50 by evil\n     * - 1 bit left (bound)\n     * - 1 bit right (bound)\n     *\n     * cache: `mainTraver` is the prefix length, `evilMatch` is matching for evil\n     *\n     * answer: marnTravel 0, evil 0, s prefix has the last character\n     */\n    cache = new Array(1 << 17).fill(-1)\n    return dfs(0, 0, n, s1, s2, evil, true, true, computeNext(evil))\n}\n/**\n * DFS:\n * 1. loop from `s1` to `s2`, range of position `i` is [0, n]: 0 means no start, n means complete\n * 2. if `s1` has traversed to nth, it means has been generated a legal character, and return 1; else\n * 3. `mainTravel` is the length of the `s` generated by dfs last time\n * 4. `evilMatch` is the length that matches the last generated `s` in evilMatch evil\n * 5. n, s1, s2, evil, left, right, next\n */\nfunction dfs(mainTravel, evilMatch, n, s1, s2, evil, left, right, next, ans = 0) {\n    // same length means that the match has been successful\n    if(evilMatch === evil.length) {\n        return 0\n    }\n    // this means s is conformed\n    if(mainTravel === n) {\n        return 1\n    }\n    \n    // get key for cache\n    let key = generateKey(mainTravel, evilMatch, left, right)\n    // because any combination of the four categories will only appear once, there will be no repetition\n    if(cache[key] !== -1) {\n        return cache[key]\n    }\n    \n    // get start, end calculate\n    let [start, end] = [left ? s1.charCodeAt(mainTravel) : 97, right ? s2.charCodeAt(mainTravel) : 122]\n    \n    // loop\n    for(let i = start; i <= end; i++) {\n        // get char code\n        let code = String.fromCharCode(i)\n        // actually, `evilMatch` will only get longer or stay the same, not shorter\n        let m = evilMatch\n        \n        while((m > 0) && (evil[m] !== code)) {\n            m = next[m - 1]\n        }\n\n        if(evil[m] === code) {\n            m++\n        }\n\n        // recursive\n        ans += dfs(mainTravel + 1, m, n, s1, s2, evil, left && (i === start), right && (i === end), next)\n        \n        // too large\n        ans %= mod\n    }\n\n    // result after cache set\n    return cache[key] = ans, ans\n}\n\n// create key for cache\nfunction generateKey(mainTravel, evilMatch, left, right) {\n    return (mainTravel << 8) | (evilMatch << 2) | ((left ? 1 : 0 ) << 1) | (right ? 1 : 0)\n}\n\n// for next right move, index + 1\nfunction computeNext(evil, n = evil.length, ans = new Array(n).fill(0), k = 0) {\n    for(let i = 1; i < n; i++) {\n        while((k > 0) && (evil[i] !== evil[k])) {\n            k = ans[k - 1]\n        }\n\n        if(evil[i] === evil[k]) {\n            ans[i] = ++k\n        }\n    }\n    return ans\n}",
        "solution_java": "class Solution {\n    Integer[][][][] dp;\n    int mod = 1000000007;\n    int[] lps;\n    private int add(int a, int b) {\n        return (a % mod + b % mod) % mod;\n    }\n    private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) {\n        if(evI == evil.length) return 0;\n        if(cur == s2.length) return 1;\n        if(dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] != null) return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI];\n        char start = isStrictLower ? s1[cur] : 'a';\n        char end = isStrictUpper ? s2[cur] : 'z';\n        int res = 0;\n        for(char ch = start; ch <= end; ch ++) {\n            if(evil[evI] == ch)\n                res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, evI + 1));\n            else {\n                int j = evI;\n                while (j > 0 && evil[j] != ch) j = lps[j - 1];\n                if (ch == evil[j]) j++;\n                res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, j));\n            }\n        }\n        return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] = res;\n    }\n    public int findGoodStrings(int n, String s1, String s2, String evil) {\n        char[] arr = s1.toCharArray();\n        char[] brr = s2.toCharArray();\n        char[] crr = evil.toCharArray();\n        lps = new int[crr.length];\n        for (int i = 1, j = 0; i < crr.length; i++) {\n            while (j > 0 && crr[i] != crr[j]) j = lps[j - 1];\n            if (crr[i] == crr[j]) lps[i] = ++j;\n        }\n        dp = new Integer[n][2][2][crr.length];\n        return solve(arr, brr, 0, true, true, crr, 0);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    using ll = long long;\n    int findGoodStrings(int n, string s1, string s2, string evil) {\n      int M = 1e9+7;\n      int m = evil.size();\n      // kmp\n      int f[m];\n      f[0] = 0;\n      for (int i = 1, j = 0; i < m; ++i) {\n        while (j != 0 && evil[i] != evil[j]) {\n          j = f[j-1];\n        }\n        if (evil[i] == evil[j]) {\n          ++j;\n        }\n        f[i] = j;\n      }\n      // next(i,c) jump function when matched i length and see c\n      int next[m+1][26];\n      for (int i = 0; i <= m; ++i) {\n        for (int j = 0; j < 26; ++j) {\n          if (i < m && evil[i] == 'a'+j) {\n            next[i][j] = i+1;\n          } else {\n            next[i][j] = i == 0? 0: next[f[i-1]][j];\n          }\n        }\n      }\n      // dp(i,j,l1,l2) length i greater than s1, less than s2;\n      // match j length of evil\n      // l1 true means limited for s1, l2 true means limited for s2\n      ll dp[n+1][m+1][2][2];\n      memset(dp, 0, sizeof(dp));\n      dp[0][0][1][1] = 1;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < m; ++j) {\n          for (int c = 0; c < 26; ++c) {\n            int k = next[j][c];\n            char ch = 'a'+c;\n            dp[i+1][k][0][0] += dp[i][j][0][0];\n            if (dp[i][j][1][1]) {\n              if (ch > s1[i] && ch < s2[i]) {\n                dp[i+1][k][0][0] += dp[i][j][1][1];\n              } else if (ch == s1[i] && ch == s2[i]) {\n                dp[i+1][k][1][1] += dp[i][j][1][1];\n              } else if (ch == s1[i]) {\n                dp[i+1][k][1][0] += dp[i][j][1][1];\n              } else if (ch == s2[i]) {\n                dp[i+1][k][0][1] += dp[i][j][1][1];\n              }\n            }\n            if (dp[i][j][1][0]) {\n              if (ch > s1[i]) {\n                dp[i+1][k][0][0] += dp[i][j][1][0];\n              } else if (ch == s1[i]) {\n                dp[i+1][k][1][0] += dp[i][j][1][0];\n              }\n            }\n            if (dp[i][j][0][1]) {\n              if (ch < s2[i]) {\n                dp[i+1][k][0][0] += dp[i][j][0][1];\n              } else if (ch == s2[i]) {\n                dp[i+1][k][0][1] += dp[i][j][0][1];\n              }\n            }\n            dp[i+1][k][0][0] %= M;\n          }\n        }\n      }\n      ll ans = 0;\n      for (int i = 0; i < m; ++i) {\n        ans += dp[n][i][0][0] + dp[n][i][0][1] + dp[n][i][1][0];\n        ans %= M;\n      }\n      return ans;\n    }\n};"
    },
    {
        "title": "Allocate Mailboxes",
        "algo_input": "Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.\n\nReturn the minimum total distance between each house and its nearest mailbox.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n\n\nExample 2:\n\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= houses.length &lt;= 100\n\t1 &lt;= houses[i] &lt;= 104\n\tAll the integers of houses are unique.\n\n",
        "solution_py": "class Solution:\n    def minDistance(self, houses: List[int], k: int) -> int:\n        houses.sort()\n\n        @lru_cache(None)\n        def dp(left, right, k):\n            if k == 1:                                          # <-- 1.\n                mid = houses[(left+right) // 2]\n                return sum(abs(houses[i] - mid) for i in range(left, right + 1))\n\n            return min(dp(left, i, 1) + dp(i+1, right, k - 1) \n                       for i in range(left, right - k + 2))     # <-- 2.\n\n        return dp(0, len(houses)-1, k)",
        "solution_js": "/**\n * @param {number[]} houses\n * @param {number} k\n * @return {number}\n */\nvar minDistance = function(houses, k) {\n    var distance=[],median,dist,cache={};\n    houses.sort(function(a,b){return a-b});\n    //distance[i][j] is the minimun distacne if we cover houses from ith index to jth index with 1 mailbox. This mailbox will be at the median index of sub array from ith index to jth index.\n    for(let i=0;i<houses.length;i++){\n        for(let j=i;j<houses.length;j++){\n            median = Math.floor((i+j)/2);\n            dist=0;\n            for(let k=i;k<=j;k++){\n                dist+=Math.abs(houses[median]-houses[k]);\n            }\n            if(distance[i]===undefined){\n                distance[i]=[];\n            }\n            distance[i][j]=dist;\n        }\n    }\n    return dp(0,k);\n    function dp(i,k){\n        let cacheKey=i+\"_\"+k;\n        if(cache[cacheKey]!==undefined){\n            return cache[cacheKey];\n        }\n        let min=Number.MAX_SAFE_INTEGER,ans;\n        if(i===houses.length && k===0){//Its a correct answer only if we have used all the mailboxes and all the houses are completed. \n            return 0;\n        }\n        if(i===houses.length || k===0){//Other than the first if condition, every other condition to exhaust either mailboxes for houses is an invalid answer. So returning minus an infinite number from here. \n            return min;\n        }\n        \n        for(let j=i;j<houses.length;j++){//Here in each step we are covering houses from ith index to jth index with one mailbox and calling dp function to cover the rest of the houses, starting from jth+1 index with the remaining k-1 houses. In each possible answer we will keep the minimum ans. \n            ans = dp(j+1,k-1)+distance[i][j];\n            min = Math.min(min,ans);\n        }\n        cache[cacheKey]=min;\n        return min;\n    }\n};",
        "solution_java": "class Solution {\n    public int minDistance(int[] houses, int k) {\n        Arrays.sort(houses);\n        int n = houses.length;\n        int[] dp = new int[n];\n        for (int i = 1; i < n; i++){ // know optimal dist for i-1, then for i, we add houses[i] - houses[i/2]\n            dp[i]=dp[i-1]+houses[i]-houses[i/2];\n        }\n        for (int i = 0; i < k-1; i++){\n            int[] next = new int[n];\n            Arrays.fill(next, Integer.MAX_VALUE);\n            for (int j = 0; j < n; j++){\n                int sum = 0;\n                for (int m = j; m >= 0; m--){\n                    sum += houses[(m+j+1)>>1]-houses[m]; // likewise, adding to the front needs the +1 to account for the truncation.\n                    next[j] = Math.min(next[j], (m==0?0:dp[m-1])+sum);\n                }\n            }\n            dp=next;\n        }\n        return dp[n-1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[101][101] ;\n    int solve(vector<int>&houses , int pos , int k){\n        if(k < 0) return 1e9 ;\n        if(pos >= houses.size()) return k ? 1e9 : 0 ; \n        if(dp[pos][k] != -1) return dp[pos][k] ;\n        \n        //at current position pos, spread the group from (pos upto j) and allot this whole group 1 mailbox.\n        //start new neigbour at j + 1\n        \n        int ans = INT_MAX ;\n        for(int j = pos ; j < houses.size() ; ++j ){\n            int middle = (pos + j) / 2 , cost = 0 ;\n            //cost calculation\n            for(int i = pos ; i <= j ; ++i ) cost += abs(houses[middle] - houses[i]);\n            \n            ans = min(ans,cost + solve(houses,j + 1, k - 1)) ;\n        }\n        return dp[pos][k] = ans ;\n    }\n    int minDistance(vector<int>& houses, int k) {\n        sort(begin(houses),end(houses)) ;\n        memset(dp,-1,sizeof(dp)) ;\n        \n        return solve(houses,0,k);\n    }\n};"
    },
    {
        "title": "Shortest Completing Word",
        "algo_input": "Given a string licensePlate and an array of strings words, find the shortest completing word in words.\n\nA completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.\n\nFor example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\".\n\nReturn the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.\n\n&nbsp;\nExample 1:\n\nInput: licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput: \"steps\"\nExplanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.\n\n\nExample 2:\n\nInput: licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput: \"pest\"\nExplanation: licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= licensePlate.length &lt;= 7\n\tlicensePlate contains digits, letters (uppercase or lowercase), or space ' '.\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length &lt;= 15\n\twords[i] consists of lower case English letters.\n\n",
        "solution_py": "class Solution:\n    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n        newPlate = ''         # modify the licensePlate\n        for i in licensePlate:\n            if i.isalpha():\n                newPlate += i.lower()\n                \n        c = Counter(newPlate)\n        l1 = []         # store (word,len,index)\n        for idx,word in enumerate(words):\n            if Counter(word) >= c:\n                l1.append((word,len(word),idx))\n        l1.sort(key = lambda x:(x[1],idx))\n        return l1[0][0]",
        "solution_js": "var shortestCompletingWord = function(licensePlate, words) {\n\n    // Object to hold the shortest word that matches\n    var match = {'found':false, 'word':''};\n\n    // Char array to hold the upper case characters we want to match\n    var licensePlateChars = licensePlate.toUpperCase().replace(/[^A-Z]/g, '').split('');\n\n    words.forEach(function (word) {\n        // if we already have a match make sure that the word we are checking is shorter\n        if (!match.found || word.length < match.word.length) {\n            var replaceWord = word.toUpperCase();\n\n            // Loop over each character in the license plate and replace one at a time\n            // the key here is that replace will only replace 1 S even if there are 2\n            licensePlateChars.forEach(function (lChar) {\n                replaceWord = replaceWord.replace(lChar, '');\n            });\n\n            // We know the word works if the length of the word minus\n            // the length of chars equals the length of the new word\n            if (word.length - licensePlateChars.length === replaceWord.length) {\n                match.found = true;\n                match.word = word\n            }\n        }\n    });\n\n    return match.word;\n};",
        "solution_java": "class Solution {\n    public String shortestCompletingWord(String licensePlate, String[] words) {\n        //Store count of letters in LicensePlate\n        int[] licensePlateCount = new int[26];\n        \n        //To store all words which meet the criteria\n        ArrayList<String> res = new ArrayList<>();\n        //To find min length word that meets the criteria\n        int min = Integer.MAX_VALUE;\n        \n        //Add char count for each char in LicensePlate\n        for(Character c:licensePlate.toCharArray()) {\n            if(isChar(c)) {\n                licensePlateCount[Character.toLowerCase(c) - 'a']++;\n            }\n        }\n        \n        //Add char count for each word in words\n        for(String word : words) {\n            int[] wordCharCount = new int[26];\n            boolean flag = true;\n            \n            for(Character c:word.toCharArray()) {\n                wordCharCount[Character.toLowerCase(c) - 'a']++;\n            }\n            \n            //Eliminate words that don't satisfy the criteria\n            for(int i = 0; i<26;i++) {\n                if(licensePlateCount[i] > wordCharCount[i]) flag = false;\n            }\n            \n            //Add words satisfying criteria to res and calculate min word length\n            if(flag) {\n                res.add(word);\n                if(word.length() < min) min = word.length();\n            }\n        }\n        \n        //Return 1st word in array meeting all criteria\n        for(int i = 0; i < res.size();i++) {\n            if(res.get(i).length() == min) return res.get(i);\n        }\n        \n        //If not found, return -1 (or whatever interviewer expects)\n        return \"-1\";\n    }\n    \n    private boolean isChar(Character c) {\n        if((c >='a' && c <='z') ||\n           (c>='A' && c<='Z')) return true;\n        \n        return false;\n    }\n}",
        "solution_c": "\tclass Solution {\npublic:\n    string shortestCompletingWord(string licensePlate, vector<string>& words) \n    {\n        string ans=\"\";\n        vector<int> m(26,0);\n        for(auto &lp:licensePlate)\n        {\n            if(isalpha(lp))\n                m[tolower(lp)-'a']++;\n        }\n        for(auto &word:words)\n        {\n            vector<int> v=m;\n            for(auto &ch:word)\n            {\n                v[tolower(ch)-'a']--;\n            }\n            bool flag=true;\n            for(int i=0;i<26;i++)\n            {\n                if(v[i]>0)\n                    flag =false;\n            }\n            if(flag&&(ans==\"\"||ans.size()>word.size()))\n                ans=word;\n        }\n        return ans;\n        \n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Number of Increasing Paths in a Grid",
        "algo_input": "You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.\n\nReturn the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.\n\nTwo paths are considered different if they do not have exactly the same sequence of visited cells.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,1],[3,4]]\nOutput: 8\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -&gt; 3], [1 -&gt; 4], [3 -&gt; 4].\n- Paths with length 3: [1 -&gt; 3 -&gt; 4].\nThe total number of paths is 4 + 3 + 1 = 8.\n\n\nExample 2:\n\nInput: grid = [[1],[2]]\nOutput: 3\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -&gt; 2].\nThe total number of paths is 2 + 1 = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 1000\n\t1 &lt;= m * n &lt;= 105\n\t1 &lt;= grid[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def __init__(self):\n        self.dp = None\n        self.di = [0, 0, -1, 1]\n        self.dj = [-1, 1, 0, 0]\n        self.mod = 1000000007\n    \n    def countPaths(self, grid):\n        n = len(grid)\n        m = len(grid[0])\n        self.dp = [[0] * m for _ in range(n)]\n        ans = 0\n        for i in range(n):\n            for j in range(m):\n                ans = (ans + self.dfs(grid, i, j, -1)) % self.mod\n        return ans\n    \n    def dfs(self, grid, i, j, prev):\n        if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= prev:\n            return 0\n        if self.dp[i][j] != 0:\n            return self.dp[i][j]\n        self.dp[i][j] = 1\n        for k in range(4):\n            self.dp[i][j] += self.dfs(grid, i + self.di[k], j + self.dj[k], grid[i][j])\n            self.dp[i][j] %= self.mod\n        return self.dp[i][j] % self.mod",
        "solution_js": "var countPaths = function(grid) {\n  let mod = Math.pow(10, 9) + 7;\n  let result = 0;\n  let rows = grid.length, columns = grid[0].length;\n  let dp = Array(rows).fill(null).map(_ => Array(columns).fill(0));\n\n  const dfs = (r, c, preVal)=> {\n    if (r < 0 || r == rows || c < 0 || c == columns || grid[r][c] <= preVal) return 0\n    if (dp[r][c]) return dp[r][c]\n    return dp[r][c] = (1 + dfs(r + 1, c, grid[r][c]) +\n                       dfs(r - 1, c, grid[r][c]) +\n                       dfs(r , c + 1, grid[r][c]) +\n                       dfs(r , c - 1, grid[r][c])) % mod;\n  }\n   for(let i = 0; i < rows; i++) {\n    for(let j = 0; j < columns; j++) {\n      result += dfs(i, j, -1) % mod;\n    }\n  }\n\n  return result % mod;\n};",
        "solution_java": "class Solution {\n    long[][] dp;\n    int mod = 1_000_000_007;\n    public int countPaths(int[][] grid) {\n        dp = new long[grid.length][grid[0].length];\n        long sum=0L;\n        for(int i=0;i<grid.length;i++){\n            for(int j=0;j<grid[0].length;j++){\n                sum = (sum + dfs(grid,i,j,0)) % mod;\n            }\n        }\n        return (int)sum;\n    }\n    long dfs(int[][] grid,int i,int j,int pre){\n        if(i<0||j<0||i>=grid.length||j>=grid[0].length) return 0;\n        if(grid[i][j]<=pre) return 0;\n        if(dp[i][j]>0) return dp[i][j];\n        long a = dfs(grid,i+1,j,grid[i][j]);\n        long b = dfs(grid,i,j+1,grid[i][j]);\n        long c = dfs(grid,i-1,j,grid[i][j]);\n        long d = dfs(grid,i,j-1,grid[i][j]);\n        dp[i][j] = (1+a+b+c+d)%mod;\n        return dp[i][j];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = 1000000007;\n    int dx[4] = {1,0,-1,0};\n    int dy[4] = {0,1,0,-1};\n    int countPaths(vector<vector<int>>& grid) {\n        vector <vector <int>> dp(grid.size(),vector<int>(grid[0].size(),-1));\n        long long count = 0;\n        for(int i = 0; i<grid.size(); i++){\n            for(int j = 0; j<grid[0].size(); j++){\n                count = (count%mod + dfs(i,j,grid,dp)%mod)%mod;\n            }\n        }\n        return (int)count%mod;\n    }\nprotected:\n    bool isvalid(int x, int y, vector<vector<int>>&grid){\n        if(x<0 or x>=grid.size() or y<0 or y>=grid[0].size()) return false;\n        return true;\n    }\n    int dfs(int x, int y, vector <vector<int>>&grid,vector <vector<int>>&dp){\n        if(dp[x][y]!=-1) return dp[x][y];\n\n        int ans = 1;\n        for(int i = 0; i<4; i++){\n            if(isvalid(x+dx[i],y+dy[i],grid) and grid[x][y]>grid[x+dx[i]][y+dy[i]]){\n                ans = (ans%mod+dfs(x+dx[i],y+dy[i],grid,dp)%mod)%mod;\n            }\n        }\n        return dp[x][y] = ans%mod;\n    }\n};"
    },
    {
        "title": "Number of Subsequences That Satisfy the Given Sum Condition",
        "algo_input": "You are given an array of integers nums and an integer target.\n\nReturn the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,5,6,7], target = 9\nOutput: 4\nExplanation: There are 4 subsequences that satisfy the condition.\n[3] -&gt; Min value + max value &lt;= target (3 + 3 &lt;= 9)\n[3,5] -&gt; (3 + 5 &lt;= 9)\n[3,5,6] -&gt; (3 + 6 &lt;= 9)\n[3,6] -&gt; (3 + 6 &lt;= 9)\n\n\nExample 2:\n\nInput: nums = [3,3,6,8], target = 10\nOutput: 6\nExplanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]\n\n\nExample 3:\n\nInput: nums = [2,3,3,4,6,7], target = 12\nOutput: 61\nExplanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 106\n\t1 &lt;= target &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def numSubseq(self, nums: List[int], target: int) -> int:\n        nums.sort()\n        left, right = 0, len(nums) - 1\n        count = 0\n        mod = 10 ** 9 + 7\n        \n        while left <= right:\n            if nums[left] + nums[right] > target:\n                right -= 1\n            else:\n                count += pow(2, right - left, mod)\n                left += 1\n        \n        return count % mod",
        "solution_js": "const MOD = 1000000007;\n\nvar numSubseq = function(nums, target) {\n    nums.sort((a, b) => a - b);\n    const len = nums.length;\n    const pow = new Array(len).fill(1);\n    for(let i = 1; i < len; i++) {\n        pow[i] = (pow[i - 1] * 2) % MOD;\n    }\n    let l = 0, r = len - 1, ans = 0;\n    while(l <= r) {\n        if(nums[l] + nums[r] > target) {\n            r--; continue;\n        } else {\n            ans = (ans + pow[r - l]) % MOD;\n            l++;\n        }\n    }\n    return ans % MOD;\n};",
        "solution_java": "class Solution {\n    public int numSubseq(int[] nums, int target) {\n        int n = nums.length;\n        int i =0, j = n-1;\n        int mod = (int)1e9+7;\n        Arrays.sort(nums);\n        int[] pow = new int[n];\n        pow[0]=1;\n        int count =0;\n        for(int z =1;z<n;z++){\n            pow[z] = (pow[z-1]*2)%mod;\n        }\n        \n        while(i<=j){\n            if((nums[i]+nums[j]) <= target){\n                count=(count+pow[j-i])%mod;\n                i++;\n            }\n            else if((nums[i]+nums[j]) > target)\n                j--;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    int mod=1e9+7;\n    int multiply(int a,int b){\n        if(b==0){\n            return 0;\n        } else if(b%2==0){\n            int ans=multiply(a,b/2);\n            return (ans%mod+ans%mod)%mod;\n        } else {\n            int ans=multiply(a,b-1);\n            return (a%mod+ans%mod)%mod;\n        }\n    }\n    int power(int b,int e){\n        if(e==0){\n            return 1;\n        } else if(e%2==0){\n            int ans=power(b,e/2);\n            return multiply(ans,ans);\n        } else {\n            int ans=power(b,e-1);\n            return multiply(b,ans);\n        }\n    }\npublic:\n    int numSubseq(vector<int>& nums, int target) {\n        sort(nums.begin(),nums.end());\n        int start=0,end=0;\n        while(end<nums.size() and nums[start]+nums[end]<=target){\n            end++;\n        }\n        end--;\n        int ans=0;\n        while(start<=end){\n            if(nums[start]+nums[end]<=target){\n                ans=(ans%mod+power(2,end-start))%mod;\n                start++;\n            } else {\n                end--;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Add to Make Parentheses Valid",
        "algo_input": "A parentheses string is valid if and only if:\n\n\n\tIt is the empty string,\n\tIt can be written as AB (A concatenated with B), where A and B are valid strings, or\n\tIt can be written as (A), where A is a valid string.\n\n\nYou are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.\n\n\n\tFor example, if s = \"()))\", you can insert an opening parenthesis to be \"(()))\" or a closing parenthesis to be \"())))\".\n\n\nReturn the minimum number of moves required to make s valid.\n\n&nbsp;\nExample 1:\n\nInput: s = \"())\"\nOutput: 1\n\n\nExample 2:\n\nInput: s = \"(((\"\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts[i] is either '(' or ')'.\n\n",
        "solution_py": "class Solution:\n    def minAddToMakeValid(self, s: str) -> int:\n        stack = []\n\n        for parenthese in s:\n            if parenthese == \"(\":\n                stack.append(\"(\")\n\n            else:\n                if not stack or stack[-1] == \")\":\n                    stack.append(\")\")\n\n                if stack and stack[-1] == \"(\":\n                    stack.pop()\n\n        return len(stack)",
        "solution_js": "var minAddToMakeValid = function(s) {\n    let stack = []\n    let count = 0\n    for(let i=0;i<s.length;i++) {\n        let ch = s[i]\n        if(ch === '(') {\n            stack.push(ch)\n        } else {\n            let top = stack.pop()\n            if(top != '(') count++\n        }\n    }\n\n    count += stack.length\n\n    return count\n};",
        "solution_java": "class Solution {\n    public int minAddToMakeValid(String s) {\n        int open = 0;\n        int extra = 0;\n        for(int i=0;i<s.length();i++){\n            if(s.charAt(i)=='('){\n                open++;\n            }else{\n                if(open==0){\n                    extra++;\n                }else{\n                    open--;\n                }\n            }\n        }\n        return open+extra;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minAddToMakeValid(string s) {\n        stack<char> sta;\n        int nums = 0;\n        for (int i = 0; i < s.size(); i++)\n        {\n            if (s[i] == '(')\n            {\n                sta.push(s[i]);\n            }\n            else\n            {\n                if (!sta.empty())\n                {\n                    sta.pop();\n                }\n                else\n                {\n                    nums++;\n                }\n            }\n        }\n        nums += sta.size();\n        return nums;\n    }\n};"
    },
    {
        "title": "Increasing Triplet Subsequence",
        "algo_input": "Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i &lt; j &lt; k and nums[i] &lt; nums[j] &lt; nums[k]. If no such indices exists, return false.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: Any triplet where i &lt; j &lt; k is valid.\n\n\nExample 2:\n\nInput: nums = [5,4,3,2,1]\nOutput: false\nExplanation: No triplet exists.\n\n\nExample 3:\n\nInput: nums = [2,1,5,0,4,6]\nOutput: true\nExplanation: The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 105\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n\n&nbsp;\nFollow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?",
        "solution_py": "class Solution:\n    def increasingTriplet(self, nums: List[int]) -> bool:\n        first = second = float('inf')\n        for n in nums:\n            if n <= first:\n                first = n\n            elif n <= second:\n                second = n\n            else:\n                return True\n        return False",
        "solution_js": "var increasingTriplet = function(nums) {\n    const length = nums.length, arr = [];\n    let tripletFound = false, arrLength, added = false, found = false;\n    if(length < 3) return false;\n    arr.push([nums[0],1]);\n    for(let index = 1; index < length; index++) {\n        let count = 1;\n        added = false;\n        found = false;\n        arrLength = arr.length;\n        for(let index2 = 0; index2 < arrLength; index2++) {\n            if(arr[index2][0] < nums[index]) {\n                added = true;\n                if(count !== arr[index2][1]+1) {\n                    count = arr[index2][1]+1;\n                    if(JSON.stringify(arr[index2+1]) !== JSON.stringify([nums[index],count]))\n                        arr.push([nums[index],count]);\n                }\n                if(arr[index2][1]+1 === 3) {\n                    tripletFound = true;\n                    break;\n                }\n            }\n            if(arr[index2][0] === nums[index]) found = true;\n        }\n        if(tripletFound) break;\n        if(!added && !found) {\n                arr.push([nums[index],1]);\n            }\n    }\n    return tripletFound;\n};",
        "solution_java": "class Solution {\n    public boolean increasingTriplet(int[] nums) {\n        if(nums.length < 3)\n            return false;\n        \n        int x = Integer.MAX_VALUE;\n        int y = Integer.MAX_VALUE;\n        \n        for (int i : nums){\n            if(i <= x){\n                x = i;\n            }else if (i <= y)\n                y = i;\n            else \n                return true;\n        }\n        \n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool increasingTriplet(vector<int>& nums) {\n        int n = nums.size();\n        int smallest = INT_MAX;\n        int second_smallest = INT_MAX;\n        for(int i = 0;i<n;i++)\n        {\n            if(nums[i] <= smallest)\n            {\n                smallest = nums[i];\n            }\n            else if(nums[i] <= second_smallest)\n            {\n                second_smallest = nums[i];\n            }\n            else\n            {\n                return true;\n            }\n        }\n\n        return false;\n    }\n};"
    },
    {
        "title": "Duplicate Zeros",
        "algo_input": "Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.\n\nNote that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,0,2,3,0,4,5,0]\nOutput: [1,0,0,2,3,0,0,4]\nExplanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]\n\n\nExample 2:\n\nInput: arr = [1,2,3]\nOutput: [1,2,3]\nExplanation: After calling your function, the input array is modified to: [1,2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t0 &lt;= arr[i] &lt;= 9\n\n",
        "solution_py": "class Solution:\n    def duplicateZeros(self, arr: List[int]) -> None:\n        \"\"\"\n        Do not return anything, modify arr in-place instead.\n        \"\"\"\n        l = len(arr)\n        i,c=0,0\n        while i<l:\n            if arr[i]==0:\n                arr.insert(i+1,0)\n                i+=1\n                arr.pop()\n            i+=1",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {void} Do not return anything, modify arr in-place instead.\n */\nvar duplicateZeros = function(arr) {\n    // Variables\n    const originalLength = arr.length;\n    \n    // Iterate over all the numbers in 'arr', if the number is 0 we duplicate it and skip the next loop iteration to prevent an overflow.\n    for (let idx = 0; idx < arr.length; idx ++)\n    {\n      const number = arr[idx];\n      if (number === 0 )\n      {\n        arr.splice(idx, 0, 0);\n        idx += 1;\n      };\n    };\n    \n    // Here we restore the array to its original length.\n    return (arr.length = originalLength);\n};",
        "solution_java": "class Solution {\n    \n    //  Time Complexity = O(n)\n    //  Space Complexity = O(1)\n    \n    public void duplicateZeros(int[] arr) {\n        \n        //  Loop through the array\n        for(int i = 0; i < arr.length; i++) {\n        \n        //  Trigger Condition     \n            if(arr[i] ==0) {\n                int j;      // auxilliary variable for swapping \n                for(j = arr.length-2; j>=i+1; j--) {\n                    arr[j+1] = arr[j];      //  Shift each element by one space\n                }\n                arr[j+1] = 0;               //  Duplicating the zero on the consecutive index of i\n                i++;                        //  Skipping the duplicated zero index in the array \n            }\n        }\n    }       \n}",
        "solution_c": "class Solution {\npublic:\n    void duplicateZeros(vector<int>& arr) {\n        for(int i=0;i<arr.size();i++)\n        {\n          if(arr[i]==0)\n          {\n              arr.pop_back();\n              arr.insert(arr.begin()+i,0);\n              i++;\n          }\n            }\n\n    }\n};"
    },
    {
        "title": "Unique Number of Occurrences",
        "algo_input": "Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,2,1,1,3]\nOutput: true\nExplanation:&nbsp;The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n\nExample 2:\n\nInput: arr = [1,2]\nOutput: false\n\n\nExample 3:\n\nInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length&nbsp;&lt;= 1000\n\t-1000 &lt;= arr[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def uniqueOccurrences(self, arr: List[int]) -> bool:\n\t\t# defining dictionary\n        occ = dict()\n        \n\t\t# adding elements with their counts in dictionary\n        for element in arr:\n            if element not in occ:\n                occ[element] = 0\n            else:\n                occ[element] += 1\n        \n\t\t# list of count of elements\n        values = list(occ.values())\n\t\t# Unique count\n        unique = set(values)\n        \n        if len(values) == len(unique):\n            return True\n        else:\n            return False",
        "solution_js": "var uniqueOccurrences = function(arr) {\n    const obj = {};\n//     Creating hashmap to store count of each number\n    arr.forEach(val => obj[val] = (obj[val] || 0) + 1);\n//     Creating an array of the count times\n    const val = Object.values(obj).sort((a, b) => a-b);\n//     Now, just finding the duplicates\n    for(let i = 0; i<val.length-1; i++){\n        if(val[i]===val[i+1]) return false;\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean uniqueOccurrences(int[] arr) {\n        Arrays.sort(arr);\n        HashSet<Integer> set = new HashSet<>();\n\n        int c = 1;\n        for(int i = 1; i < arr.length; i++)\n        {\n            if(arr[i] == arr[i-1]) c++;\n\n            else\n            {\n                if(set.contains(c)) return false;\n\n                set.add(c);\n\n                c = 1;\n            }\n        }\n\n        if(set.contains(c)) return false;\n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool uniqueOccurrences(vector<int>& arr) {\n        unordered_map<int,int>sk;\n        unordered_map<int,int>skk;\n        for(int i=0;i<arr.size();i++){\n            sk[arr[i]]++;\n        }\n         for(auto j : sk)\n        {\n            if(skk[j.second]==1){\n                return false;\n            }\n            skk[j.second]++;\n        }\n\n        return true;\n    }\n};"
    },
    {
        "title": "Flower Planting With No Adjacent",
        "algo_input": "You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.\n\nAll gardens have at most 3 paths coming into or leaving it.\n\nYour task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.\n\nReturn any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, paths = [[1,2],[2,3],[3,1]]\nOutput: [1,2,3]\nExplanation:\nGardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].\n\n\nExample 2:\n\nInput: n = 4, paths = [[1,2],[3,4]]\nOutput: [1,2,1,2]\n\n\nExample 3:\n\nInput: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\nOutput: [1,2,3,4]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= paths.length &lt;= 2 * 104\n\tpaths[i].length == 2\n\t1 &lt;= xi, yi &lt;= n\n\txi != yi\n\tEvery garden has at most 3 paths coming into or leaving it.\n\n",
        "solution_py": "class Solution:\n\tdef gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n\t\tg = defaultdict(list)\n\t\tfor u,v in paths:\n\t\t\tg[u-1].append(v-1)            \n\t\t\tg[v-1].append(u-1) \n\t\tans = [0]*n\n\t\tfor i in range(n):\n\t\t\tc = [1,2,3,4]\n\t\t\tfor j in g[i]:\n\t\t\t\tif ans[j] in c: c.remove(ans[j])\n\t\t\tans[i] = c.pop()\n\t\treturn ans",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} paths\n * @return {number[]}\n */\nvar gardenNoAdj = function(n, paths) {\n    //if n is less than or equal to four just return an array of size n from 1 to n\n    if(n <= 4){\n        let arr = []\n        let count = 1\n        while(arr.length < n){\n            arr.push(count)\n            count++\n        }\n        return arr\n    }\n    //if there are no gardens connecting to each other then just return an array of size n with ones\n    if(paths.length === 0)return new Array(n).fill(1)\n\n    //because we have three possible paths connecting to gardens and 4 flowers we know that this problems is possible because our graph is of degree 3 and we have D + 1 flowers\n    //to solve\n    let adjList = {}\n    // create an array filled with ones so if there is a garden with no path just fill with one\n    let result = new Array(n).fill(1)\n    let garden = new Set([1,2,3,4])\n\n    //create adj list from the paths\n    paths.forEach(path => {\n        let first = path[0];\n        let second = path[1];\n\n        if(first in adjList )adjList[first].neighbors.add(second)\n        else {adjList[first] = new Fnode(second)}\n\n        if(second in adjList)adjList[second].neighbors.add(first)\n        else {adjList[second] = new Fnode(first)}\n\n    })\n\n    for(let node in adjList){\n        //every node\n        let current = adjList[node]\n\n        //create a set of invalid flowers, flowers you can't use because they are part of\n        //the other gardens this one is connected to.\n        let invalidFlower = new Set();\n\n        //iterate over the neighbors to find what type of flower they have and if it is not\n        //null included in the invalid flowers set\n        current.neighbors.forEach(neighbor => {\n            if(adjList[neighbor]['flower'] !== null){\n                invalidFlower.add(adjList[neighbor]['flower'])\n            }\n        })\n\n        //create our possible value or better said our value because we will use the first one\n        //we obtain.\n        let possibleFlower;\n\n        //we iterate over over our garden {1,2,3,4}\n        for(let flower of garden) {\n            //and if our flower is not part of the invalid flowers;\n            if(!invalidFlower.has(flower)){\n                //we have found a possible flower we can use\n                possibleFlower = flower\n                //we break because this is the only one we need\n                break;\n            }\n        }\n        // we add our flower to current so that we dont use it in the future\n        current.flower = possibleFlower\n\n        //and update our result\n        result[node - 1] = possibleFlower\n    }\n    //we return our result\n    return result\n\n};\n\n//create a Flower class just for simplicity\nclass Fnode{\n    constructor(neighbor){\n        this.flower = null\n        this.neighbors = new Set([neighbor])\n    }\n}",
        "solution_java": "class Solution {\n    public int[] gardenNoAdj(int n, int[][] paths) {\n        boolean[][] graph = new boolean[n][n];\n        for(int i = 0;i<paths.length;i++){\n            int u = paths[i][0]-1;\n            int v = paths[i][1]-1;\n            graph[u][v] = true;\n            graph[v][u] = true;\n        }\n        int[] colored = new int[n];\n        boolean[] available = new boolean[4];\n        Arrays.fill(colored,-1);\n        colored[0] = 1;\n        for(int i = 1;i<n;i++){\n            for(int j = 0;j<n;j++){\n                if(graph[i][j] && colored[j]!=-1){\n                    available[colored[j]-1]=true;\n                }\n            }\n            int k,flag = 0;\n            for(k = 0;k<4;k++){\n                if(available[k]==false){\n                    flag = 1;\n                    break;\n                }\n            }\n            colored[i] = k+1;\n            Arrays.fill(available,false);\n        }\n        return colored;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int check(vector<int> a[],vector<int> &col,int sv,int i)\n    {\n        for(auto it:a[sv])\n        {\n            if(col[it]==i)return 0;\n        }\n        return 1;\n    }\n    \n    void dfs(vector<int> a[],vector<int> &col,int sv,int lc)\n    {\n        for(int i = 1;i<5;i++)\n        {\n            if(check(a,col,sv,i))\n            {\n                col[sv] = i;\n                break;\n            }\n        }\n        for(auto it:a[sv])\n        {\n            if(col[it]==-1)\n            {\n                dfs(a,col,it,col[sv]);\n            }\n        }\n    }\n    vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) {\n        vector<int> a[n];\n        for(auto it:paths)\n        {\n            a[it[0]-1].push_back(it[1]-1);\n            a[it[1]-1].push_back(it[0]-1);\n        }\n        \n        vector<int> col(n,-1);\n        for(int i = 0;i<n;i++)\n        {\n            if(col[i]==-1)\n            {\n                dfs(a,col,i,-7);\n            }\n        }\n        return col;\n    }\n};"
    },
    {
        "title": "Minimum Amount of Time to Fill Cups",
        "algo_input": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.\n\nYou are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.\n\n&nbsp;\nExample 1:\n\nInput: amount = [1,4,2]\nOutput: 4\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.\n\n\nExample 2:\n\nInput: amount = [5,4,4]\nOutput: 7\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.\n\n\nExample 3:\n\nInput: amount = [5,0,0]\nOutput: 5\nExplanation: Every second, we fill up a cold cup.\n\n\n&nbsp;\nConstraints:\n\n\n\tamount.length == 3\n\t0 &lt;= amount[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def fillCups(self, amount: List[int]) -> int:\n\n        count = 0\n        amount = sorted(amount, reverse=True)\n        while amount[0] > 0:\n            amount[0] -= 1\n            amount[1] -= 1\n            count += 1\n            amount = sorted(amount, reverse=True)\n        return count",
        "solution_js": "var fillCups = function(amount) {\n    var count = 0\n    var a = amount\n    while (eval(a.join(\"+\")) > 0) {\n        var max = Math.max(...a)\n        a.splice(a.indexOf(max), 1)\n        var max2 = Math.max(...a)\n        a.splice(a.indexOf(max2), 1)\n        count++\n        if(max == 0) a.push(0)\n        else a.push(max - 1)\n        if (max2==0) a.push(0)\n        else a.push(max2 - 1)\n    } return count\n}",
        "solution_java": "class Solution {\n    public int fillCups(int[] amount) {\n         Arrays.sort(amount);\n        int x=amount[0];\n         int y=amount[1];\n         int z=amount[2];\n        int sum=x+y+z;\n        if(x+y>z){return sum/2 +sum%2;}\n        if(x==0&&y==0){return z;}\n        else{return z;}\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int fillCups(vector<int>& amount) {\n      sort(amount.begin(),amount.end());\n      int x=amount[0];\n      int y=amount[1];\n      int z=amount[2];\n      int sum=x+y+z;\n      if(x+y>z) return sum/2+sum%2;\n      if(x==0 && y==0) return z;\n      else return z;\n    }\n};"
    },
    {
        "title": "Grumpy Bookstore Owner",
        "algo_input": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.\n\nOn some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.\n\nWhen the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.\n\nThe bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.\n\nReturn the maximum number of customers that can be satisfied throughout the day.\n\n&nbsp;\nExample 1:\n\nInput: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput: 16\nExplanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.\n\n\nExample 2:\n\nInput: customers = [1], grumpy = [0], minutes = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tn == customers.length == grumpy.length\n\t1 &lt;= minutes &lt;= n &lt;= 2 * 104\n\t0 &lt;= customers[i] &lt;= 1000\n\tgrumpy[i] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def recursion(self,index,used):\n        # base case\n        if index == self.n: return 0\n        \n        #check in dp\n        if (index,used) in self.dp: return self.dp[(index,used)]\n        #choice1 is using the secret technique\n        choice1 = -float('inf')\n        \n        # we can only use secret technique once and consecutively\n        if used == True :\n            # use the secret technique\n            end = index + self.minutes if index + self.minutes < self.n else self.n\n            to_substract = self.prefix_sum[index - 1] if index != 0 else 0\n            val = self.prefix_sum[end - 1] - to_substract\n            choice1 = self.recursion(end,False) + val\n        \n        # Do not use the secret tehcnique and play simple \n        choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)\n        ans = choice1 if choice1 > choice2 else choice2\n        \n        # Memoization is done here\n        self.dp[(index,used)] = ans\n        return ans\n    \n    def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n        self.n = len(customers)\n        self.customers = customers\n        self.grumpy = grumpy\n        self.minutes = minutes\n        self.dp = {}\n        self.prefix_sum = [x for x in customers]\n        for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]\n        return self.recursion(0,True)\n        ",
        "solution_js": "var maxSatisfied = function(customers, grumpy, minutes) {\n    let left=0;\n    let maxUnsatisfied=0;\n    let curr=0;\n    let satisfied=0;\n    \n\t// finding the satisfied customers\n    for(let i=0;i<customers.length;i++){\n        if(grumpy[i]===0)satisfied+=customers[i];\n    }\n    \n    // finding the maximum un-satisfied customers within the give timeframe\n\t// classic sliding window approach\n    for(let i=0;i<customers.length;i++){\n        if(grumpy[i]) curr+=customers[i];\n        if(i-left+1>minutes){\n            if(grumpy[left])curr-=customers[left]\n            left++\n        }   \n        if(i-left+1===minutes){\n            if(curr>max){\n                maxUnsatisfied=curr\n            }\n        }\n    }\n\t\n    return satisfied + maxUnsatisfied;\n};",
        "solution_java": "class Solution {\n    public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n        int start = -1;\n        int count = 0;\n        \n        int max = 0;\n        int curr = 0;\n        \n        for (int i = 0; i < customers.length; i++) {\n            if (grumpy[i] == 0) {\n                count += customers[i];\n            } else {\n                curr += customers[i];\n            }\n            \n            if (i-start > minutes) {\n                start++;\n                if (grumpy[start] == 1) {\n                    curr -= customers[start];\n                }\n            }\n            max = Math.max(max, curr);\n        }\n        \n        return count + max;\n    }\n}",
        "solution_c": "/*\n    https://leetcode.com/problems/grumpy-bookstore-owner/\n    \n    TC: O(N)\n    SC: O(1)\n    \n    Looking at the problem, main thing to find is the window where the minutes should\n    be used so that the owner is not grumpy and max customers in that window can be satisifed.\n    \n    Find the window with most no. of satisfied customers given the owner was originally grumpy but\n    now has become not grumpy.\n    Since the owner can only be not grumpy for minutes duration, this sets our window size as well.\n    So with 'minutes' window size, find the max window.\n    \n    Then add the max window value with the normal satisfied customers.\n*/\nclass Solution {\npublic:\n    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {\n        // Tracks the max window where being not grumpy will add most customers and current grumpy window customers\n        int max_grumpy_window = 0, grumpy_window = 0;\n        int curr = 0, n = customers.size();\n        // Total satisifed customers when owner is not grumpy\n        int satisfied_cx = 0;\n        // net effective duration of not being grumpy\n        minutes = min(minutes, n);\n        \n        // process the 1st window\n        while(curr < minutes) {\n            satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);\n            grumpy_window += (grumpy[curr] ? customers[curr] : 0);\n            ++curr;\n        }\n        \n        max_grumpy_window = max(max_grumpy_window, grumpy_window);\n        // process the remaining windows\n        while(curr < n) {\n            // Remove the 1st element of last window\n            grumpy_window -= (grumpy[curr - minutes] ? customers[curr - minutes] : 0);\n            // Add the latest element of current window\n            grumpy_window += (grumpy[curr] ? customers[curr] : 0);\n            max_grumpy_window = max(max_grumpy_window, grumpy_window);\n            \n            satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);\n            ++curr;\n        }\n        \n        return satisfied_cx + max_grumpy_window;\n    }\n};"
    },
    {
        "title": "Number of 1 Bits",
        "algo_input": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n\nNote:\n\n\n\tNote that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\n\tIn Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.\n\n\n&nbsp;\nExample 1:\n\nInput: n = 00000000000000000000000000001011\nOutput: 3\nExplanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.\n\n\nExample 2:\n\nInput: n = 00000000000000000000000010000000\nOutput: 1\nExplanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.\n\n\nExample 3:\n\nInput: n = 11111111111111111111111111111101\nOutput: 31\nExplanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe input must be a binary string of length 32.\n\n\n&nbsp;\nFollow up: If this function is called many times, how would you optimize it?",
        "solution_py": "class Solution:\n    def hammingWeight(self, n: int) -> int:\n      i = 0\n      while n > 0:\n        if n % 2 != 0: i += 1\n        n = n >> 1\n      return i",
        "solution_js": "var hammingWeight = function(n) {\n    let count = 0, i = 0;\n    while(n > 0) {\n        i = 0;\n        while(n >= Math.pow(2,i)) {\n            i++;\n        }\n        count++;\n        n -= Math.pow(2,i-1);\n    }\n    return count;\n};",
        "solution_java": "public class Solution {\n    // you need to treat n as an unsigned value\n    public int hammingWeight(int n) {\n        return Integer.bitCount(n);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int hammingWeight(uint32_t n) {\n      int ans=0;\n      while(n!=0){\n        n=n&(n-1);\n        ans++;\n      }\n      return ans;  \n    }\n};"
    },
    {
        "title": "Sort Colors",
        "algo_input": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n\nWe will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.\n\nYou must solve this problem without using the library's sort function.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\n\nExample 2:\n\nInput: nums = [2,0,1]\nOutput: [0,1,2]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 300\n\tnums[i] is either 0, 1, or 2.\n\n\n&nbsp;\nFollow up:&nbsp;Could you come up with a one-pass algorithm using only&nbsp;constant extra space?\n",
        "solution_py": "class Solution:\n    def sortColors(self, nums: List[int]) -> None:\n\n        red, white, blue = 0, 0, len(nums) - 1\n\n        while white <= blue:\n            if nums[white] == 0:\n                nums[white], nums[red] = nums[red], nums[white]\n                red += 1\n                white += 1\n            elif nums[white] == 1:\n                white += 1\n            else:\n                nums[white], nums[blue] = nums[blue], nums[white]\n                blue -= 1",
        "solution_js": "var sortColors = function(nums) {\n    let map = {\n        '0': 0,\n        '1': 0,\n        '2': 0\n    };\n    for(let char of nums) {\n        map[char] = map[char] + 1;\n    }\n    let values = Object.values(map);\n    let curr = 0;\n    for(let k=0; k<values.length; k++) {\n        for(let i=curr; i<curr+values[k]; i++) {\n            nums[i] = k;\n        }\n        curr = curr + values[k];\n    }\n};",
        "solution_java": "class Solution {\n\n  public void sortColors(int[] nums) {\n\n    int zeroIndex = 0, twoIndex = nums.length - 1, i = 0;\n    while (i <= twoIndex) {\n      if (nums[i] == 0)\n        swap(nums, zeroIndex++, i++);\n      else if (nums[i] == 2)\n        swap(nums, twoIndex--, i);\n      else\n        i++;\n    }\n  }\n\n  public void swap(int[] nums, int i, int j) {\n    int temp = nums[i];\n    nums[i] = nums[j];\n    nums[j] = temp;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    void sortColors(vector<int>& nums) {\n        int a =0; int b=0,c=0;int i;\n        for(i=0;i<nums.size();i++){\n            if(nums[i]==0){\n                a++;\n            }\n            if(nums[i]==1){\n                b++;\n            }\n            else c++;\n            \n        }\n        for(i=0;i<nums.size();i++){\n            if(i<a){\n                nums[i]=0;\n            }\n            else if(i<a+b){\n                nums[i]=1;\n            }\n            else nums[i]=2;\n        }\n      \n    }\n};"
    },
    {
        "title": "Reverse Prefix of Word",
        "algo_input": "Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.\n\n\n\tFor example, if word = \"abcdefd\" and ch = \"d\", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be \"dcbaefd\".\n\n\nReturn the resulting string.\n\n&nbsp;\nExample 1:\n\nInput: word = \"abcdefd\", ch = \"d\"\nOutput: \"dcbaefd\"\nExplanation:&nbsp;The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".\n\n\nExample 2:\n\nInput: word = \"xyxzxe\", ch = \"z\"\nOutput: \"zxyxxe\"\nExplanation:&nbsp;The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".\n\n\nExample 3:\n\nInput: word = \"abcd\", ch = \"z\"\nOutput: \"abcd\"\nExplanation:&nbsp;\"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 250\n\tword consists of lowercase English letters.\n\tch is a lowercase English letter.\n\n",
        "solution_py": "class Solution:\n    def reversePrefix(self, word: str, ch: str) -> str:\n        idx=word.find(ch)\n        if idx:\n            return word[:idx+1][::-1]+ word[idx+1:]\n        return word",
        "solution_js": "var reversePrefix = function(word, ch) {\n    return word.indexOf(ch) !== -1 ? word.split(\"\").slice(0, word.indexOf(ch) + 1).reverse().join(\"\") + word.slice(word.indexOf(ch) + 1) : word;\n};",
        "solution_java": "class Solution {\n    public String reversePrefix(String word, char ch) {\n        char[] c = word.toCharArray();\n        int locate = 0;\n        for (int i = 0; i < word.length(); i++) { //first occurrence of ch\n            if (ch == c[i]) {\n                locate = i;\n                break;\n            }\n        }\n        char[] res = new char[word.length()];\n        for (int i = 0; i <= locate; i++) {\n            res[i] = c[locate - i];\n        }\n        for (int i = locate + 1; i < word.length(); i++) {\n            res[i] = c[i];\n        }\n        return String.valueOf(res);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reversePrefix(string word, char ch) {\n        string ans = \"\";\n        int tr = true;\n        for(auto w : word){\n            ans.push_back(w);\n            if(tr && w == ch){\n                tr=false;\n                reverse(ans.begin(), ans.end());\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Score Triangulation of Polygon",
        "algo_input": "You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).\n\nYou will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.\n\nReturn the smallest possible total score that you can achieve with some triangulation of the polygon.\n\n&nbsp;\nExample 1:\n\nInput: values = [1,2,3]\nOutput: 6\nExplanation: The polygon is already triangulated, and the score of the only triangle is 6.\n\n\nExample 2:\n\nInput: values = [3,7,4,5]\nOutput: 144\nExplanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\nThe minimum score is 144.\n\n\nExample 3:\n\nInput: values = [1,3,1,4,1,5]\nOutput: 13\nExplanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == values.length\n\t3 &lt;= n &lt;= 50\n\t1 &lt;= values[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minScoreTriangulation(self, values: List[int]) -> int:\n        \n        n = len(values)\n        \n        c = [[0 for _ in range(n)] for _ in range(n)]\n        \n        for L in range(2, n):\n            \n            for i in range(1, n-L+1):\n                \n                j = i + L - 1\n                \n                c[i][j] = float('inf')\n                \n                for k in range(i, j):\n                    \n                    q = c[i][k] + c[k+1][j] + (values[i-1]*values[k]*values[j])\n                    \n                    if c[i][j] > q:\n                        c[i][j] = q\n        \n        return c[1][n-1]\n                \n                \n        \n            \n        ",
        "solution_js": "var minScoreTriangulation = function(values) {\n    let dp = Array(values.length).fill().map((i) => Array(values.length).fill(0));\n    function dfs(i, j) {\n        if (dp[i][j]) return dp[i][j];\n        if (j - i < 2) return 0;\n        let min = Infinity;\n        // k forms a triangle with i and j, thus bisecting the array into two parts\n        // These two parts become two subproblems that can be solved recursively\n        for (let k = i + 1; k < j; k++) {\n            let sum = values[i] * values[j] * values[k] + dfs(i, k) + dfs(k, j);\n            min = Math.min(min, sum);\n        }\n        return dp[i][j] = min;\n    }\n    return dfs(0, values.length - 1);\n};",
        "solution_java": "class Solution {\n    int solve(int[] v, int i, int j){\n        if(i+1==j)\n            return 0;\n        int ans= Integer.MAX_VALUE;\n        for(int k=i+1;k<j;k++){\n            ans= Math.min(ans, (v[i]*v[j]*v[k] + solve(v,i,k) + solve(v,k,j) ) );\n        }\n        return ans;\n    }\n\n    int solveMem(int[] v, int i, int j, int[][] dp){\n      if(i+1==j)\n            return 0;\n\n        if(dp[i][j]!=-1)\n            return dp[i][j];\n\n       int ans= Integer.MAX_VALUE;\n\n        for(int k=i+1;k<j;k++){\n          ans = Math.min(ans, (v[i]*v[j]*v[k] + solveMem(v,i,k,dp) + solveMem(v,k,j,dp) ) );\n        }\n        dp[i][j]=ans;\n        return dp[i][j];\n    }\n\n    int solveTab(int[] v){\n        int n= v.length;\n        int[][] dp= new int[n][n];\n\n        for(int i=n-1;i>=0;i--){\n            for(int j=i+2;j<n;j++){\n\n                int ans=Integer.MAX_VALUE;\n                 for(int k=i+1;k<j;k++){\n                    ans = Math.min(ans, (v[i]*v[j]*v[k] + dp[i][k] + dp[k][j] ) );\n                    }\n                    dp[i][j]=ans;\n            }\n        }\n\n        return dp[0][n-1];\n\n        }\n\n    public int minScoreTriangulation(int[] values) {\n        int n= values.length;\n       // return solve(values, 0, n-1); // For Recursion\n\n    /* int[][] dp= new int[n][n]; // For Top-Down DP(Memoisation)\n        for(int[] row:dp){\n            Arrays.fill(row,-1);\n        }\n\n        return solveMem(values,0,n-1,dp);\n        */\n\n        return solveTab(values); //For Bottom-Down DP(Tabulisation)\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint f(int i,int j,vector<int>& values,vector<vector<int>> &dp){\n\t\tif(i == j || i+1 == j)    return 0;\n\t\tif(dp[i][j] != -1)        return dp[i][j];\n\t\tint res = INT_MAX;\n\t\tfor(int k = i+1;k < j;k++)\n\t\t{\n\t\t\tint temp = values[i]*values[j]*values[k] + f(k,j,values,dp) + f(i,k,values,dp);\n\t\t\tres = min(res,temp);\n\t\t}\n\t\treturn dp[i][j] = res;\n\t}\n\n\tint minScoreTriangulation(vector<int>& values) {\n\t\tint n = values.size();\n\t\tvector<vector<int>> dp(n+1,vector<int>(n+1,-1));\n\t\treturn f(0,n - 1,values,dp);\n\t}"
    },
    {
        "title": "Smallest Integer Divisible by K",
        "algo_input": "Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.\n\nReturn the length of n. If there is no such n, return -1.\n\nNote: n may not fit in a 64-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: k = 1\nOutput: 1\nExplanation: The smallest answer is n = 1, which has length 1.\n\n\nExample 2:\n\nInput: k = 2\nOutput: -1\nExplanation: There is no such positive integer n divisible by 2.\n\n\nExample 3:\n\nInput: k = 3\nOutput: 3\nExplanation: The smallest answer is n = 111, which has length 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def smallestRepunitDivByK(self, k: int) -> int:\n        if k % 2 == 0: return -1\n        n = 1\n        leng = 1\n        mapp = {}\n        while True:\n            rem = n % k\n            if rem == 0: return leng\n            if rem in mapp : return -1\n            mapp[rem] = True\n            n = n*10 + 1\n            leng += 1\n        ",
        "solution_js": "/**\n * @param {number} k\n * @return {number}\n */\nvar smallestRepunitDivByK = function(k) {\n    if( 1 > k > 1e6 ) return -1;\n    let val = 0;\n    for (let i = 1; i < 1e6; i++) {\n        val = (val * 10 + 1) % k;\n        if (val === 0) return i;\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int smallestRepunitDivByK(int k) {\n        // if (k % 2 == 0 || k % 5 == 0) return -1;  // this trick may save a little time\n        boolean[] hit = new boolean[k];\n        int n = 0, ans = 0;\n        while (true) { // at most k times, because 0 <= remainder < k\n            ++ ans;\n            n = (n * 10 + 1) % k; // we only focus on whether to divide, so we only need to keep the remainder.\n            if (n == 0) return ans; // can be divisible\n            if (hit[n]) return -1; // the remainder of the division repeats, so it starts to loop that means it cannot be divisible.\n            hit[n] = true;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int smallestRepunitDivByK(int k) {\n        if(k&1==0)return -1;\n        long long val=0;\n\n        for(int i=1; i<=k;i++)\n        {\n            // val=((val*10)+1);\n            if((val=(val*10+1)%k)==0)return i;\n        }\n        return -1;\n        \n        \n        \n    }\n};"
    },
    {
        "title": "Kth Smallest Element in a BST",
        "algo_input": "Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,1,4,null,2], k = 1\nOutput: 1\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,null,1], k = 3\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t1 &lt;= k &lt;= n &lt;= 104\n\t0 &lt;= Node.val &lt;= 104\n\n\n&nbsp;\nFollow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n        n=0\n        stack=[] # to store the elements\n        cur=root # pointer to iterate\n        while cur or stack:\n            while cur: # used to find the left most element\n                stack.append(cur)\n                cur=cur.left\n            cur=stack.pop() # pop the most recent element which will be the least value at that moment\n            n+=1\n            if n==k:\n                return cur.val\n            cur=cur.right",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} k\n * @return {number}\n */\nvar kthSmallest = function(root, k) {\n    let stack = [];\n    while(root != null || stack.length > 0) {\n        while(root != null){\n            stack.push(root);\n            root = root.left\n        }\n        root = stack.pop();\n        if(--k == 0) break;\n        root = root.right;\n    };\n\n    return root.val;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    int element,count;\n    \n    public int kthSmallest(TreeNode root, int k) {\n        inorderTraversal(root,k);\n        return element;\n    }\n    \n    \n    public void inorderTraversal(TreeNode root,int k){\n        if(root.left != null){\n            inorderTraversal(root.left,k);\n        }\n        count++;\n        if(count==k){\n            element = root.val;\n        }\n        \n        if(root.right != null){\n            inorderTraversal(root.right,k);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void findInorder(TreeNode* root, vector<int> &ans) {\n        if(root == NULL)\n            return;\n\n        findInorder(root->left, ans);\n        ans.push_back(root->val);\n        findInorder(root->right, ans);\n    }\n    int kthSmallest(TreeNode* root, int k) {\n        vector<int> ans;\n        findInorder(root, ans);\n        return ans[k-1];\n    }\n};"
    },
    {
        "title": "Find the Smallest Divisor Given a Threshold",
        "algo_input": "Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.\n\nEach result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).\n\nThe test cases are generated so&nbsp;that there will be an answer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,5,9], threshold = 6\nOutput: 5\nExplanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). \n\n\nExample 2:\n\nInput: nums = [44,22,33,11,1], threshold = 5\nOutput: 44\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t1 &lt;= nums[i] &lt;= 106\n\tnums.length &lt;= threshold &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def helper(self,nums,m):\n        Sum = 0\n        for n in nums:\n            Sum += math.ceil(n/m)\n        return Sum\n    \n    def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n        l,r = 1, max(nums)\n        while l < r:\n            mid = (l+r)//2\n            Sum = self.helper(nums,mid)\n            if Sum > threshold:\n                l = mid + 1\n            else:\n                r = mid     \n        return r",
        "solution_js": "var smallestDivisor = function(nums, threshold) {\n    let left = 1;\n    let right = nums.reduce((r, x) => Math.max(r, x), 0);\n    \n    while (left <= right) {\n        const div = Math.floor((left + right) / 2);\n        const sum = nums.reduce((r, x) => r + Math.ceil(x / div), 0);\n        \n        if (sum <= threshold) {\n            right = div - 1;\n        } else {\n            left = div + 1;\n        }\n    }\n    \n    return left;\n};",
        "solution_java": "class Solution {\n    public int smallestDivisor(int[] a, int h) {\n        int l = 1, r = a[0];\n        for (int x : a) if (x > r) r = x;\n\n        while (l < r) {\n            int m = l + (r-l)/2;\n            if (valid(a, m, h)) r = m;\n            else l = m + 1;\n        }\n\n        return l;\n    }\n\n    private boolean valid(int[] a, int m, int h) {\n        for (int x : a)\n            if ((h -= (x + m-1)/m) < 0) return false;\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int smallestDivisor(vector<int>& nums, int threshold) {\n        int l=1,r=0;\n        for(int n:nums)r=max(r,n);\n\n        int mid,s=0;\n        while(l<r){\n            s=0;\n            mid = l+(r-l)/2;\n            for(int n:nums){\n                s+= n/mid + (n%mid !=0);\n            }\n            if(s<= threshold){\n                r=mid;\n            }else{\n                l=mid+1;\n            }\n\n        }\n        return r;\n    }\n};"
    },
    {
        "title": "Short Encoding of Words",
        "algo_input": "A valid encoding of an array of words is any reference string s and array of indices indices such that:\n\n\n\twords.length == indices.length\n\tThe reference string s ends with the '#' character.\n\tFor each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].\n\n\nGiven an array of words, return the length of the shortest reference string s possible of any valid encoding of words.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"time\", \"me\", \"bell\"]\nOutput: 10\nExplanation: A valid encoding would be s = \"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"\n\n\nExample 2:\n\nInput: words = [\"t\"]\nOutput: 2\nExplanation: A valid encoding would be s = \"t#\" and indices = [0].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 2000\n\t1 &lt;= words[i].length &lt;= 7\n\twords[i] consists of only lowercase letters.\n\n",
        "solution_py": "class Solution:\n    def minimumLengthEncoding(self, words):\n        \n        \n        # root of suffix trie\n        trie_root = dict()\n        \n        # helper function to judge leaf node\n        isLeafNode = lambda node: len(node) == 0\n        \n        # collection of tail nodes\n        tail_nodes = []\n        \n        # set of unique words\n        unique_words = set(words)\n        \n        # scan each word\n        for word in unique_words:\n            \n            # build suffix trie from root node\n            cur = trie_root\n            \n            # scan each character in reversed order\n            for char in reversed(word):\n                \n                # update trie\n                cur[char] = cur.get(char, dict() )\n                \n                # go to next level\n                cur = cur[char]\n            \n            # save tail nodes with corresponding word length, +1 is for '#' symbol\n            tail_nodes.append( (cur, len(word)+1) )\n\n        # summation of the length with all tail node which is also a leaf node\n        return sum( suffix_length for node, suffix_length in tail_nodes if isLeafNode(node) )",
        "solution_js": "/**\n * @param {string[]} words\n * @return {number}\n */\nclass Trie {\n    constructor(letter) {\n        this.letter = letter;\n        this.children = new Map();\n        this.isWord = false;\n    }\n}\n\nvar minimumLengthEncoding = function(words) {\n    let minEncodingLength = 0;\n    const sortedWords = words.sort((a, b) => a.length - b.length);\n\n    const buildTrie = (root, word, index) => {\n        // This means we reached to the end of word, so mark it as a word and compute encoding length\n        if (index < 0) {\n            minEncodingLength += word.length + 1;\n            root.isWord = true;\n            return;\n        }\n\n        const character = word[index];\n        // If we do not have a char in children, create a node and add it under root\n        if (!root.children.has(character)) {\n            const node = new Trie(character);\n            root.children.set(character, node);\n            buildTrie(node, word, index - 1);\n            return;\n        }\n\n        const node = root.children.get(character);\n        // Remove the common suffix length considered before since it would be covered as a part of current word traversal\n        if (node.isWord) {\n            node.isWord = false;\n            minEncodingLength -= word.length - index + 1;\n        }\n\n        buildTrie(node, word, index - 1);\n    };\n\n    const root = new Trie();\n    for (const word of sortedWords) {\n        buildTrie(root, word, word.length - 1);\n    }\n\n    return minEncodingLength;\n};",
        "solution_java": "class Node {\n    private boolean flag;\n    private Node[] children;\n\n    public Node () {\n        flag = false;\n        children = new Node[26];\n        Arrays.fill (children, null);\n    }\n\n    public boolean getFlag () {\n        return flag;\n    }\n\n    public Node getChild (int index) {\n        return children[index];\n    }\n\n    public boolean hasChild (int index) {\n        return children[index] != null;\n    }\n\n    public void setFlag (boolean flag) {\n        this.flag = flag;\n    }\n\n    public void makeChild (int index) {\n        children[index] = new Node();\n    }\n}\n\nclass Trie {\n    private Node root;\n\n    public Trie () {\n        root = new Node();\n    }\n\n    public int addWord (String word) {\n\n        boolean flag = true;\n        Node node = root;\n        int count = 0;\n\n        for (int i = word.length () - 1; i >= 0; --i) {\n            int index = (int) word.charAt(i) - 97;\n\n            if (!node.hasChild (index)) {\n                flag = false;\n                node.makeChild (index);\n            }\n\n            node = node.getChild (index);\n            if (node.getFlag()) {\n                node.setFlag (false);\n                count -= word.length() - i + 1;\n\n                if (i == 0)\n                    flag = false;\n            }\n        }\n\n        if (!flag)\n            node.setFlag (true);\n\n        return flag? count: count + 1 + word.length();\n    }\n}\n\nclass Solution {\n    public int minimumLengthEncoding(String[] words) {\n        Trie trie = new Trie ();\n        int size = 0;\n\n        for (String word: words) {\n            size += trie.addWord (word);\n        }\n\n        return size;\n    }\n}",
        "solution_c": "class TrieNode{\npublic:\n    bool isEnd;\n    vector<TrieNode*> children;\n    TrieNode(){\n        isEnd = false;\n        children = vector<TrieNode*>(26, NULL);\n    }\n};\n\nclass Trie{\npublic:\n    TrieNode* root;\n    Trie(){\n        root = new TrieNode();\n    }\n    \n    void insert(string& word, bool& isSuffix){\n        auto cur = root;\n        for(int i=0; i<word.size(); i++){\n            int index = word[i] - 'a';\n\t\t\t\n\t\t\t//If new node is needed to be inserted for this word, then this word can't be suffix of some other word.\n            if(cur->children[index] == NULL){\n                isSuffix = false;\n                cur->children[index] = new TrieNode();\n            }\n            cur = cur->children[index];\n        }\n        cur -> isEnd= true;\n    }\n};\n\nclass Solution {\npublic:\n    int minimumLengthEncoding(vector<string>& words) {\n        sort(words.begin(), words.end(), [](string& a, string& b){\n            return a.size() > b.size();\n        });\n        \n        int res = 0;\n        Trie* trie = new Trie();\n\n\t\tfor(auto word: words){\n            reverse(word.begin(), word.end());\n            bool wordIsSuffix = true;\n            trie->insert(word, wordIsSuffix);\n            // If word is not suffix of some other word, it needs to be added separately\n            if(!wordIsSuffix) res += word.size()+1; //+1 for '#'\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Leaf-Similar Trees",
        "algo_input": "Consider all the leaves of a binary tree, from&nbsp;left to right order, the values of those&nbsp;leaves form a leaf value sequence.\n\n\n\nFor example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).\n\nTwo binary trees are considered leaf-similar&nbsp;if their leaf value sequence is the same.\n\nReturn true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.\n\n&nbsp;\nExample 1:\n\nInput: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput: true\n\n\nExample 2:\n\nInput: root1 = [1,2,3], root2 = [1,3,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in each tree will be in the range [1, 200].\n\tBoth of the given trees will have values in the range [0, 200].\n\n",
        "solution_py": "# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n        tree=[]\n        def inorder(root):\n            nonlocal tree\n            if root is None:\n                return\n            if root.left is None and root.right is None:\n                tree.append(root.val)\n            \n            inorder(root.left)\n            inorder(root.right)\n        \n        inorder(root1)\n        inorder(root2)\n        tree1=tree[:len(tree)//2]\n        tree2=tree[len(tree)//2:]\n        if tree1==tree2:\n            return True\n        else:\n            return False",
        "solution_js": "/*\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root1\n * @param {TreeNode} root2\n * @return {boolean}\n */\n \nvar leafSimilar = function(root1, root2) {\n    let array1 = [], array2 = [];\n    let leaf1 = getLeaf(root1, array1),\n        leaf2 = getLeaf(root2, array2);\n    \n    if (leaf1.length !== leaf2.length){   // if different lengths, return false right away\n        return false;\n    } \n    \n    for(let i = 0; i < leaf1.length; i++){\n        if (leaf1[i] !== leaf2[i]){     // compare pair by pair\n            return false;\n        }\n    }\n\t\n    return true;\n};\n\nvar getLeaf = function(root, array){    // DFS\n    if (!root){\n        return;\n    }\n    if (!(root.left || root.right)){\n        array.push(root.val);  // push leaf value to the array\n    }\n    getLeaf(root.left, array);\n    getLeaf(root.right, array);\n    \n    return array;\n}",
        "solution_java": "class Solution {\n    public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n        List<Integer> list1 = new ArrayList<>();\n        checkLeaf(root1, list1);\n        List<Integer> list2 = new ArrayList<>();\n        checkLeaf(root2, list2);\n\n        if(list1.size() != list2.size()) return false;\n\n        int i = 0;\n        while(i < list1.size()){\n            if(list1.get(i) != list2.get(i)){\n                return false;\n            }\n            i++;\n        }\n        return true;\n    }\n\n    private void checkLeaf(TreeNode node, List<Integer> arr){\n        if(node.left == null && node.right == null) arr.add(node.val);\n        if(node.left != null) checkLeaf(node.left, arr);\n        if(node.right != null) checkLeaf(node.right, arr);\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    \n    /*  How to get LeafOrder?\n        Simply traverse the tree Left->right\n        whenever you get a leaf, push its value to a vector\n    */\n    \n    \n    void getLeafOrder(TreeNode* root, vector<int> &leafOrder){  // Here we are passing vector\n        if(root == NULL){                                       // by reference to make changes\n            return;                                             // directly in main vector\n        }\n        \n        // Leaf found -> push its value in the vector\n        if(root->left == NULL and root->right == NULL){\n            leafOrder.push_back(root->val);\n            return;\n        }\n        \n        getLeafOrder(root->left, leafOrder);    // Left then Right -> to maintain the sequence\n        getLeafOrder(root->right, leafOrder);\n    }\n    \n    \n    bool leafSimilar(TreeNode* root1, TreeNode* root2) {\n        vector<int> leafOrder1;\n        vector<int> leafOrder2;\n        \n        getLeafOrder(root1, leafOrder1);    // Get leaf order for both trees\n        getLeafOrder(root2, leafOrder2);\n        \n        return leafOrder1 == leafOrder2;    // return if they are equal or not\n    }\n};"
    },
    {
        "title": "Increasing Order Search Tree",
        "algo_input": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n\n\nExample 2:\n\nInput: root = [5,1,7]\nOutput: [1,null,5,null,7]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the given tree will be in the range [1, 100].\n\t0 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    \n    def increasingBST(self, root):\n        \n        def sortBST(node):\n            if not node:    return []\n            \n            # return the in order BST nodes in list\n            return sortBST(node.left) + [node.val] + sortBST(node.right)\n            \n        # the in order sorted list of the tree nodes\n        sorted_list = sortBST(root)\n        \n        # generate new tree: temp for update, ans for return the root\n        ans = temp = TreeNode(sorted_list[0])\n        \n        # insert nodes to the right side of the new tree\n        for i in range(1, len(sorted_list)):\n            temp.right = TreeNode(sorted_list[i])\n            temp = temp.right\n            \n        return ans",
        "solution_js": "var increasingBST = function(root) {\n    let newRoot = new TreeNode(-1);\n    const newTree = newRoot;\n\n    const dfs = (node) => {\n        if (!node) return null;\n\n        if (node.left) dfs(node.left);\n\n        const newNode = new TreeNode(node.val);\n        newRoot.right = newNode;\n        newRoot.left = null;\n        newRoot = newRoot.right;\n\n        if (node.right) dfs(node.right);\n    }\n    dfs(root);\n\n    return newTree.right;\n};",
        "solution_java": "class Solution {\n    TreeNode inRoot = new TreeNode();\n    TreeNode temp = inRoot;\n    public TreeNode increasingBST(TreeNode root) {\n        inorder(root);\n        return inRoot.right;\n    }\n    public void inorder(TreeNode root) {\n        if(root==null)\n            return;\n        inorder(root.left);\n        temp.right = new TreeNode(root.val);\n        temp = temp.right;\n        inorder(root.right);\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* temp;\n    vector<int>z;\n    TreeNode* increasingBST(TreeNode* root) \n    {  \n        incresing(root);    \n        sort(z.begin(), z.end());\n        temp = new TreeNode(z[0]);\n        create(temp, z);\n        return temp;\n    }\n    void incresing(TreeNode* root)\n    {\n        if(root == NULL)  return;\n        \n        z.push_back(root->val);\n        incresing(root->left);\n        incresing(root->right);        \n    }\n    void create(TreeNode* create, vector<int> ze)\n    {\n          \n        for(int i = 1; i<ze.size(); i++)\n        {\n            cout<<ze[i]<<endl;\n            create->right = new TreeNode(ze[i]);\n            create = create->right;\n        }       \n    }\n};"
    },
    {
        "title": "Intersection of Two Linked Lists",
        "algo_input": "Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.\n\nFor example, the following two linked lists begin to intersect at node c1:\n\nThe test cases are generated such that there are no cycles anywhere in the entire linked structure.\n\nNote that the linked lists must retain their original structure after the function returns.\n\nCustom Judge:\n\nThe inputs to the judge are given as follows (your program is not given these inputs):\n\n\n\tintersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.\n\tlistA - The first linked list.\n\tlistB - The second linked list.\n\tskipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.\n\tskipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.\n\n\nThe judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput: Intersected at '8'\nExplanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.\n\n\nExample 2:\n\nInput: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput: Intersected at '2'\nExplanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\n\n\nExample 3:\n\nInput: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput: No intersection\nExplanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes of listA is in the m.\n\tThe number of nodes of listB is in the n.\n\t1 &lt;= m, n &lt;= 3 * 104\n\t1 &lt;= Node.val &lt;= 105\n\t0 &lt;= skipA &lt;&nbsp;m\n\t0 &lt;= skipB &lt;&nbsp;n\n\tintersectVal is 0 if listA and listB do not intersect.\n\tintersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.\n\n\n&nbsp;\nFollow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?",
        "solution_py": "class Solution:\n    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n        m = 0\n        n = 0\n        temp = headA\n        while temp != None:\n            m+=1\n            temp = temp.next\n        temp = headB\n        while temp != None:\n            n+=1\n            temp = temp.next\n        diff = 0\n        if m>=n : \n            diff = m-n\n        else:\n            diff = n-m\n        p1 = headA\n        p2 = headB\n        if max(m,n) == m:\n            while diff > 0:\n                p1 = p1.next\n                diff-=1\n        else:\n            while diff > 0:\n                p2 = p2.next\n                diff-=1\n        while p1 != None and p2!=None:\n            if p1 == p2:\n                return p1\n            p1 = p1.next\n            p2 = p2.next\n        return None",
        "solution_js": "var getIntersectionNode = function(headA, headB) {\n   let node1 = headA;\n   let node2 = headB;\n\n    const set = new Set()\n\n    while(node1 !== undefined || node2!== undefined){\n        if(node1 && set.has(node1)){\n            return node1\n        }\n        if(node2 && set.has(node2)){\n            return node2\n        }\n        if(node1){\n            set.add(node1)\n            node1 = node1.next;\n        }\n        else if(node2){\n            set.add(node2)\n            node2 = node2.next;\n        }\n        else {return}\n    }\n };",
        "solution_java": "public class Solution {\n    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n        ListNode tempA = headA, tempB = headB;\n        int lenA = 0, lenB = 0;\n        while (tempA != null) {\n            lenA++;\n            tempA = tempA.next;\n        }\n        while (tempB != null) {\n            lenB++;\n            tempB = tempB.next;\n        }\n        tempA = headA; tempB = headB;\n        if (lenB > lenA) {\n            for (int i = 0; i < lenB - lenA; i++) {\n                tempB = tempB.next;\n            }\n        } else if (lenA > lenB) {\n            for (int i = 0; i < lenA - lenB; i++) {\n                tempA = tempA.next;\n            }\n        }\n        while (tempA != null && tempA != tempB) {\n            tempA = tempA.next;\n            tempB = tempB.next;\n        }\n        return tempA;\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n\n    //function to get length of linked list\n    int getLength(ListNode *head)\n    {\n        //initial length 0\n        int l = 0;\n\n        while(head != NULL)\n        {\n            l++;\n            head = head->next;\n        }\n        return l;\n    }\n\n    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {\n\n        //ptr1 & ptr2 will move to check nodes are intersecting or not\n        //ptr1 will point to the list which have higher length, higher elements (big list)\n        //ptr2 will point to small list\n        ListNode *ptr1,*ptr2;\n\n        //fetching length of both the list,as we want a node that both ptr points simultaneously\n        //so if both list have same length of nodes, they travel with same speed, they intersect\n        //if diff legths, it'll be difficult for us to catch\n        //so by substracting list with higher length with lower length\n        //we get same level of length, from which both ptr start travaeling, they may get intersect\n        int length1 = getLength(headA);\n        int length2 = getLength(headB);\n\n        int diff = 0;\n\n        //ptr1 points to longer list\n        if(length1>length2)\n        {\n            diff = length1-length2;\n            ptr1 = headA;\n            ptr2 = headB;\n\n        }\n        else\n        {\n            diff = length2 - length1;\n            ptr1 = headB;\n            ptr2 = headA;\n        }\n\n        //till diff is zero and we reach our desired posn\n        while(diff)\n        {\n            //incrementing ptr1 so that it can be at a place where both list have same length\n\n            ptr1 = ptr1->next;\n\n            if(ptr1 == NULL)\n            {\n                return NULL;\n            }\n\n            diff--;\n        }\n\n        //traverse both pointers together, till any of them gets null\n        while((ptr1 != NULL) && (ptr2 != NULL))\n        {\n            //at any point, both point to same node return it\n            if(ptr1 == ptr2)\n            {\n                return ptr1;\n            }\n\n            //increment both pointers, till they both be NULL\n            ptr1 = ptr1->next;\n            ptr2 = ptr2->next;\n        }\n\n        //if not found any intersaction, return null\n        return NULL;\n\n     }\n};"
    },
    {
        "title": "Check if Every Row and Column Contains All Numbers",
        "algo_input": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).\n\nGiven an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,2,3],[3,1,2],[2,3,1]]\nOutput: true\nExplanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.\n\n\nExample 2:\n\nInput: matrix = [[1,1,1],[1,2,3],[1,2,3]]\nOutput: false\nExplanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= matrix[i][j] &lt;= n\n\n",
        "solution_py": "class Solution:\n    def checkValid(self, matrix: List[List[int]]) -> bool:\n        lst = [0]*len(matrix)\n        for i in matrix:\n            if len(set(i)) != len(matrix):\n                return False\n            for j in range(len(i)):\n                lst[j] += i[j]\n        return len(set(lst)) == 1",
        "solution_js": "var checkValid = function(matrix) {    \n    for(let i =0; i<matrix.length;i++){\n        const cols = new Set(), rows = new Set(matrix[i]);\n\t\t\n        for(let j =0; j<matrix.length;j++){\n            if(matrix[j][i] > matrix.length) return false;\n            cols.add(matrix[j][i])\n        }\n\t\t\n        if(cols.size < matrix.length || rows.size < matrix.length) return false;\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean checkValid(int[][] matrix) {\n        int n = matrix.length;\n        int num = (n*(n+1))/2; // SUM of n number 1 to n;\n\n        for(int i=0; i<n; i++)\n        {\n            HashSet<Integer> hs = new HashSet<Integer>();\n              HashSet<Integer> hs1 = new HashSet<Integer>();\n\n            int m = num; int k = num;\n\n            for(int j = 0; j<n; j++)\n            {\n                hs.add(matrix[i][j]);\n                  hs1.add(matrix[j][i]);\n                m -= matrix[i][j];\n                k -= matrix[j][i];\n            }\n\n            if(m != 0 || k != 0 || hs.size() != n || hs.size() != n)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkValid(vector<vector<int>>& matrix) {\n        int n=matrix.size();\n        unordered_set<int> s1, s2;\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<n;j++)\n            {\n                if(s1.find(matrix[i][j])!=s1.end())\n                    return false;\n                else\n                    s1.insert(matrix[i][j]);\n                if(s2.find(matrix[j][i])!=s2.end())\n                    return false;\n                else\n                    s2.insert(matrix[j][i]);\n            }\n            s1.clear();\n            s2.clear();\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Shortest Impossible Sequence of Rolls",
        "algo_input": "You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].\n\nReturn the length of the shortest sequence of rolls that cannot be taken from rolls.\n\nA sequence of rolls of length len is the result of rolling a k sided dice len times.\n\nNote that the sequence taken does not have to be consecutive as long as it is in order.\n\n&nbsp;\nExample 1:\n\nInput: rolls = [4,2,1,2,3,3,2,4,1], k = 4\nOutput: 3\nExplanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.\n\nExample 2:\n\nInput: rolls = [1,1,2,2], k = 2\nOutput: 2\nExplanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.\n\n\nExample 3:\n\nInput: rolls = [1,1,3,2,2,2,3,3], k = 4\nOutput: 1\nExplanation: The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == rolls.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= rolls[i] &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def shortestSequence(self, rolls: List[int], k: int) -> int:\n        ans = 1\n        data = set()\n\n        for roll in rolls:\n            data.add(roll)\n\n            if len(data) == k:\n                ans += 1\n                data.clear()\n\n        return ans",
        "solution_js": "var shortestSequence = function(rolls, k)\n{\n    let ans=1;\n    let sett=new Set();\n\n    for(let i of rolls)\n        {\n            sett.add(i);\n            if(sett.size===k)\n                {\n                    ans++;\n                    sett=new Set();\n                }\n        }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int shortestSequence(int[] rolls, int k) {\n        int len = 0;\n        Set<Integer> set = new HashSet<>();\n        for(int i:rolls)\n        {\n            set.add(i);\n            if(set.size()==k)\n            {\n                set = new HashSet<>();\n                len++;\n            }\n        }\n        return len+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int shortestSequence(vector<int>& rolls, int k) {\n        int len = 1;\n        set<int> data ;\n        \n        for (int i = 0; i < rolls.size(); i++) {\n            data.insert(rolls[i]);\n            \n            if (data.size() == k) {\n                len++;\n                data = set<int>();\n            }\n        }\n        \n        return len;\n    }\n};"
    },
    {
        "title": "Swap Nodes in Pairs",
        "algo_input": "Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4]\nOutput: [2,1,4,3]\n\n\nExample 2:\n\nInput: head = []\nOutput: []\n\n\nExample 3:\n\nInput: head = [1]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the&nbsp;list&nbsp;is in the range [0, 100].\n\t0 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if not head:\n            return head\n        dummy = ListNode(None, head)\n        prev, curr_1, curr_2 = dummy, head, head.next\n        while curr_1 and curr_2:\n            # 1. define temp nodes, temp nodes are comprised of 1 prev node, and multiple curr nodes. The while condition checks those curr nodes only.\n            node_0 = prev\n            node_1 = curr_1\n            node_2 = curr_2\n            node_3 = curr_2.next\n\n            # 2. swap nodes using temp nodes\n            node_0.next = node_2\n            node_1.next = node_3\n            node_2.next = node_1\n\n            # 3. move temp nodes to the next window\n            prev = node_1\n            curr_1 = node_3\n            curr_2 = node_3.next if node_3 else None\n\n        return dummy.next",
        "solution_js": "var swapPairs = function(head) {\n    if(!head || !head.next)  return head;\n    \n    // using an array to store all the pairs of the list \n    \n    let ptrArr = [];\n    let ptr = head;\n    \n    while(ptr) {\n        ptrArr.push(ptr);\n        let nptr = ptr.next ? ptr.next.next : null;\n        if(nptr) ptr.next.next = null;\n        ptr = nptr;\n    }\n    \n    // reversing all the pairs of the list in array\n    \n    for(let i=0;i<ptrArr.length;i++) {\n        let node = ptrArr[i];\n        let temp = node.next;\n        \n        if(!temp) break;\n        temp.next = node;\n        node.next = null;\n        ptrArr[i] = temp;\n    }\n    \n    let dummy = new ListNode(-1);\n    let nptr = dummy;\n    \n    // joining all the pairs back again\n    ptrArr.forEach(ele => {\n        nptr.next = ele;\n        nptr = nptr.next.next;\n    })\n    \n    return dummy.next;\n    \n};",
        "solution_java": "class Solution {\n    public ListNode swapPairs(ListNode head) {\n        ListNode dummy = new ListNode(0) , prev = dummy , curr = head;\n        dummy.next = head;\n        while(curr != null && curr.next != null){\n            prev.next = curr.next;\n            curr.next = curr.next.next ;\n            prev.next.next = curr;\n           curr = curr.next ;\n            prev = prev.next.next;\n        }\n        return dummy.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* swapPairs(ListNode* head) {\n        // if head is NULL OR just having a single node, then no need to change anything\n        if(head == NULL || head -> next == NULL)\n        {\n            return head;\n        }\n\n        ListNode* temp; // temporary pointer to store head -> next\n        temp = head->next; // give temp what he want\n\n        head->next = swapPairs(head->next->next); // changing links\n        temp->next = head; // put temp -> next to head\n\n        return temp; // now after changing links, temp act as our head\n    }\n};"
    },
    {
        "title": "Rabbits in Forest",
        "algo_input": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.\n\nGiven the array answers, return the minimum number of rabbits that could be in the forest.\n\n&nbsp;\nExample 1:\n\nInput: answers = [1,1,2]\nOutput: 5\nExplanation:\nThe two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n\n\nExample 2:\n\nInput: answers = [10,10,10]\nOutput: 11\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= answers.length &lt;= 1000\n\t0 &lt;= answers[i] &lt; 1000\n\n",
        "solution_py": "class Solution:\n    def numRabbits(self, answers: List[int]) -> int:\n        counts = {}\n        count = 0\n\n        for answer in answers:\n            if answer == 0:\n                # This must be the only rabbit of its color.\n                count += 1\n            elif answer not in counts or counts[answer] == 0:\n                # This is the first time the color appears.\n                counts[answer] = 1\n                # Add all rabbits having this new color.\n                count += answer + 1\n            else:\n                # Add one to how many times answer occurred.\n                counts[answer] += 1\n                if counts[answer] > answer:\n                    # If n+1 rabbits have said n,\n                    # this color group is complete.\n                    counts[answer] = 0\n        \n        return count",
        "solution_js": "/**\n * @param {number[]} answers\n * @return {number}\n */\nvar numRabbits = function(answers) {\n    \n    var totalRabbits = 0;\n    var sumOfLikeAnswers = new Array(1000).fill(0);\n    \n    for (let i = 0; i < answers.length; i++) {\n        sumOfLikeAnswers[answers[i]] += 1;\n    }\n    \n    for (let i = 0; i < sumOfLikeAnswers.length; i++) {\n        totalRabbits += Math.ceil(sumOfLikeAnswers[i] / (i+1)) * (i+1);\n    }\n    \n    return totalRabbits;\n};",
        "solution_java": "class Solution {\n    public int numRabbits(int[] answers) {\n        HashMap<Integer, Integer> map = new HashMap<>();\n        int count = 0;\n        \n        for(int ele : answers) {\n            \n            if(!map.containsKey(ele+1)) {\n                map.put(ele+1, 1);\n                count += ele+1;\n            }\n            else if(map.get(ele+1) == ele+1) {\n                map.put(ele+1, 1);\n                 count += ele+1;\n            }\n            else {\n                int freq = map.get(ele+1);\n                map.put(ele+1, freq+1);\n            }\n        }\n        \n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numRabbits(vector<int>& answers) {\n        sort(answers.begin(),answers.end());\n        int ans = 0;\n        for(int i=0;i<answers.size();i++){\n            ans += answers[i]+1;\n            int num = answers[i];\n            while(answers[i]==answers[i+1] && num>0 && i+1<answers.size()){\n                num--;\n                i++;\n            }\n\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Non-Zero Product of the Array Elements",
        "algo_input": "You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:\n\n\n\tChoose two elements x and y from nums.\n\tChoose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.\n\n\nFor example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.\n\nFind the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.\n\nNote: The answer should be the minimum product before the modulo operation is done.\n\n&nbsp;\nExample 1:\n\nInput: p = 1\nOutput: 1\nExplanation: nums = [1].\nThere is only one element, so the product equals that element.\n\n\nExample 2:\n\nInput: p = 2\nOutput: 6\nExplanation: nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.\n\n\nExample 3:\n\nInput: p = 3\nOutput: 1512\nExplanation: nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n    - The resulting array is [001, 110, 011, 100, 001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n    - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= p &lt;= 60\n\n",
        "solution_py": "class Solution:\n    def minNonZeroProduct(self, p: int) -> int:\n        mod = 10**9+7\n        return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod",
        "solution_js": "var minNonZeroProduct = function(p) {\n    p = BigInt(p);\n    \n    const MOD = BigInt(1e9 + 7);\n    const first = ((1n << p) - 1n);\n    \n   const half = first / 2n;\n    \n    const second = powMOD(first - 1n, half); \n    \n    return (first * second) % MOD;\n    \n    function powMOD(num, exp) {\n        if (exp === 0n) return 1n; \n        \n        const tmp = powMOD(num, exp >> 1n);\n        \n        let res = (tmp * tmp) % MOD;\n        \n        if (exp % 2n) res = (res * num) % MOD;\n        \n        return res;\n    }\n};  ",
        "solution_java": "class Solution {\n    public int mod = 1_000_000_007;\n    public int minNonZeroProduct(int p) {\n        if (p == 1) return 1;\n        \n        long mx = (long)(Math.pow(2, p)) - 1;\n        long sm = mx - 1;\n        long n = sm/2;\n        long sum = rec(sm, n);\n        \n        return (int)(sum * (mx % mod) % mod); \n    }\n    \n    public long rec(long val, long n) {\n        if (n == 0) return 1;\n        if (n == 1) return (val % mod);\n        \n        long newVal = ((val % mod) * (val % mod)) % mod;\n        \n        if (n % 2 != 0) {\n            return ((rec(newVal, n/2) % mod) * (val % mod)) % mod;\n        }\n        \n        return rec(newVal, n/2) % mod;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long myPow(long long base, long long exponent, long long mod) {\n        if (exponent == 0) return 1;\n        if (exponent == 1) return base % mod;\n        \n        long long tmp = myPow(base, exponent/2, mod);\n        \n        if (exponent % 2 == 0) { // (base ^ exponent/2) * (base ^ exponent/2)\n            return (tmp * tmp) % mod;\n        }\n        else { // (base ^ exponent/2) * (base ^ exponent/2) * base\n            tmp = tmp * tmp % mod;\n            base %= mod;\n            return (tmp * base) % mod;\n        }\n    }\n    \n    int minNonZeroProduct(int p) {\n        long long range = pow(2, p);\n        range--;\n        long long mod = pow(10, 9) + 7;\n        long long tmp = myPow(range-1, range/2, mod);\n        return (tmp * (range%mod)) % mod;\n    }\n};"
    },
    {
        "title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance",
        "algo_input": "There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.\n\nReturn the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.\n\nNotice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput: 3\nExplanation: The figure above describes the graph.&nbsp;\nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -&gt; [City 1, City 2]&nbsp;\nCity 1 -&gt; [City 0, City 2, City 3]&nbsp;\nCity 2 -&gt; [City 0, City 1, City 3]&nbsp;\nCity 3 -&gt; [City 1, City 2]&nbsp;\nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\n\n\nExample 2:\n\nInput: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput: 0\nExplanation: The figure above describes the graph.&nbsp;\nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -&gt; [City 1]&nbsp;\nCity 1 -&gt; [City 0, City 4]&nbsp;\nCity 2 -&gt; [City 3, City 4]&nbsp;\nCity 3 -&gt; [City 2, City 4]\nCity 4 -&gt; [City 1, City 2, City 3]&nbsp;\nThe city 0 has 1 neighboring city at a distanceThreshold = 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 100\n\t1 &lt;= edges.length &lt;= n * (n - 1) / 2\n\tedges[i].length == 3\n\t0 &lt;= fromi &lt; toi &lt; n\n\t1 &lt;= weighti,&nbsp;distanceThreshold &lt;= 10^4\n\tAll pairs (fromi, toi) are distinct.\n\n",
        "solution_py": "class Solution:\n    def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n        matrix = [[float('inf')] * n for _ in range(n)]\n        \n        # initializing the matrix\n        for u, v, w in edges:\n            matrix[u][v] = w\n            matrix[v][u] = w\n\n        for u in range(n):\n            matrix[u][u] = 0\n        \n        for k in range(n):\n            for i in range(n):\n                for j in range(n):\n                    if matrix[i][j] > matrix[i][k] + matrix[k][j]:\n                        matrix[i][j] = matrix[i][k] + matrix[k][j]\n        \n        # counting reachable cities(neighbor) for every single city \n        res = [0] * n\n        for i in range(len(matrix)):\n            for j in range(len(matrix[0])):\n                if 0 < matrix[i][j] <= distanceThreshold:\n                    res[j] += 1\n        return [i for i, x in enumerate(res) if x == min(res)][-1]",
        "solution_js": "var findTheCity = function(n, edges, distanceThreshold) {\n    const dp = Array.from({length: n}, (_, i) => {\n        return Array.from({length: n}, (_, j) => i == j ? 0 : Infinity)\n    });\n\n    for(let edge of edges) {\n        const [a, b, w] = edge;\n        dp[a][b] = dp[b][a] = w;\n    }\n\n    // k is intermediate node\n    for(let k = 0; k < n; k++) {\n        // fix distances from i to other nodes with k as intermediate\n        for(let i = 0; i < n; i++) {\n            if(i == k || dp[i][k] == Infinity) continue;\n            for(let j = i + 1; j < n; j++) {\n                dp[i][j] = dp[j][i] = Math.min(dp[i][j], dp[i][k] + dp[k][j]);\n            }\n        }\n    };\n\n    let city = -1, minCity = n;\n    for(let i = 0; i < n; i++) {\n        let count = 0;\n        for(let j = 0; j < n; j++) {\n            if(i == j) continue;\n            if(dp[i][j] <= distanceThreshold) count++;\n        }\n        if(count <= minCity) {\n            minCity = count;\n            city = i;\n        }\n    }\n\n    return city;\n};",
        "solution_java": "class Solution {\n    public int findTheCity(int n, int[][] edges, int distanceThreshold) {\n        int[][] graph = new int[n][n];\n        for(int[] row: graph)\n            Arrays.fill(row, Integer.MAX_VALUE);\n        \n        for(int i = 0; i < n; i++)\n            graph[i][i] = 0;\n        \n        for(int[] edge: edges)\n        {\n            graph[edge[0]][edge[1]] = edge[2];\n            graph[edge[1]][edge[0]] = edge[2];\n        }\n        \n        for(int k = 0; k < n; k++)\n        {\n            for(int i = 0; i < n; i++)\n            {\n                for(int j = 0; j < n; j++)\n                {\n                    if(graph[i][k] != Integer.MAX_VALUE && graph[k][j] != Integer.MAX_VALUE)\n                    {\n                        if(graph[i][k] + graph[k][j] < graph[i][j])\n                            graph[i][j] = graph[i][k] + graph[k][j];\n                    }\n                }\n            }\n        }\n        \n        int ans = 0;\n        int city = Integer.MAX_VALUE;;\n        \n        for(int i = 0; i < n; i++)\n        {\n            int current = 0;\n            for(int j = 0; j < n; j++)\n            {\n                if(i != j && graph[i][j] <= distanceThreshold)\n                    current++;\n            }\n            if(current <= city)\n            {\n                ans = i;\n                city = current;\n            }\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\nunordered_map<int,int>m;\n    int findTheCity(int n, vector<vector<int>>& edges, int threshold) {\n        vector<vector<pair<int,int>>>adj(n);\n        for(auto x:edges)\n        {\n            adj[x[0]].push_back({x[1],x[2]});\n            adj[x[1]].push_back({x[0],x[2]});\n        }\n        int ind=-1,ans=1e8;\n       for(int i=0;i<n;i++)\n       {\n           queue<pair<int,int>>q;\n           q.push({i,0});\n           vector<int>dis(n,1e8);\n           dis[i]=0;\n           while(!q.empty())\n           {\n               int node=q.front().first;\n               int wt=q.front().second;\n               q.pop();\n               for(auto x:adj[node])\n               {\n                   int node1=x.first;\n                   int wt1=x.second;\n                   if(wt+wt1<dis[node1])\n                   {\n                       dis[node1]=wt+wt1;\n                       q.push({node1,wt+wt1});\n                   }\n               }\n           }\n           int c=0;\n           for(int i=0;i<dis.size();i++)\n           {\n               if(dis[i]<=threshold)\n               {\n                   c++;\n               }\n           }\n           if(c<=ans)\n           {\n               ans=c;\n               ind=max(ind,i);\n           }\n           \n       }\n       return ind;\n\n\n    }\n};"
    },
    {
        "title": "Count Good Triplets",
        "algo_input": "Given an array of integers arr, and three integers&nbsp;a,&nbsp;b&nbsp;and&nbsp;c. You need to find the number of good triplets.\n\nA triplet (arr[i], arr[j], arr[k])&nbsp;is good if the following conditions are true:\n\n\n\t0 &lt;= i &lt; j &lt; k &lt;&nbsp;arr.length\n\t|arr[i] - arr[j]| &lt;= a\n\t|arr[j] - arr[k]| &lt;= b\n\t|arr[i] - arr[k]| &lt;= c\n\n\nWhere |x| denotes the absolute value of x.\n\nReturn the number of good triplets.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\nOutput: 4\nExplanation:&nbsp;There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\n\n\nExample 2:\n\nInput: arr = [1,1,2,2,3], a = 0, b = 0, c = 1\nOutput: 0\nExplanation: No triplet satisfies all conditions.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 100\n\t0 &lt;= arr[i] &lt;= 1000\n\t0 &lt;= a, b, c &lt;= 1000\n",
        "solution_py": "class Solution:\n    def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n        count = 0\n        for i in range(len(arr)):\n            for j in range(i+1,len(arr)):\n                for k in range(j+1,len(arr)):\n                    if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k]-arr[i])<=c:\n                        count+=1\n        return count",
        "solution_js": "var countGoodTriplets = function(arr, a, b, c) {\n  let triplets = 0;\n\n  for (let i = 0; i < arr.length - 2; i++) {\n    for (let j = i + 1; j < arr.length - 1; j++) {\n      if (Math.abs(arr[i] - arr[j]) > a) continue;\n      for (let k = j + 1; k < arr.length; k++) {\n        if (Math.abs(arr[j] - arr[k]) > b || Math.abs(arr[i] - arr[k]) > c) {\n          continue;\n        }\n        triplets++;\n      }\n    }\n  }\n\n  return triplets;\n};",
        "solution_java": "class Solution {\n    public int countGoodTriplets(int[] arr, int a, int b, int c) {\n        int total = 0;\n        for (int i = 0; i < arr.length - 2; i++){\n            for (int j = i+1; j < arr.length - 1; j++){\n                for (int k = j+1; k < arr.length; k++){\n                    if (helper(arr[i], arr[j]) <= a &&\n                            helper(arr[j], arr[k]) <= b &&\n                                helper(arr[k], arr[i]) <= c)\n                        total++;\n                }\n            }\n        }\n        return total;\n    }\n\n    private static int helper(int x, int y) {\n        return Math.abs(x - y);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countGoodTriplets(vector<int>& arr, int a, int b, int c) {\n        int ct = 0;\n        for(int i = 0; i<arr.size()-2; i++)\n        {\n            for(int j = i+1; j<arr.size()-1; j++)\n            {\n                if(abs(arr[i]-arr[j])<=a)\n                    for(int k = j+1; k<arr.size(); k++)\n                    {\n                        if(abs(arr[j]-arr[k])<=b && abs(arr[i]-arr[k])<=c)\n                            ct++;\n                    }\n            }\n        }\n        return ct;\n        \n    }\n};"
    },
    {
        "title": "Minimum Jumps to Reach Home",
        "algo_input": "A certain bug's home is on the x-axis at position x. Help them get there from position 0.\n\nThe bug jumps according to the following rules:\n\n\n\tIt can jump exactly a positions forward (to the right).\n\tIt can jump exactly b positions backward (to the left).\n\tIt cannot jump backward twice in a row.\n\tIt cannot jump to any forbidden positions.\n\n\nThe bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.\n\nGiven an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.\n\n&nbsp;\nExample 1:\n\nInput: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput: 3\nExplanation: 3 jumps forward (0 -&gt; 3 -&gt; 6 -&gt; 9) will get the bug home.\n\n\nExample 2:\n\nInput: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput: -1\n\n\nExample 3:\n\nInput: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput: 2\nExplanation: One jump forward (0 -&gt; 16) then one jump backward (16 -&gt; 7) will get the bug home.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= forbidden.length &lt;= 1000\n\t1 &lt;= a, b, forbidden[i] &lt;= 2000\n\t0 &lt;= x &lt;= 2000\n\tAll the elements in forbidden are distinct.\n\tPosition x is not forbidden.\n\n",
        "solution_py": "class Solution:\n    def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int:\n        fb = set(fb)\n        q = deque([[0,0,True]])\n        while(q):\n            n,l,isf = q.popleft()\n            if(n<0 or n in fb or n>2000+2*b):\n                continue\n            fb.add(n)\n            if(n==x):\n                return l\n            if isf and n-b>0:\n                q.append([n-b,l+1,False])                \n            q.append([n+a,l+1,True])\n        return -1",
        "solution_js": "var minimumJumps = function(forbidden, a, b, x) {\n    let f = new Set(forbidden);\n    let m = 2000 + 2 * b;\n    let memo = {};\n    let visited = new Set();\n    let res = dfs(0, true);\n    return res === Infinity ? -1 : res;\n    \n    function dfs(i,canJumpBack) {\n        if (i === x) return 0;\n        let key = `${i},${canJumpBack}`;\n        visited.add(i);\n        if (memo[key] !== undefined) return memo[key];\n        if (i > m || i < 0) return Infinity;\n        let min = Infinity;\n        if (canJumpBack && !f.has(i - b) && !visited.has(i-b)) {\n            min = Math.min(min, 1 + dfs(i - b, false));\n        }\n        \n        if (!f.has(i + a) && !visited.has(i+a)) {\n            min = Math.min(min, 1 + dfs(i + a, true));\n        }\n        \n        visited.delete(i);\n        return memo[key] = min;\n    }\n};",
        "solution_java": "class Solution {\n    public int minimumJumps(int[] forbidden, int a, int b, int x) {\n        \n        // Visited Set\n        Set<Integer> visited = new HashSet<Integer>();\n        \n        // Add forbidden coordinates to visited\n        for (int i = 0; i < forbidden.length; i++) {\n            visited.add(forbidden[i]);\n        }\n        \n        // Distance/ Jumps map\n        Map<Integer, Integer> jumps = new HashMap<>();\n        jumps.put(0, 0);\n        \n        // BFS Queue\n        Queue<Integer[]> q = new LinkedList<>();\n        q.add(new Integer[] {0, 1});\n        \n        // BFS \n        while (q.size() != 0) {\n            \n            Integer[] ud = q.poll();\n            \n            int u = ud[0], d = ud[1];\n            \n            // x found\n            if (u == x) {\n                return jumps.get(u);\n            }\n            \n            // jump right\n            if (u + a < 6001 && !visited.contains(u+a)) {\n                q.add(new Integer[] {u+a, 1});\n                visited.add(u+a);\n                jumps.put(u+a, jumps.get(u) + 1);\n            }\n            \n            // jump left\n            if (d != -1 && u - b > -1 && !visited.contains(u-b)) {\n                q.add(new Integer[] {u-b, -1});\n                jumps.put(u-b, jumps.get(u) + 1);\n            }\n            \n        }\n        \n        return -1;\n        \n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    typedef pair<int, bool> pi;\n    int minimumJumps(vector<int> &forbidden, int a, int b, int x)\n    {\n        set<int> st(forbidden.begin(), forbidden.end());\n        vector<vector<int>> vis(2, vector<int>(10000, 0));\n        vis[0][0] = 1;\n        vis[1][0] = 1;\n        queue<pi> q;\n        q.push({0, true});\n        int ans = 0;\n        while (!q.empty())\n        {\n            int n = q.size();\n            for (int i = 0; i < n; i++)\n            {\n                int curr = q.front().first;\n                bool canJumpBackward = q.front().second;\n                q.pop();\n                if (curr == x)\n                    return ans;\n                int p1 = curr + a;\n                int p2 = curr - b;\n                if (p1 < 10000 && vis[0][p1] == 0 && st.find(p1) == st.end())\n                {\n                    q.push({p1, true});\n                    vis[0][p1] = 1;\n                }\n                if (p2 >= 0 && vis[1][p2] == 0 && st.find(p2) == st.end() && canJumpBackward == true)\n                {\n                    q.push({p2, false});\n                    vis[1][p2] = 1;\n                }\n            }\n            ans++;\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Count Pairs Of Nodes",
        "algo_input": "You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.\n\nLet incident(a, b) be defined as the number of edges that are connected to either node a or b.\n\nThe answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:\n\n\n\ta &lt; b\n\tincident(a, b) &gt; queries[j]\n\n\nReturn an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.\n\nNote that there can be multiple edges between the same two nodes.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput: [6,5]\nExplanation: The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\n\n\nExample 2:\n\nInput: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput: [10,10,9,8,6]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 2 * 104\n\t1 &lt;= edges.length &lt;= 105\n\t1 &lt;= ui, vi &lt;= n\n\tui != vi\n\t1 &lt;= queries.length &lt;= 20\n\t0 &lt;= queries[j] &lt; edges.length\n\n",
        "solution_py": "class Solution:\n    def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n        p_c = [0] * (n+1) # point counter\n        e_c = defaultdict(int) # edge counter\n        \n        for a,b in edges:\n            p_c[a] += 1\n            p_c[b] += 1\n            if a<b:\n                e_c[(a,b)] += 1\n            else:\n                e_c[(b,a)] += 1\n        \n        f_c = defaultdict(int) # frequency of point counter (compress the individual calculations into massive one)\n        for i in range(1, n+1):\n            f_c[p_c[i]] += 1\n\n        cnt_amt = defaultdict(int) # frequency of same cnt on pairs without edge adjustment\n        f_key = list(f_c.keys()) # frequency key\n        l_f = len(f_key)\n        for i in range(l_f):\n            f1 = f_key[i]\n            cnt_amt[f1*2] += f_c[f1] * (f_c[f1]-1) // 2 # 3 points with 4, then you get 8 \n                                                        # for a frequency of 3 * (3-2) // 2 = 3\n            for j in range(i+1, l_f):\n                f2 = f_key[j]\n                cnt_amt[f1+f2] += f_c[f1] * f_c[f2] # 2 points with 2, 3 points with 4\n                                                    # will have 6 with frequency of 2 * 3 = 6\n        \n        for (u,v), z in e_c.items(): # edge adjustment\n            s = p_c[u] + p_c[v]\n            t = s - z\n            cnt_amt[s] -= 1\n            cnt_amt[t] += 1\n        \n        cnt_keys = sorted(cnt_amt.keys(), key=lambda x: -x) # accumulate the frequency by descending order\n        res = defaultdict(int)\n        tmp = 0\n        for key in cnt_keys:\n            if cnt_amt[key]: # if it is 0 then dont bother to keep them\n                tmp += cnt_amt[key]\n                res[key] = tmp\n\n        res_keys = sorted(res.keys()) # bisection search \n        for i, q in enumerate(queries):\n            local = bisect.bisect(res_keys, q)\n            try:\n                queries[i] = res[res_keys[local]]\n            except:\n                queries[i] = 0 # some test cases are annoying by requesting an unreasonable large number\n        \n        return queries",
        "solution_js": "var countPairs = function(n, edges, queries) {\n    const degree = Array(n+1).fill(0)\n    const edgesMap = new Map()\n    const countMemo = new Map()\n    const answer = []\n    \n    for(let [u, v] of edges) {\n        degree[u]++\n        degree[v]++\n        const key = `${Math.min(u, v)}-${Math.max(u, v)}`;\n        edgesMap.set(key, (edgesMap.get(key) || 0) + 1);\n    }\n    const sortedDegree = [...degree.slice(1)].sort((a, b) => a - b);  \n    \n    for(let num of queries) {\n        let cnt;\n        if(countMemo.has(num)) cnt = countMemo.get(num)\n        else {\n            cnt = calculateCount(num)\n            countMemo.set(num, cnt);\n        }\n        answer.push(cnt)\n    }\n    \n    function calculateCount(num) {\n        let low = 0, high = sortedDegree.length-1, cnt = 0;\n        \n        while(low < high) {\n            const sum  = sortedDegree[low] + sortedDegree[high];\n            \n            if(sum > num) {\n                cnt += (high - low);\n                high--;\n            } else low++;\n        }\n        \n        for(let [key, val] of edgesMap) {\n            const [u, v] = key.split('-').map(Number);\n            \n            if(degree[u] + degree[v] > num) {\n                const newSum = degree[u] + degree[v] - val\n                if(newSum <= num) cnt--;\n            }\n        }\n        return cnt;\n    }\n    return answer;\n};",
        "solution_java": "class Solution {\n    public int[] countPairs(int n, int[][] edges, int[] queries) {\n        Map<Integer, Map<Integer, Integer>> dupMap = new HashMap<>();\n        Map<Integer, Set<Integer>> map = new HashMap<>();\n        int[] ans = new int[queries.length];\n        int[] count = new int[n];\n        for (int[] e : edges){\n            int min = Math.min(e[0]-1, e[1]-1);\n            int max = Math.max(e[0]-1, e[1]-1);\n            dupMap.computeIfAbsent(min, o -> new HashMap<>()).merge(max, 1, Integer::sum);\n            map.computeIfAbsent(min, o -> new HashSet<>()).add(max);\n            count[min]++;\n            count[max]++;\n        }\n        Integer[] indexes = IntStream.range(0, n).boxed().toArray(Integer[]::new);\n        Arrays.sort(indexes, Comparator.comparingInt(o -> count[o]));\n        for (int j = 0, hi = n; j < queries.length; j++, hi = n){\n            for (int i = 0; i < n; i++){\n                while(hi>i+1&&count[indexes[i]]+count[indexes[hi-1]]>queries[j]){\n                    hi--;\n                }\n                if (hi==i){\n                    hi++;\n                }\n                ans[j]+=n-hi;\n                for (int adj : map.getOrDefault(indexes[i], Set.of())){\n                    int ttl = count[indexes[i]] + count[adj];\n                    if (ttl > queries[j] && ttl-dupMap.get(indexes[i]).get(adj) <= queries[j]){\n                        ans[j]--;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\n    vector<int> st;\npublic:\n    void update(int tind,int tl,int tr,int ind,int val){\n        if(tl>tr)\n            return;\n        if(tl==tr){\n            st[tind]+=val;\n            return;\n        }\n        int tm=tl+((tr-tl)>>1),left=tind<<1;\n        if(ind<=tm)\n            update(left,tl,tm,ind,val);\n        else\n            update(left|1,tm+1,tr,ind,val);\n        st[tind]=st[left]+st[left|1];\n    }\n    \n    int query(int tind,int tl,int tr,int ql,int qr){\n        if(tl>tr or qr<tl or ql>tr)\n            return 0;\n        if(ql<=tl and tr<=qr)\n            return st[tind];\n        int tm=tl+((tr-tl)>>1),left=tind<<1;\n        return query(left,tl,tm,ql,qr)+query(left|1,tm+1,tr,ql,qr);\n    }\n    \n    vector<int> countPairs(int n,vector<vector<int>>& a,vector<int>& q) {\n        vector<int> f(n+2,0);\n        vector<unordered_map<int,int>> mp(n+2); // using a normal map gives TLE\n        \n        for(auto v:a){\n            int mx=max(v[0],v[1]),mn=min(v[1],v[0]);\n            f[mx]++;\n            f[mn]++;\n            mp[mx][mn]++;\n        }\n        \n        vector<int> ans(q.size(),0);\n        int m=a.size();\n        st.resize(4*m+40,0);\n        \n        for(int i=n;i;i--){\n\t\t\t// reducing the common edges between current node and its adjacent\n            for(auto e:mp[i]){\n                update(1,0,m,f[e.first],-1);\n                update(1,0,m,f[e.first]-e.second,1);\n            }\n            \n            int curr=f[i];\n            for(int j=0;j<q.size();j++)\n                ans[j]+=query(1,0,m,max(0,q[j]-curr+1),m);\n            \n\t\t\t// reversing the changes made initially\n            for(auto e:mp[i]){\n                update(1,0,m,f[e.first],1);\n                update(1,0,m,f[e.first]-e.second,-1);\n            }\n            \n            update(1,0,m,f[i],1);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "The Number of the Smallest Unoccupied Chair",
        "algo_input": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.\n\n\n\tFor example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.\n\n\nWhen a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.\n\nYou are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.\n\nReturn the chair number that the friend numbered targetFriend will sit on.\n\n&nbsp;\nExample 1:\n\nInput: times = [[1,4],[2,3],[4,6]], targetFriend = 1\nOutput: 1\nExplanation: \n- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.\n\n\nExample 2:\n\nInput: times = [[3,10],[1,5],[2,6]], targetFriend = 0\nOutput: 2\nExplanation: \n- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == times.length\n\t2 &lt;= n &lt;= 104\n\ttimes[i].length == 2\n\t1 &lt;= arrivali &lt; leavingi &lt;= 105\n\t0 &lt;= targetFriend &lt;= n - 1\n\tEach arrivali time is distinct.\n\n",
        "solution_py": "class Solution:\n    def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n        arrivals = []\n        departures = []\n        for ind, (x, y) in enumerate(times):\n            heappush(arrivals, (x, ind))\n            heappush(departures, (y, ind))\n        d = {}\n        occupied = [0] * len(times)\n        while True:\n            if arrivals and departures and arrivals[0][0] < departures[0][0]:\n                _, ind = heappop(arrivals)\n                d[ind] = occupied.index(0)\n                occupied[d[ind]] = 1\n                if ind == targetFriend:\n                    return d[ind]\n            elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n                _, ind = heappop(departures)\n                occupied[d[ind]] = 0",
        "solution_js": "/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nvar smallestChair = function(times, targetFriend) {\n    const [targetArrival] = times[targetFriend]; // we need only arrival time\n    const arrivalQueue = times;\n    const leavingQueue = [...times];\n    arrivalQueue.sort((a, b) => a[0] - b[0]); // sort by arrival time\n    leavingQueue.sort((a, b) => (a[1] - b[1]) || (a[0] - b[0])); // sort by leaving time and if they are equal by arrival\n    const chairsByLeaveTime = new Map(); // key - arrival time, value - chair index\n    let chairsCount = 0;\n    let arriving = 0, leaving = 0; // two pointers for keeping track of available chairs\n\n    while (arriving < arrivalQueue.length) {\n        let chairIdx;\n        const arrival = arrivalQueue[arriving][0];\n        const leave = leavingQueue[leaving][1];\n        if (arrival < leave) {\n            chairIdx = chairsCount++; // if no one is leaving, take a new chair\n        } else {\n            let freeChairIdx = leaving;\n            chairIdx = chairsByLeaveTime.get(leavingQueue[freeChairIdx++][0]); // when arriaval time is less then or equal to the next leaving friend we can take her chair\n            while (arrival >= leavingQueue[freeChairIdx][1]) { // to avoid situation when a few friends left already and the next chair in leaving queue is not the smallest\n                const nextChair = chairsByLeaveTime.get(leavingQueue[freeChairIdx][0]);\n                if (chairIdx > nextChair) {\n                    [leavingQueue[leaving], leavingQueue[freeChairIdx]] = [leavingQueue[freeChairIdx], leavingQueue[leaving]]; // swap the front of the queue with the smallest chair owner\n                    chairIdx = nextChair;\n                }\n                ++freeChairIdx;\n            }\n            ++leaving;\n        }\n        if (targetArrival === arrival) { // we found the target, no need to continue\n            return chairIdx;\n        }\n        chairsByLeaveTime.set(arrival, chairIdx); // as far as arrival time is distinct, we can use it as a key\n        arriving++;\n    }\n};",
        "solution_java": "class Solution {\n    public int smallestChair(int[][] times, int targetFriend) {\n        int targetStart = times[targetFriend][0];\n        Arrays.sort(times, (a, b) -> a[0] - b[0]);\n\n        PriorityQueue<Integer> available = new PriorityQueue<>();\n        for (int i = 0; i < times.length; ++ i) {\n            available.offer(i);\n        }\n\n        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n\n        for (int i = 0; i < times.length; ++ i) {\n            while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) {\n                available.offer(pq.poll()[1]);\n            }\n\n            if (times[i][0] == targetStart) {\n                break;\n            }\n\n            pq.offer(new int[]{times[i][1], available.poll()});\n        }\n\n        return available.peek();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int smallestChair(vector<vector<int>>& times, int targetFriend) {\n        \n        int n = times.size();\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > busy; //departure time as first , index as second\n        priority_queue<int, vector<int>, greater<int>> free; //min heap of chair index that are unoccupied\n        \n\t\t//store friend indexes so that they don't get lost after sorting\n        for(int i=0;i<n;++i){\n            times[i].push_back(i);\n        }\n\t\t//Sort according to arrival time\n        sort(times.begin(),times.end());\n        \n\t\tint new_chair = 0; //chairs alloted till now \n        for(int i=0;i<n;++i){\n            int arrival = times[i][0]; //pop chairs before arrival \n            int leave_time = times[i][1];\n            int fr = times[i][2]; //friend index\n            //free chairs accordingly\n            while(!busy.empty() && busy.top().first <= arrival){\n                // cout << \"Chair free \" << busy.top().second << endl;\n                free.push(busy.top().second);\n                busy.pop();\n            }   \n            //No free chair allot new chair\n            if(free.empty()){\n                // cout << \"Alloting new_chair \" << new_chair << \"to\" << fr << endl;\n                if(fr  == targetFriend) return new_chair;\n                busy.push({leave_time,new_chair});\n                new_chair++;\n            }\n            else{\n                int x = free.top();\n                // cout << \"giving chair \" << x << \"to\" << fr << endl;\n                free.pop();\n                if( fr  == targetFriend) return x; \n                busy.push({leave_time,x});\n            }\n        }\n        return -1;\n    }\n    \n};"
    },
    {
        "title": "Minimum Number of Operations to Convert Time",
        "algo_input": "You are given two strings current and correct representing two 24-hour times.\n\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\n\nIn one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.\n\nReturn the minimum number of operations needed to convert current to correct.\n\n&nbsp;\nExample 1:\n\nInput: current = \"02:30\", correct = \"04:35\"\nOutput: 3\nExplanation:\nWe can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.\n\nExample 2:\n\nInput: current = \"11:00\", correct = \"11:01\"\nOutput: 1\nExplanation: We only have to add one minute to current, so the minimum number of operations needed is 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tcurrent and correct are in the format \"HH:MM\"\n\tcurrent &lt;= correct\n\n",
        "solution_py": "class Solution:\n    def HHMMToMinutes(self, s: str) -> int:\n        return int(s[0:2])*60 + int(s[3:5])\n    def convertTime(self, current: str, correct: str) -> int:\n        diff = self.HHMMToMinutes(correct) - self.HHMMToMinutes(current)\n        order = [60,15,5,1]\n        ops = 0\n        for i in range(0,4):\n            ops+=int(diff/order[i])\n            diff%=order[i]\n        return ops",
        "solution_js": "var getTime = function(time){\n    var [hrs,mins] = time.split(\":\");\n    return parseInt(hrs)*60 + parseInt(mins);\n}\n\n\nvar convertTime = function(current, correct) {\n    var diff = getTime(correct) - getTime(current);\n    var order = [60,15,5,1];\n    var ops = 0;\n    order.forEach(val =>{\n        ops+=Math.floor((diff/val));\n        diff%=val;\n    })\n    return ops;\n};",
        "solution_java": "class Solution {\n    public int HHMMToMinutes(String s){\n        return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;\n    }\n    public int convertTime(String current, String correct) {\n        int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);\n        int[] order = {60,15,5,1};\n        int i = 0;\n        int ops = 0;\n        while(i < 4){\n            ops+=(diff/order[i]);\n            diff%=order[i];\n            i++;\n        }\n        return ops;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int HHMMToMinutes(string s){\n        return stoi(s.substr(0,2))*60 + stoi(s.substr(3,2));\n    }\n    int convertTime(string current, string correct) {\n        int diff = - HHMMToMinutes(current) +  HHMMToMinutes(correct);\n        vector<int> order = {60,15,5,1};\n        int i = 0;\n        int ans = 0;\n        while(i < 4){\n            ans+=(diff/order[i]);\n            diff%=order[i];\n            i++;\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum One Bit Operations to Make Integers Zero",
        "algo_input": "Given an integer n, you must transform it into 0 using the following operations any number of times:\n\n\n\tChange the rightmost (0th) bit in the binary representation of n.\n\tChange the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.\n\n\nReturn the minimum number of operations to transform n into 0.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 2\nExplanation: The binary representation of 3 is \"11\".\n\"11\" -&gt; \"01\" with the 2nd operation since the 0th bit is 1.\n\"01\" -&gt; \"00\" with the 1st operation.\n\n\nExample 2:\n\nInput: n = 6\nOutput: 4\nExplanation: The binary representation of 6 is \"110\".\n\"110\" -&gt; \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n\"010\" -&gt; \"011\" with the 1st operation.\n\"011\" -&gt; \"001\" with the 2nd operation since the 0th bit is 1.\n\"001\" -&gt; \"000\" with the 1st operation.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minimumOneBitOperations(self, n: int) -> int:\n        if n <= 1:\n            return n\n        def leftmostbit(x):\n            x |= x >> 1\n            x |= x >> 2\n            x |= x >> 4\n            x |= x >> 8\n            x |= x >> 16\n            x += 1\n            x >>= 1\n            return x\n        x = leftmostbit(n)\n        return ((x << 1) - 1) - self.minimumOneBitOperations(n - x)",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar minimumOneBitOperations = function(n) {\n  let answer = 0;\n  let op = 1;\n  let bits = 30;\n  while(bits >= 0) {\n    if(n & (1 << bits)) {\n      let tmp = (1 << (bits + 1)) - 1;\n      answer += tmp * op;\n      op *= -1;\n    }\n    bits--;\n  }\n  return answer;\n}",
        "solution_java": "class Solution {\n    public int minimumOneBitOperations(int n) {\n\n    int inv = 0;\n\n        // xor until n becomes zero\n        for ( ; n != 0 ; n = n >> 1){\n\n            inv ^= n;\n            System.out.println(inv+\" \"+n);\n        }\n\n        return inv;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumOneBitOperations(int n) {\n        int output = 0;\n        \n        while( n> 0)\n        {\n            output ^= n;\n            n = n >> 1;\n        }\n        \n        return output;\n    }\n};"
    },
    {
        "title": "Number of Islands",
        "algo_input": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.\n\nAn island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n\n&nbsp;\nExample 1:\n\nInput: grid = [\n  [\"1\",\"1\",\"1\",\"1\",\"0\"],\n  [\"1\",\"1\",\"0\",\"1\",\"0\"],\n  [\"1\",\"1\",\"0\",\"0\",\"0\"],\n  [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput: 1\n\n\nExample 2:\n\nInput: grid = [\n  [\"1\",\"1\",\"0\",\"0\",\"0\"],\n  [\"1\",\"1\",\"0\",\"0\",\"0\"],\n  [\"0\",\"0\",\"1\",\"0\",\"0\"],\n  [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 300\n\tgrid[i][j] is '0' or '1'.\n\n",
        "solution_py": "seen=set()\ndef dfs(i,j,m,n,grid):\n    global seen\n    if (i<0 or i>=m or j<0 or j>=n):return\n    if (i,j) in seen:return\n    seen.add((i,j))\n    if grid[i][j]==\"1\":\n        dfs(i,j+1,m,n,grid)\n        dfs(i,j-1,m,n,grid)\n        dfs(i+1,j,m,n,grid)\n        dfs(i-1,j,m,n,grid)\n\nclass Solution:\n    def numIslands(self, grid: List[List[str]]) -> int:\n        global seen\n        m=len(grid) #no of rows\n        n=len(grid[0]) #no of columns\n        count=0\n        for i in range(m):\n            for j in range(n):\n                if (i,j) not in seen and grid[i][j]==\"1\":\n                    dfs(i,j,m,n,grid)\n                    count+=1\n        seen.clear()\n        return count",
        "solution_js": "/**\n * @param {character[][]} grid\n * @return {number}\n */\nvar numIslands = function(grid) {\n    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n    let islandCount = 0\n    \n    for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) {\n        for (let colIndex = 0; colIndex < grid[0].length; colIndex++) {\n            const node = grid[rowIndex][colIndex]\n            \n            // Don't bother with water\n            if (node === \"0\") continue\n            \n            // Once we encounter land, try to get all\n            // the connected land from the current land.\n            // Once we get all the land connected from\n            // the current land, mark them as water so\n            // that it would disregarded by the main loop.\n            islandCount++\n            \n            const connectedLandStack = [[rowIndex, colIndex]]\n            \n            while(connectedLandStack.length > 0) {\n                const [row, col] = connectedLandStack.pop()\n                \n                // change the land to water\n                grid[row][col] = \"0\"\n                \n                for (const direction of directions) {\n                    // To get all the connected land we need to check\n                    //  all directions (left, right, top, bottom)\n                    const newNode = [row + direction[0], col + direction[1]]\n                    const newNodeValue = grid[newNode[0]]?.[newNode[1]]\n                    \n                    // We only care about the connected lands\n                    if (newNodeValue === undefined || newNodeValue === \"0\") {\n                        continue\n                    }\n                    \n                    connectedLandStack.push(newNode)\n                }\n            }\n        }\n    }\n    \n    return islandCount\n};",
        "solution_java": "class Solution {\n    public int numIslands(char[][] grid) {\n        int count = 0;\n        int r = grid.length;\n        int c = grid[0].length;\n        for(int i=0;i<r;i++){\n            for(int j=0;j<c;j++){\n                if(grid[i][j]=='1'){\n                    dfs(grid,i,j);\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n    public void dfs(char[][] grid,int i,int j){\n        if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j]=='0'){\n            return;\n        }\n        grid[i][j] = '0';\n        dfs(grid,i,j+1);\n        dfs(grid,i,j-1);\n        dfs(grid,i+1,j);\n        dfs(grid,i-1,j);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    void calculate(vector<vector<char>>& grid, int i, int j)\n    {\n        if(i>=grid.size() || j>=grid[i].size() || i<0 || j<0)\n            return;\n\n        if(grid[i][j]=='0')\n            return;\n\n        grid[i][j] = '0';\n        calculate(grid,i,j-1);\n        calculate(grid,i-1,j);\n        calculate(grid,i,j+1);\n        calculate(grid,i+1,j);\n\n    }\n\n    int numIslands(vector<vector<char>>& grid) {\n\n        int ans = 0;\n\n        for(int i=0;i<grid.size();i++)\n        {\n            for(int j=0;j<grid[0].size();j++)\n            {\n                if(grid[i][j]=='0')\n                    continue;\n\n                else if (grid[i][j]=='1')\n                {\n                    ans++;\n                    calculate(grid,i,j);\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Repeated String Match",
        "algo_input": "Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.\n\nNotice: string \"abc\" repeated 0 times is \"\", repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\".\n\n&nbsp;\nExample 1:\n\nInput: a = \"abcd\", b = \"cdabcdab\"\nOutput: 3\nExplanation: We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.\n\n\nExample 2:\n\nInput: a = \"a\", b = \"aa\"\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a.length, b.length &lt;= 104\n\ta and b consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def repeatedStringMatch(self, a: str, b: str) -> int:\n        res=\"\"\n        count=0\n        while len(res)<len(b)+len(a):\n            count+=1\n            res=a*count\n            if b in res:\n                return count\n        return -1",
        "solution_js": "var repeatedStringMatch = function(a, b) {\n    const initRepeatTimes = Math.ceil(b.length / a.length);\n    const isMatch = (times) => a.repeat(times).includes(b);\n\n    if (isMatch(initRepeatTimes)) return initRepeatTimes;\n    if (isMatch(initRepeatTimes + 1)) return initRepeatTimes + 1;\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int repeatedStringMatch(String a, String b) {\n        String copyA = a;\n        int count =1;\n        int repeat = b.length()/a.length();\n        for(int i=0;i<repeat+2;i++){\n            if(a.contains(b)){\n                return count;\n            }\n            else{\n                a+=copyA;\n                count++;\n            }\n        }\n        return -1;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int repeatedStringMatch(string a, string b) {\n        int m=a.size(); int n=b.size();\n        vector<int>d; int mod=n%m; int h=n/m;\n\n        if(mod==0)\n        {d.push_back(h); d.push_back(h+1); }\n        else\n        { d.push_back(h+1); d.push_back(h+2); }\n        string s=\"\"; string t=\"\";\n\n        for(int i=0;i<d[0];i++)\n        {s+=a;}\n        for(int i=0;i<d[1];i++)\n        {t+=a;}\n\n        int i=0; int y1=s.size()-n; int y2=t.size()-n;\n\n        while(i<=y1)\n        {\n            string x=s.substr(i,n); //cout<<x;\n            if(x==b){return d[0]; break;}\n            i++;\n        }\n        i=0;\n        while(i<=y2)\n        {\n            string x=t.substr(i,n); //cout<<\"ok1\"<<x;\n            if(x==b){return d[1]; break;}\n            i++;\n        }\n        return -1;\n\n    }\n};"
    },
    {
        "title": "Univalued Binary Tree",
        "algo_input": "A binary tree is uni-valued if every node in the tree has the same value.\n\nGiven the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,1,1,1,1,null,1]\nOutput: true\n\n\nExample 2:\n\nInput: root = [2,2,2,5,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t0 &lt;= Node.val &lt; 100\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n        val1 = root.val\n        self.tracker = False\n        def dfs(root,val1):\n            if not root:\n                return \n            if root.val!=val1:\n                self.tracker=True\n            dfs(root.left,val1)\n            dfs(root.right,val1)\n            return \n        dfs(root,val1)\n        \n        if self.tracker == False:\n            return True\n        return False",
        "solution_js": "var isUnivalTree = function(root) {\n    if (!root) {\n        return false;\n    }\n\n    const prev = root.val;\n    const nodes = [root];\n\n    for (const node of nodes) {\n        if (node.val !== prev) {\n            return false;\n        }\n\n        if (node.left) {\n            nodes.push(node.left);\n        }\n\n        if (node.right) {\n            nodes.push(node.right);\n        }\n    }\n\n    return true;\n};\n    ```",
        "solution_java": "class Solution {\n    boolean ans=true;\n    int firstVal=0;\n    public boolean isUnivalTree(TreeNode root) {\n        if(root==null)\n          return ans; \n        firstVal=root.val;\n        traversal(root);\n      return ans;\n    }\n  private void traversal(TreeNode root)\n  {\n    if(root==null)\n      return;\n    if(root.val!=firstVal)\n        ans=false;\n    traversal(root.left);\n    traversal(root.right);\n  }\n  \n}",
        "solution_c": "class Solution {\npublic:\n    bool recur(TreeNode* root, int value){\n        if(root==NULL)\n            return true;\n        if(root->val!=value){\n            return false;\n        }\n        return recur(root->left,value) &&recur(root->right,value);\n\n    }\n    bool isUnivalTree(TreeNode* root) {\n        if(root==NULL)\n            return true;\n        int value=root->val;\n        return recur(root,value);\n\n    }\n};"
    },
    {
        "title": "Maximum Product After K Increments",
        "algo_input": "You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.\n\nReturn the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.&nbsp;\n\n&nbsp;\nExample 1:\n\nInput: nums = [0,4], k = 5\nOutput: 20\nExplanation: Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\nExample 2:\n\nInput: nums = [6,3,3,2], k = 2\nOutput: 216\nExplanation: Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length, k &lt;= 105\n\t0 &lt;= nums[i] &lt;= 106\n\n",
        "solution_py": "import heapq\n\nclass Solution:\n    def maximumProduct(self, nums, k: int) -> int:\n        \n        # creating a heap\n        heap = []\n        for i in nums:\n            heapq.heappush (heap,i)\n            \n            \n        # basic idea here is keep on incrementing smallest number, then only multiplication of that number will be greater\n        # so basically till I have operations left I will increment my smallest number\n        while k :\n            current = heapq.heappop(heap)\n            heapq.heappush(heap, current+1)\n            k-=1\n            \n        result =1\n        \n        # Just Multiply all the numbers in heap and return the value\n        while len(heap)>0:\n            x= heapq.heappop(heap)\n            result =(result*x )% (10**9+7)\n            \n        return result",
        "solution_js": "var maximumProduct = function(nums, k) {\n  let MOD = Math.pow(10, 9) + 7;\n\n  // build a new minimum priority queue\n  // LeetCode loads MinPriorityQueue by default, no need to implement again\n  let queue = new MinPriorityQueue();\n  for (let i = 0; i < nums.length; i++) {\n    queue.enqueue(nums[i], nums[i]);\n  }\n\n  // To maximize the product, take the smallest element out\n  // add 1 to it and add it back to the queue\n  let count = 0;\n  while (count < k && queue.size() > 0) {\n    let {element, priority} = queue.dequeue();\n    queue.enqueue(element + 1, priority + 1);\n    count += 1;\n  }\n\n  // calculate the product\n  let result = 1;\n  let elements = queue.toArray().map((a) => a.element);\n  for (let i = 0; i < elements.length; i++) {\n    result = (result * elements[i]) % MOD;\n  }\n\n  return result;\n};",
        "solution_java": "class Solution {\n    public int maximumProduct(int[] nums, int k) {\n        \n        Queue<Integer> pq = new PriorityQueue<>();\n        for (int num : nums)    pq.add(num);\n        \n        while (k-->0) {\n            int top = pq.poll() + 1 ;\n            pq.add(top);\n        }\n\n        long res = 1;\n        while (!pq.isEmpty()) {\n            res = (res*pq.poll()) % 1000000007;\n        }\n\n        return (int)(res);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumProduct(vector<int>& nums, int k) {\n\n        priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());\n\n        while(k--) {\n            int mini = pq.top();\n            pq.pop();\n            pq.push(mini + 1);\n        }\n\n        long long ans = 1, mod = 1e9+7;\n\n        while(!pq.empty()) {\n            ans = ((ans % mod) * (pq.top() % mod)) % mod;\n            pq.pop();\n        }\n\n        return (int)ans;\n    }\n};"
    },
    {
        "title": "Maximize Number of Subsequences in a String",
        "algo_input": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.\n\nYou can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.\n\nReturn the maximum number of times pattern can occur as a subsequence of the modified text.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\n&nbsp;\nExample 1:\n\nInput: text = \"abdcdbc\", pattern = \"ac\"\nOutput: 4\nExplanation:\nIf we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.\n\n\nExample 2:\n\nInput: text = \"aabb\", pattern = \"ab\"\nOutput: 6\nExplanation:\nSome of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 105\n\tpattern.length == 2\n\ttext and pattern consist only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n        total = count_a = count_b = 0\n        for c in text:\n            if c == pattern[1]:\n                total += count_a\n                count_b += 1\n            if c == pattern[0]:\n                count_a += 1\n        \n        return total + max(count_a, count_b)",
        "solution_js": "/**\n * @param {string} text\n * @param {string} pattern\n * @return {number}\n */\nvar maximumSubsequenceCount = function(text, pattern) {\n    const arrText = text.split(\"\")\n    const lengthP0 = arrText.filter(x => x === pattern[0]).length\n    const lengthP1 = arrText.filter(x => x === pattern[1]).length\n    const [c1, c2, lengthmax] = lengthP0 <= lengthP1 ? [...pattern, lengthP1]: [pattern[1], pattern[0], lengthP0]\n    let newText = lengthP0 <= lengthP1 ? [c1,...arrText]: [...arrText, c1]\n    newText = lengthP0 <= lengthP1 ? newText : newText.reverse()\n\n    let i = 0;\n    let count = 0;\n    let countmax = lengthmax\n    while(i < newText.length) {\n        if(newText[i] === c1) {\n            count += countmax\n        }\n        if(newText[i] === c2) {\n            countmax--\n        }\n        i++;\n    }\n    return count\n};",
        "solution_java": "class Solution {\n    public long maximumSubsequenceCount(String text, String pattern) {\n        //when pattern[0] == pattern[1]\n        if (pattern.charAt(0) == pattern.charAt(1)) {\n            long freq = 1;\n            //O(N)\n            for (int i = 0; i < text.length(); i++) {\n                if (text.charAt(i) == pattern.charAt(0)) {\n                    freq++;\n                }\n            }\n            //number of subsequences : choose any two characters from freq nC2\n            return (freq * (freq - 1)) / 2;\n        }\n\n        //choice 1\n        String text1 = pattern.charAt(0) + text;\n\n        int freq = 0;\n        long count1 = 0;\n        //O(N)\n        for (int i = 0; i < text1.length(); i++) {\n            if (text1.charAt(i) == pattern.charAt(0)) {\n                freq++;\n            } else if (text1.charAt(i) == pattern.charAt(1)) {\n                count1 += freq;\n            }\n        }\n\n        //choice 2\n        String text2 = text + pattern.charAt(1);\n        freq = 0;\n        long count2 = 0;\n        //O(N)\n        for (int i = text2.length() - 1; i>= 0; i--) {\n            if (text2.charAt(i) == pattern.charAt(1)) {\n                freq++;\n            } else if (text2.charAt(i) == pattern.charAt(0)) {\n                count2 += freq;\n            }\n        }\n\n        return Math.max(count1, count2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long maximumSubsequenceCount(string text, string pattern) {\n        // support variables\n        int len = text.size();\n        long long res = 0, aCount = 0, bCount = 0;\n        char a = pattern[0], b = pattern[1];\n        // getting the frequencies\n        for (char c: text)  {\n            if (c == a) aCount++;\n            else if (c == b) bCount++;\n        }\n        // edge case: a == b\n        if (a == b) return aCount++ * aCount / 2;\n        // adding our extra character to maximise the occurrences\n        if (aCount < bCount) res += bCount;\n        else bCount++;\n        // computing the occurrences\n        for (char c: text)  {\n            // first case: spotting the first element of a sequence\n            if (c == a) {\n                res += bCount;\n            }\n            // second case: we found an ending sequence\n            else if (c == b) bCount--;\n            // all the rest: we do nothing\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Count Largest Group",
        "algo_input": "You are given an integer n.\n\nEach number from 1 to n is grouped according to the sum of its digits.\n\nReturn the number of groups that have the largest size.\n\n&nbsp;\nExample 1:\n\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "def compute(num):\n\tif num < 10:\n\t\treturn num\n\n\tnewVal = 0\n\n\twhile num > 0:\n\t\tlast = num % 10\n\t\tnewVal += last\n\t\tnum /= 10\n\n\treturn newVal\n\nclass Solution(object):\n\tdef countLargestGroup(self, n):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tmyMap = {}\n\n\t\tfor i in range(1, n + 1):\n\t\t\tval = compute(i)\n\n\t\t\tif val in myMap.keys():\n\t\t\t\tmyMap.get(val).append(i)\n\t\t\telse:\n\t\t\t\tmyMap[val] = [i]\n\n\t\tmaxLen = 0\n\n\t\tfor n in myMap.values():\n\t\t\tmaxLen = max(maxLen, len(n))\n\n\t\tans = 0\n\n\t\tfor n in myMap.values():\n\t\t\tif len(n) == maxLen:\n\t\t\t\tans += 1\n\n\t\treturn ans",
        "solution_js": "var countLargestGroup = function(n) {\n    const hash = {};\n\n    for (let i = 1; i <= n; i++) {\n        const sum = i.toString().split('').reduce((r, x) => r + parseInt(x), 0);\n\n        if (!hash[sum]) {\n            hash[sum] = 0;\n        }\n\n        hash[sum]++;\n    }\n\n    return Object.keys(hash)\n        .sort((a, b) => hash[b] - hash[a])\n        .reduce((res, x) => {\n            const prev = res[res.length - 1];\n\n            if (!prev || prev === hash[x]) {\n                res.push(hash[x]);\n            }\n\n            return res;\n        }, []).length;\n};",
        "solution_java": "class Solution {\n    public int countLargestGroup(int n) {\n        Map<Integer,Integer> map=new HashMap<>();\n        for(int i=1;i<=n;i++){\n            int x=sum(i);\n            map.put(x,map.getOrDefault(x,0)+1);\n        }\n        int max=Collections.max(map.values());\n        int c=0;\n        for(int i:map.values()){\n            if(i==max) c++;\n        }\n        return c;\n    }\n    public int sum(int g){\n        int summ=0;\n        while(g!=0){\n            int rem=g%10;\n            summ+=rem;\n            g/=10;\n        }\n        return summ;\n    }\n}```",
        "solution_c": "class Solution {\npublic:\n    int cal(int n){\n        int sum = 0;\n        while(n > 0){\n            sum += n%10;\n            n /= 10;\n        }\n        return sum;\n    }\n\n    int countLargestGroup(int n) {\n        int a[40];\n        for(int i=0; i<40; i++) a[i] = 0;\n\n        for(int i=1; i<=n; i++){\n            a[cal(i)]++;\n        }\n\n        int max = 0;\n        int count = 0;\n        for(int i=0; i<40; i++){\n            if(a[i] > max){\n                count = 1;\n                max = a[i];\n            }\n            else if(a[i] == max) count++;\n        }\n\n        return count;\n    }\n};"
    },
    {
        "title": "Snakes and Ladders",
        "algo_input": "You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.\n\nYou start on square 1 of the board. In each move, starting from square curr, do the following:\n\n\n\tChoose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].\n\n\t\n\t\tThis choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.\n\t\n\t\n\tIf next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.\n\tThe game ends when you reach the square n2.\n\n\nA board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder.\n\nNote that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent&nbsp;snake or ladder.\n\n\n\tFor example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.\n\n\nReturn the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.\n\n&nbsp;\nExample 1:\n\nInput: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput: 4\nExplanation: \nIn the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.\n\n\nExample 2:\n\nInput: board = [[-1,-1],[-1,3]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tn == board.length == board[i].length\n\t2 &lt;= n &lt;= 20\n\tgrid[i][j] is either -1 or in the range [1, n2].\n\tThe squares labeled 1 and n2 do not have any ladders or snakes.\n\n",
        "solution_py": "class Solution:\n    def snakesAndLadders(self, board: List[List[int]]) -> int:\n        \n        # creating a borad map to loop-up the square value\n        board_map = {}\n        i = 1\n        b_rev = board[::-1]\n        for d, r in enumerate(b_rev):\n\t\t\t# reverse for even rows - here d is taken as direction \n            if d%2 != 0: r = r[::-1] \n            for s in r:\n                board_map[i] = s\n                i += 1\n        \n        # BFS Algorithm\n        q = [(1, 0)] # (curr, moves)\n        v = set()\n        goal = len(board) * len(board) # end square\n        \n        while q:\n            curr, moves = q.pop(0)\n            # win situation\n            if curr == goal: return moves\n            # BFS on next 6 places (rolling a die)\n            for i in range(1, 7):\n                # skip square outside board\n                if curr+i > goal: continue\n                # get value from mapping\n                next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i]\n                if next_pos not in v:\n                    v.add(next_pos)\n                    q.append((next_pos, moves+1))\n        \n        return -1\n ",
        "solution_js": "var snakesAndLadders = function(board) {\n    let n = board.length;\n  let seen = new Set();\n  let queue = [[1, 0]];\n\n  while (queue.length) {\n    let [label, step] = queue.shift();\n    //console.log(label, step);\n    let [r, c] = labelToPosition(label, n);\n    //console.log(r, c, n);\n    if (board[r][c] !== -1) {\n      label = board[r][c];\n    }\n    if (label == n * n) {\n      return step;\n    }\n    for (let x = 1; x < 7; x++) {\n      let nextLabel = label + x;\n      if (nextLabel <= n * n && !seen.has(nextLabel)) {\n        seen.add(nextLabel);\n        queue.push([nextLabel, step + 1]);\n      }\n    }\n  }\n  return -1;\n};\n\nconst labelToPosition = (label, n) => {\n  let row = Math.floor((label - 1) / n);\n  let col = (label - 1) % n;\n  //console.log(\"label\", row, col);\n  if (row % 2 === 0) {\n    return [n - 1 - row, col];\n  } else {\n    return [n - 1 - row, n - 1 - col];\n  }\n};",
        "solution_java": "class Solution {\n    //what if we have changed the dice number, or changing the starting index or changing the ending index\n    //so i have covered all possible ways in which this question can be asked\n\n//bfs tip:- for better bfs, we can use marking first and then inserting it in the queue which works faster then removing first and then checking\n    public int [] getans(int dice,HashMap<Integer,Integer> map,int si,int ei){\n        //if si==ei just directly return \n        if(si==ei) return new int [] {0,0,0};\n        LinkedList<int[]> que = new LinkedList<>();\n        que.addLast(new int[] {si,0,0});\n        int level = 0;\n        //to stop visiting cells again\n        boolean [] vis = new boolean [ei+1];\n        vis[si]=true;\n        //starting bfs\n        while(que.size()!=0){\n            int size=que.size();\n            while(size-->0){\n                int [] rem = que.removeFirst();\n                int idx= rem[0];\n                int lad = rem[1];\n                int sna = rem[2];\n                for(int i=1;i<=dice;i++){\n                    int x =i+rem[0]; //checking all the steps\n                    if(x<=ei){ //valid points\n                        if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder\n                            if(map.containsKey(x)){\n                                int val = map.get(x); \n                                if(val==ei) return new int[] {level+1,lad+1,sna};\n                                if(!vis[val]){\n                                    vis[val]=true;\n                                    //if val>x this means we have a ladder and if less, then it is a snake\n                                    que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});\n                                }\n                            }\n                        }\n                        else{\n                            //if it is not present in map, then it is a normal cell, so just insert it directly\n                            if(x==ei) return new int [] {level+1,lad,sna};\n                            if(!vis[x]){\n                                vis[x]=true;\n                                que.addLast(new int [] {x,lad,sna});\n                            }\n                        }\n                    }\n                }\n            }\n            level++;\n        }\n        return new int [] {-1,0,0};\n    }\n    public int snakesAndLadders(int[][] board) {\n        HashMap<Integer,Integer> map = new HashMap<>();\n        int count = 1;\n        int n = board.length;\n        boolean flag = true;\n        //traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)\n        for(int i=n-1;i>=0;i--){\n            //traversing in the order of the board\n            if(flag){\n                for(int j=0;j<n;j++){\n                    if(board[i][j]!=-1){\n                        map.put(count,board[i][j]);   \n                    }\n                    count++;\n                    flag=false;\n                }\n            }\n            else{\n                //reversing the direction\n                for(int j=n-1;j>=0;j--){\n                    if(board[i][j]!=-1){\n                        map.put(count,board[i][j]);\n                    }\n                    flag=true;\n                    count++;\n                }\n            }\n        }\n        //if snake on destination then just return -1;\n        if(board[0][0]!=-1) return -1;\n        //we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used} \n        int [] ans = getans(6,map,1,n*n);;\n        return ans[0];\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int snakesAndLadders(vector<vector<int>>& board) {\n        unordered_map<int, int> mp;\n        int n = board.size();\n        for(int i = n-1; i >= 0; i--) {\n            for(int j = 0; j < n; j++) {\n                if(board[i][j] != -1) {\n                    int val;\n                    if((n-i)%2 != 0) val = (n-i-1)*n + j + 1;\n                    else val = (n-i-1)*n + n - j;\n                    mp[val] = board[i][j];\n                }\n            }\n        }\n        queue<pair<int, int>> q;\n        vector<int> visited(n*n+1, false);\n        q.push({1, 0});\n        while(!q.empty()) {\n            int node = q.front().first;\n            int moves = q.front().second;\n            q.pop();\n            if(node == n*n) return moves;\n            if(visited[node]) continue;\n            visited[node] = true;\n            for(int k = 1; k <= 6; k++) {\n                if(node+k > n*n) continue;\n                int x = node + k;\n                if(mp.find(x) != mp.end()) x = mp[x];\n                q.push({x, moves+1});\n            }\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Non-negative Integers without Consecutive Ones",
        "algo_input": "Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: 5\nExplanation:\nHere are the non-negative integers &lt;= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n\n\nExample 2:\n\nInput: n = 1\nOutput: 2\n\n\nExample 3:\n\nInput: n = 2\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def findIntegers(self, n: int) -> int:\n        b=(bin(n).replace(\"0b\",\"\"))\n        dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)]\n        def fun(i,last,tight,leading_zeros):\n            if i==len(str(b)):\n                return 1\n            if dp[i][tight][leading_zeros][last]!=-1:\n                return dp[i][tight][leading_zeros][last]\n            end=1\n            if tight==1:\n                end = int(b[i])\n            res=0\n            for j in range(end+1):\n                if j==0 and leading_zeros==1:\n                    res+=fun(i+1,j,tight&int(j==end),1)\n                else:\n                    if j==0:\n                        res+=fun(i+1,j,tight&int(j==end),0)\n                    else:\n                        if last!=j:\n                            res+=fun(i+1,j,tight&int(j==end),0)\n            dp[i][tight][leading_zeros][last] = res\n            return res\n        return fun(0,0,1,1)",
        "solution_js": "var findIntegers = function(n) {\n    let dp = len=>{\n        if (len<0)\n            return 0;\n        if (!len)\n            return 1;\n        let _0x = 1; // number of accepted combination when '1' is first\n        let _1x = 1; // number of accepted combination when '0' is first\n        while (--len)\n            [_0x, _1x] = [_0x+_1x, _0x];\n        return _0x + _1x;\n    };\n    let binary = n.toString(2);\n    let count = 0;\n    let is_prev_one = false;\n    for (let i = 0; i<binary.length; i++) {\n        if (binary[i] === '0') {\n            is_prev_one = false;\n            continue;\n        }\n        count += dp(binary.length-i-1);\n        if (is_prev_one)\n            return count;\n        is_prev_one = true;\n    }\n    return count + 1;\n};",
        "solution_java": "class Solution {\n    public int findIntegers(int n) {\n        int val=0,res=0,cn=n,digi=0,prevdig=0,i;//digi means bin digi\n        while(cn>0){\n            cn=cn>>1;\n            digi++;\n        }\n        int dp[]=new int[digi+1];\n        dp[0]=1;dp[1]=2;\n        for(i=2;i<=digi;i++)\n            dp[i]=dp[i-1]+dp[i-2];\n        digi++;\n        while(digi-->=0){\n            if((n&(1<<digi))>0){\n                res+=dp[digi];\n                if(prevdig==1)return res;\n                prevdig=1;\n            }else prevdig=0;\n        }\n        \n        return res+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[31][2];\n    vector<int> f(){ \n        vector<int> res(31, 1);\n        dp[1][0]=0;\n        dp[1][1]=1;\n        for(int i=2; i<31; i++){\n            dp[i][0]=dp[i-1][0]+dp[i-1][1];\n            dp[i][1]=dp[i-1][0];\n        }\n        \n        \n        for(int i=1; i<31; i++){\n            res[i]=res[i-1]+dp[i][0]+dp[i][1];\n        }\n\n        res[1]=2;\n        return res;\n    }\n    \n    int findIntegers(int n) {\n        int res=0;\n        int bits=0;\n        int temp=n;\n        vector<int> v;\n        while(temp>0){\n            bits++;\n            v.push_back(temp&1);\n            temp=temp>>1;\n        }\n        vector<int> nums=f();\n        \n        bool valid=true, isValid=true;\n\n        for(int i=bits-2;i>=0;i--){\n            if(v[i]==1 && v[i+1]==1){\n                res+=nums[i];\n                isValid=false;\n                break;\n            }else if(v[i]==1)\n                res+=nums[i];\n        }\n        \n        res+=nums[bits-1];\n        return isValid==true ? res+1:res;\n    }\n};"
    },
    {
        "title": "Number of Restricted Paths From First to Last Node",
        "algo_input": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.\n\nA path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 &lt;= i &lt;= k-1.\n\nThe distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) &gt; distanceToLastNode(zi+1) where 0 &lt;= i &lt;= k-1.\n\nReturn the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput: 3\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --&gt; 2 --&gt; 5\n2) 1 --&gt; 2 --&gt; 3 --&gt; 5\n3) 1 --&gt; 3 --&gt; 5\n\n\nExample 2:\n\nInput: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput: 1\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --&gt; 3 --&gt; 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 104\n\tn - 1 &lt;= edges.length &lt;= 4 * 104\n\tedges[i].length == 3\n\t1 &lt;= ui, vi &lt;= n\n\tui != vi\n\t1 &lt;= weighti &lt;= 105\n\tThere is at most one edge between any two nodes.\n\tThere is at least one path between any two nodes.\n\n",
        "solution_py": "class Solution:\n    def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n        \n        dct_nd    = {}\n        dist_to_n = {}\n        queue     = deque() # from n-node to 1-node\n        visited   = set()\n        \n        # 1 step: create dictionary with nodes and nodes' distances to n\n\n        # create dictionary with format (weight, node_to)\n        # heap will automatically sort weight and node_to in ascending order\n        for l, r, w in edges:\n            dct_nd[l] = dct_nd.get(l, []) + [(w, r)]\n            dct_nd[r] = dct_nd.get(r, []) + [(w, l)]\n        \n        dist_to_n[n] = 0\n        queue.append(n)\n        visited.add(n)\n        \n        hpf = dct_nd[n].copy()   # without '.copy()' hpf will be only pointer and dct_nd[n] could change\n        heapify(hpf)\n        while hpf:\n            el_w, el_nd = heappop(hpf)\n            if el_nd in visited:   continue\n            \n            dist_to_n[el_nd] = el_w\n            visited.add(el_nd)\n            queue.append(el_nd)\n\n            if el_nd == 1:         break  # you don't need to traverse more if you've reached 1-node\n                                          # other distances will be more than distance of 1-node\n            for (i_w, i_nd) in dct_nd[el_nd]:\n                if i_nd not in visited:\n                    heappush(hpf, (el_w + i_w, i_nd))\n        # step 1: end\n\n        # add to dictionary one more field: number of routes to n\n        dist_to_n = {k: [v, 0]   for k, v in dist_to_n.items()}\n        dist_to_n[n] = [dist_to_n[n][0], 1]  # for n-node number of routes = 1\n        \n        # step 2: Dynamic Programming\n        visited.clear()\n        while queue:\n            # start from n and traverse futher and futher\n            nd_prv = queue.popleft()\n            visited.add(nd_prv)\n            for (w_cur, nd_cur) in dct_nd[nd_prv]:\n                if nd_cur not in visited           and   \\\n                   nd_cur     in dist_to_n.keys()  and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:\n                    # to current node add number of routes from previous node\n                    dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]\n                    # !!! careful !!! you need to add modulo operation (as said in the task)\n                    dist_to_n[nd_cur][1]  = int(dist_to_n[nd_cur][1] % (1e9+7))\n        # step 2: End\n        \n        return dist_to_n[1][1] # return number of routes for 1-node",
        "solution_js": "var countRestrictedPaths = function(n, edges) {\n    // create an adjacency list to store the neighbors with weight for each node\n    const adjList = new Array(n + 1).fill(null).map(() => new Array(0));\n    for (const [node1, node2, weight] of edges) {\n        adjList[node1].push([node2, weight]);\n        adjList[node2].push([node1, weight]);\n    }\n    \n    // using djikstras algorithm\n    // find the shortest path from n to each node\n    const nodeToShortestPathDistance = {}\n    const heap = new Heap();\n    heap.push([n, 0])\n    let numNodeSeen = 0;\n    while (numNodeSeen < n) {\n        const [node, culmativeWeight] = heap.pop();\n        if (nodeToShortestPathDistance.hasOwnProperty(node)) {\n            continue;\n        }\n        nodeToShortestPathDistance[node] = culmativeWeight;\n        numNodeSeen++;\n        for (const [neighbor, edgeWeight] of adjList[node]) {\n            if (nodeToShortestPathDistance.hasOwnProperty(neighbor)) {\n                continue;\n            }\n            heap.push([neighbor, edgeWeight + culmativeWeight]);\n        }\n    }\n    \n\n    // do a DFS caching the number of paths for each node\n    // so that we don't need to redo the number of paths again\n    // when we visit that node through another path\n    const nodeToNumPaths = {};\n    const dfs = (node) => {\n        if (node === n) return 1;\n        if (nodeToNumPaths.hasOwnProperty(node)) {\n            return nodeToNumPaths[node];\n        }\n        let count = 0;\n        for (const [neighbor, weight] of adjList[node]) {\n            if (nodeToShortestPathDistance[node] > nodeToShortestPathDistance[neighbor]) {\n                count += dfs(neighbor);\n            }\n        }\n        return nodeToNumPaths[node] = count % 1000000007;\n    }\n    return dfs(1);\n};\n\nclass Heap {\n    constructor() {\n        this.store = [];\n    }\n    \n    peak() {\n        return this.store[0];\n    }\n    \n    size() {\n        return this.store.length;\n    }\n    \n    pop() {\n        if (this.store.length < 2) {\n            return this.store.pop();\n        }\n        const result = this.store[0];\n        this.store[0] = this.store.pop();\n        this.heapifyDown(0);\n        return result;\n    }\n    \n    push(val) {\n        this.store.push(val);\n        this.heapifyUp(this.store.length - 1);\n    }\n    \n    heapifyUp(child) {\n        while (child) {\n            const parent = Math.floor((child - 1) / 2);\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                child = parent;\n            } else {\n                return child;\n            }\n        }\n    }\n    \n    heapifyDown(parent) {\n        while (true) {\n            let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n            if (this.shouldSwap(child2, child)) {\n                child = child2\n            }\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                parent = child;\n            } else {\n                return parent;\n            }\n        }\n    }\n    \n    shouldSwap(child, parent) {\n        return child && this.store[child][1] < this.store[parent][1];\n    }\n}",
        "solution_java": "class Solution {\n    int dp[];\n    //We use memoization\n    public int countRestrictedPaths(int n, int[][] edges) {\n        int[] dist = new int[n+1];\n        dp = new int[n+1];\n        Arrays.fill(dp,-1);\n        Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();\n        //Create the graph from input edges\n        for(int[] e : edges){\n            graph.putIfAbsent(e[0], new HashMap<>());\n            graph.putIfAbsent(e[1], new HashMap<>());\n            graph.get(e[0]).put(e[1],e[2]);\n            graph.get(e[1]).put(e[0],e[2]);\n        }\n        //Single source shortest distance - something like Dijkstra's\n        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));\n        int[] base = new int[2];\n        base[0]=n;\n        pq.offer(base);\n        while(!pq.isEmpty()){\n            int[] currNode = pq.poll();\n\n            for(Map.Entry<Integer, Integer> neighbour: graph.get(currNode[0]).entrySet()){\n                int node = neighbour.getKey();\n                int d = neighbour.getValue()+currNode[1];\n                if(node==n) continue;\n                //Select only those neighbours, whose new distance is less than existing distance\n                //New distance = distance of currNode from n + weight of edge between currNode and neighbour\n\n                if( dist[node]==0 || d < dist[node]){\n                    int[] newNode = new int[2];\n                    newNode[0]=node;\n                    newNode[1]=d;\n                    pq.offer(newNode);\n                    dist[node]= d;\n                }\n            }\n        }\n\n        return find(1,graph,n,dist);\n    }\n    //This method traverses all the paths from source node to n though it's neigbours\n    private int find(int node, Map<Integer, Map<Integer, Integer>> graph, int n, int[] dist ){\n        if(node==n){\n            return 1;\n        }\n\n        //Memoization avoid computaion of common subproblems.\n        if(dp[node]!=-1) return dp[node];\n\n        int ans = 0;\n        for(Map.Entry<Integer, Integer> neighbour: graph.get(node).entrySet()){\n                int currNode = neighbour.getKey();\n                int d = dist[currNode];\n                if( dist[node] > d){\n                    ans = (ans + find(currNode, graph, n, dist)) % 1000000007;\n            }\n        }\n\n        return dp[node] = ans;\n    }\n}",
        "solution_c": "typedef pair<int, int> pii;\nclass Solution {\npublic:\n    int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n        unordered_map<int, vector<pair<int, int>>> gp;\n        for (auto& edge : edges) {\n            gp[edge[0]].push_back({edge[1], edge[2]});\n            gp[edge[1]].push_back({edge[0], edge[2]});\n        }\n\n        vector<int> dist(n + 1, INT_MAX);\n        priority_queue<pii, vector<pii>, greater<pii> > pq;\n        pq.push({0, n});\n        dist[n] = 0;\n\n        int u, v, w;\n        while (!pq.empty()) {\n            pii p = pq.top(); pq.pop();\n            u = p.second;\n            for (auto& to : gp[u]) {\n                v = to.first, w = to.second;\n                if (dist[v] > dist[u] + w) {\n                    dist[v] = dist[u] + w;\n                    pq.push({dist[v], v});\n                }\n            }\n        }\n        vector<int> dp(n + 1, -1);\n        return dfs(gp, n, dp, dist);\n    }\n\n    int dfs(unordered_map<int, vector<pair<int, int>>>& gp, int s, vector<int>& dp, vector<int>& dist) {\n        int mod = 1e9+7;\n        if (s == 1) return 1;\n        if (dp[s] != -1) return dp[s];\n        int sum = 0, weight, val;\n        for (auto& n : gp[s]) {\n            weight = dist[s];\n            val = dist[n.first];\n            if (val > weight) {\n                sum = (sum % mod + dfs(gp, n.first, dp, dist) % mod) % mod;\n            }\n        }\n        return dp[s] = sum % mod;\n    }\n};"
    },
    {
        "title": "Frequency of the Most Frequent Element",
        "algo_input": "The frequency of an element is the number of times it occurs in an array.\n\nYou are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.\n\nReturn the maximum possible frequency of an element after performing at most k operations.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,4], k = 5\nOutput: 3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.\n\nExample 2:\n\nInput: nums = [1,4,8,13], k = 5\nOutput: 2\nExplanation: There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n\n\nExample 3:\n\nInput: nums = [3,9,6], k = 2\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\t1 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maxFrequency(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        sums, i, ans = 0, 0, 0\n        for j in range(len(nums)):\n            sums += nums[j]\n            while nums[j]*(j-i+1) > sums+k:\n                sums -= nums[i]\n                i = i+1\n            ans = max(ans, j-i+1)\n        return ans",
        "solution_js": "var maxFrequency = function(nums, k) {\n// We sorted because as we are allowed only to increment the value & we try to increase the smaller el to some larger el\n    nums.sort((a,b)=>a-b);\n    \n    let left=0;\n    let max=Math.max(); // without any args, Math.max() is -Infinity\n    let curr=0;\n\t// I have used 'for loop' so rightPtr is 'i' here\n    for(let i=0;i<nums.length;i++){\n        curr+=nums[i];\n\t\t// decrement the winSize once the value required to convert could not be achieved even after utilizing K\n\t\t// (i-left+1) * nums[i] because we are converting every el upto that winSize by current el\n        while((i-left+1) * nums[i] > curr+k){\n            curr-=nums[left++]\n        }        \n        max = Math.max(max,i-left+1);\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maxFrequency(int[] nums, int k) {\n        //Step-1: Sorting->\n        Arrays.sort(nums);\n        //Step-2: Two-Pointers->\n        int L=0,R=0;\n        long totalSum=0;\n        int res=1;\n        //Iterating over the array:\n        while(R<nums.length)\n        {\n            totalSum+=nums[R];\n            //The value of \"totalSum+k\" should be \">=\" \"windowSize*nums[R]\"\n            //then only the window is possible else decrease the \"totalSum\"\n            //till the value \"totalSum+k\" is \">=\" \"windowSize*nums[R]\"\n            while(! ((totalSum+k) >= ((R-L+1)*nums[R])) )\n            {\n                totalSum-=nums[L];\n                L++;\n            }\n            res=Math.max(res,(R-L+1));\n            R++;\n        }\n        return res;\n    }\n}",
        "solution_c": "#define ll long long\n\nclass Solution {\npublic:\n    int maxFrequency(vector<int>& nums, int k) {\n        // sorting so that can easily find the optimal window\n        sort(nums.begin(), nums.end());\n\n        // left - left pointer of window\n        // right - right pointer of window\n        int left = 0, right = 0, ans = 1;\n        ll total = 0, n = nums.size();\n        while(right < n){\n            // total - total sum of elements in the window\n            total += nums[right];\n\n            // Checking if the we can achieve elements in this window\n            // If it exceeds k then shrinking the window by moving left pointer\n            // For optimal we will make all elements in the array equal to\n            // the maximum value element\n            while((1ll)*(right - left + 1)*nums[right] - total > k){\n                total -= nums[left];\n                left++;\n            }\n\n            ans = max(ans, right - left + 1);\n            right++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Remove Invalid Parentheses",
        "algo_input": "Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\n\nReturn all the possible results. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: s = \"()())()\"\nOutput: [\"(())()\",\"()()()\"]\n\n\nExample 2:\n\nInput: s = \"(a)())()\"\nOutput: [\"(a())()\",\"(a)()()\"]\n\n\nExample 3:\n\nInput: s = \")(\"\nOutput: [\"\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 25\n\ts consists of lowercase English letters and parentheses '(' and ')'.\n\tThere will be at most 20 parentheses in s.\n\n",
        "solution_py": "class Solution:\n    def removeInvalidParentheses(self, s: str) -> List[str]:\n        ## RC ##\n        ## APPROACH : BACK-TRACKING ##\n        ## Similar to Leetcode 32. Longest Valid Parentheses ##\n        ## LOGIC ##\n        #   1. use stack to find invalid left and right braces.\n        #   2. if its close brace at index i , you can remove it directly to make it valid and also you can also remove any of the close braces before that i.e in the range [0,i-1]\n        #   3. similarly for open brace, left over at index i, you can remove it or any other open brace after that i.e [i+1, end]\n        #   4. if left over braces are more than 1 say 2 close braces here, you need to make combinations of all 2 braces before that index and find valid parentheses.\n        #   5. so, we count left and right invalid braces and do backtracking removing them\n        \n\t\t## TIME COMPLEXITY : O(2^N) ## (each brace has 2 options: exits or to be removed)\n\t\t## SPACE COMPLEXITY : O(N) ##\n\n        def isValid(s):\n            stack = []\n            for i in range(len(s)):\n                if( s[i] == '(' ):\n                    stack.append( (i,'(') )\n                elif( s[i] == ')' ):\n                    if(stack and stack[-1][1] == '('):\n                        stack.pop()\n                    else:\n                        stack.append( (i,')') )         # pushing invalid close braces also\n            return len(stack) == 0, stack\n        \n        \n        def dfs( s, left, right):\n            visited.add(s)\n            if left == 0 and right == 0 and isValid(s)[0]:  res.append(s)\n            for i, ch in enumerate(s):\n                if ch != '(' and ch != ')': continue                                    # if it is any other char ignore.\n                if (ch == '(' and left == 0) or (ch == ')' and right == 0): continue    # if left == 0 then removing '(' will only cause imbalance. Hence, skip.\n                if s[:i] + s[i+1:] not in visited:\n                    dfs( s[:i] + s[i+1:], left - (ch == '('), right - (ch == ')') )\n        \n        stack = isValid(s)[1]\n        lc = sum([1 for val in stack if val[1] == \"(\"]) # num of left braces\n        rc = len(stack) - lc\n        \n        res, visited = [], set()\n        dfs(s, lc, rc)\n        return res",
        "solution_js": "var removeInvalidParentheses = function(s) {\n    const isValid = (s) => {\n        const stack = [];\n        for(let c of s) {\n            if(c == '(') stack.push(c);\n            else if(c == ')') {\n                if(stack.length && stack.at(-1) == '(')\n                    stack.pop();\n                else return false;\n            }\n        }\n        return stack.length == 0;\n    }\n\n    const Q = [s], vis = new Set([s]), ans = [];\n    let found = false;\n    while(Q.length) {\n        const top = Q.shift();\n        if(isValid(top)) {\n            ans.push(top);\n            found = true;\n        }\n        if(found) continue;\n        for(let i = 0; i < top.length; i++) {\n            if(!'()'.includes(top[i])) continue;\n\n            const str = top.slice(0, i) + top.slice(i + 1);\n            if(!vis.has(str)) {\n                Q.push(str);\n                vis.add(str);\n            }\n        }\n    }\n    if(ans.length == 0) return [''];\n    return ans;\n};",
        "solution_java": "class Solution {\n    public List<String> removeInvalidParentheses(String s) {\n        List<String> ans=new ArrayList<>();\n        HashSet<String> set=new HashSet<String>();\n        \n        int minBracket=removeBracket(s);\n        getAns(s, minBracket,set,ans);\n        \n        return ans;\n    }\n    \n    public void getAns(String s, int minBracket, HashSet<String> set, List<String> ans){\n        if(set.contains(s)) return;\n        \n        set.add(s);\n        \n        if(minBracket==0){\n            int remove=removeBracket(s);   \n            if(remove==0) ans.add(s);\n            return;\n        }\n        \n        for(int i=0;i<s.length();i++){\n            if(s.charAt(i)!='(' && s.charAt(i)!=')') continue;\n            String L=s.substring(0,i);\n            String R=s.substring(i+1);\n            \n            if(!set.contains(L+R)) getAns(L+R,minBracket-1,set,ans);\n        }\n    }\n    \n    public int removeBracket(String s){\n        Stack<Character> stack=new Stack<>();\n        \n        for(int i=0;i<s.length();i++){\n            char x=s.charAt(i);\n            \n            if(x=='(') stack.push(x);\n            else if(x==')'){\n                if(!stack.isEmpty() && stack.peek()=='(') stack.pop();\n                else stack.push(x);\n            } \n        }\n        return stack.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void back_tracking(vector<string>& res, string cus, int lp, int rp, int idx) {\n        if (!lp && !rp) {\n            int invalid = 0;\n            bool flag = true;\n            for (int i = 0; i < cus.size(); i++) {\n                if (cus[i] == '(')\n                    invalid++;\n                else if (cus[i] == ')') {\n                    invalid--;\n                    if (invalid < 0) {\n                        flag = false;\n                        break;\n                    }\n                }\n            }\n            if (flag)\n                res.emplace_back(cus);\n            return;\n        }\n        \n        for (int i = idx; i < cus.size(); i++) {\n            if (i != idx && cus[i] == cus[i - 1])\n                continue;\n            \n            if (lp + rp > cus.size() - i)\n                return;\n            \n            if (lp && cus[i] == '(')\n                back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp - 1, rp, i);\n            \n            if (rp && cus[i] == ')')\n                back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp, rp - 1, i);\n        }\n    }\n    \n    vector<string> removeInvalidParentheses(string s) {\n        int left_p = 0;\n        int right_p = 0;\n        for (auto& ch : s) {\n            if (ch == '(')\n                left_p++;\n            else if (ch == ')') {\n                if (left_p > 0)\n                    left_p--;\n                else\n                    right_p++;\n            }\n        }\n        vector<string> res;\n        back_tracking(res, s, left_p, right_p, 0);\n        return res;\n    }\n};"
    },
    {
        "title": "Check If Two String Arrays are Equivalent",
        "algo_input": "Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.\n\nA string is represented by an array if the array elements concatenated in order forms the string.\n\n&nbsp;\nExample 1:\n\nInput: word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\nOutput: true\nExplanation:\nword1 represents string \"ab\" + \"c\" -&gt; \"abc\"\nword2 represents string \"a\" + \"bc\" -&gt; \"abc\"\nThe strings are the same, so return true.\n\nExample 2:\n\nInput: word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput: false\n\n\nExample 3:\n\nInput: word1  = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word1.length, word2.length &lt;= 103\n\t1 &lt;= word1[i].length, word2[i].length &lt;= 103\n\t1 &lt;= sum(word1[i].length), sum(word2[i].length) &lt;= 103\n\tword1[i] and word2[i] consist of lowercase letters.\n\n",
        "solution_py": "class Solution:\n    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n        return True if \"\".join(word1) == \"\".join(word2) else False",
        "solution_js": "var arrayStringsAreEqual = function(word1, word2) {\n    return word1.join('') === word2.join('')\n};",
        "solution_java": "class Solution {\n    public boolean arrayStringsAreEqual(String[] word1, String[] word2)\n    {\n        return(String.join(\"\", word1).equals(String.join(\"\", word2)));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) \n    {\n        int wordIdx1 = 0, wordIdx2 = 0, chIdx1 = 0, chIdx2 = 0;\n        while(true)\n        {\n            char ch1 = word1[wordIdx1][chIdx1];\n            char ch2 = word2[wordIdx2][chIdx2];\n            if (ch1 != ch2) return false;\n            \n            chIdx1++; //incrementing the character index of current word from \"word1\"\n            chIdx2++; //incrementing the character index of current word from \"word2\";\n            //=========================================================\n            if (chIdx1 == word1[wordIdx1].size()) //if current word from \"word1\" is over\n            { \n                wordIdx1++;  //move to next word in \"word1\"\n                chIdx1 = 0;  //reset character index to 0\n            }\n            if (chIdx2 == word2[wordIdx2].size()) //if  current word from \"word2\" is over\n            { \n                wordIdx2++;  //move to next word  in \"word2\"\n                chIdx2 = 0; //reset character index to 0\n            }\n            //=================================================================\n            if (wordIdx1 == word1.size() && wordIdx2 == word2.size()) break; // words in both arrays are finished\n            \n            if (wordIdx1 == word1.size() || wordIdx2 == word2.size()) return false;\n            //if words in any onr of the arrays are finished and other still has some words in it\n            //then there is no way same string could be formed on concatenation\n        }\n        return true; \n    }\n};"
    },
    {
        "title": "Word Subsets",
        "algo_input": "You are given two string arrays words1 and words2.\n\nA string b is a subset of string a if every letter in b occurs in a including multiplicity.\n\n\n\tFor example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\".\n\n\nA string a from words1 is universal if for every string b in words2, b is a subset of a.\n\nReturn an array of all the universal strings in words1. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\nOutput: [\"facebook\",\"google\",\"leetcode\"]\n\n\nExample 2:\n\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\nOutput: [\"apple\",\"google\",\"leetcode\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words1.length, words2.length &lt;= 104\n\t1 &lt;= words1[i].length, words2[i].length &lt;= 10\n\twords1[i] and words2[i] consist only of lowercase English letters.\n\tAll the strings of words1 are unique.\n\n",
        "solution_py": "class Solution:\n    def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:\n        freq = [0]*26 \n        \n        for w in B: \n            temp = [0]*26\n            for c in w: temp[ord(c)-97] += 1\n            for i in range(26): freq[i] = max(freq[i], temp[i])\n                \n        ans = []\n        for w in A: \n            temp = [0]*26\n            for c in w: temp[ord(c)-97] += 1\n            if all(freq[i] <= temp[i] for i in range(26)): ans.append(w)\n        return ans ",
        "solution_js": "var wordSubsets = function(words1, words2) {\n    this.count = Array(26).fill(0);\n    let tmp = Array(26).fill(0);\n    for(let b of words2){\n        tmp = counter(b);\n        for(let i=0; i<26; i++)\n            count[i] = Math.max(count[i], tmp[i]);\n    }\n    let list = []\n    for(let a of words1)\n        if(isSub(counter(a)))\n            list.push(a);\n    return list;\n};\n\nfunction isSub(tmp){\n    for(let i=0; i<26; i++)\n        if(tmp[i] < this.count[i])\n            return false;\n    return true;\n};\n\nfunction counter(s){\n    let tmp = Array(26).fill(0);\n    for(let c of s)\n        tmp[c.charCodeAt() - 97]++;\n    return tmp;\n};",
        "solution_java": "class Solution {\n    public List<String> wordSubsets(String[] words1, String[] words2) {\n        List<String> list=new ArrayList<>();\n        int[] bmax=count(\"\");\n        for(String w2:words2)\n        {\n            int[] b=count(w2);\n            for(int i=0;i<26;i++)\n            {\n                bmax[i]=Math.max(bmax[i],b[i]);\n            }\n        }\n        for(String w1:words1)\n        {\n            int[] a=count(w1);\n            for(int i=0;i<26;i++)\n            {\n                if(a[i]<bmax[i])\n                {\n                    break;\n                }\n                  if(i==25)\n             {\n                 list.add(w1);\n             }\n            } \n        }\n        return list;\n    }\n    public int[] count(String s)\n    {\n        int[] ans=new int[26];\n        for(char c:s.toCharArray())\n        {\n            ans[c-'a']++;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    // calculate the frequency of string s\n    vector<int> giveMeFreq(string s)\n    {\n        vector<int> freq(26,0);\n        for(int i = 0; i < s.length(); i++)\n        {\n            freq[s[i] - 'a']++;\n        }\n        return freq;\n    }\n    \n    vector<string> wordSubsets(vector<string>& words1, vector<string>& words2) \n    {\n       vector<string> ans; // store ans\n       vector<int> max_Freq_w2(26, 0);   // store max freq of each character present in word2 stirngs\n\t   \n        // we will Iterate over word to and try to find max freq for each character present in all strings.\n\t\tfor(auto &x : words2) \n        {\n            vector<int> freq = giveMeFreq(x);\n            for(int i = 0; i < 26; i++)\n            {\n                max_Freq_w2[i] = max(freq[i], max_Freq_w2[i]);  // upadate freq to max freq\n            }\n        }\n        \n\t\t// we will iterate for each string in words1 ans if it have all charaters present in freq array with freq >= that     then we will add it to ans\n        for(auto &x : words1)\n        {\n            vector<int> freq = giveMeFreq(x);  // gives freq of characters for word in words1\n            bool flag = true;\n            for(int i = 0; i < 26; i++)\n            {\n                if(freq[i] < max_Freq_w2[i]) // specifies that word did not have all the characters from word2 array\n                {\n                    flag = false;\n                    break;\n                }\n            }\n            if(flag) ans.push_back(x);   // string x is Universal string\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Distant Barcodes",
        "algo_input": "In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].\n\nRearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.\n\n&nbsp;\nExample 1:\nInput: barcodes = [1,1,1,2,2,2]\nOutput: [2,1,2,1,2,1]\nExample 2:\nInput: barcodes = [1,1,1,1,2,2,3,3]\nOutput: [1,3,1,3,1,2,1,2]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= barcodes.length &lt;= 10000\n\t1 &lt;= barcodes[i] &lt;= 10000\n\n",
        "solution_py": "import heapq\n\nclass Solution:\n\n    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n        barcodes_counter = Counter(barcodes)\n        if len(barcodes_counter) == len(barcodes):\n            return barcodes\n\n        barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ]\n        heapq.heapify(barcodes_heapq)\n\n        idx, prev_count, prev_barcode = 0, 0, 0\n        while barcodes_heapq:\n            (curr_count, curr_barcode) = heapq.heappop(barcodes_heapq)\n\n            barcodes[idx] = curr_barcode\n            idx += 1\n            curr_count += 1\n\n            if prev_count:\n                heapq.heappush(barcodes_heapq, (prev_count, prev_barcode))\n\n            prev_count, prev_barcode = curr_count, curr_barcode\n\n        return barcodes",
        "solution_js": "var rearrangeBarcodes = function(barcodes) {\n    var result = [];\n    var map = new Map();\n    barcodes.forEach(n => map.set(n, map.get(n) + 1 || 1));\n    let list = [...map.entries()].sort((a,b) => {return b[1]-a[1]})\n    let i = 0; //list[i][0]=>number list[i][1]=>count of this number\n    while(result.length!==barcodes.length){\n        if(list[i][1]>0) result.push(list[i][0]), list[i][1]--;\n        i++;\n        if(list[i]===undefined) i = 0;\n        if(list[0][1]-list[i][1]>=1&&result[result.length-1]!==list[0][0]) i = 0;\n    } //list has sorted, so list[0] appeared most frequent\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] rearrangeBarcodes(int[] barcodes) {\n        \n        if(barcodes.length <= 2){\n            return barcodes ; //Problem says solution always exist.\n        }\n        \n        Map<Integer, Integer> count = new HashMap<>();\n        Integer maxKey = null; // Character having max frequency\n        \n        for(int i: barcodes){\n            count.put(i, count.getOrDefault(i, 0) + 1);\n            if(maxKey == null || count.get(i) > count.get(maxKey)){\n                maxKey = i;\n            }\n        }\n        \n        int pos = 0;\n     \n        //Fill maxChar\n        int curr =  count.get(maxKey);\n        while(curr-- > 0){\n            barcodes[pos] = maxKey;\n            pos += 2;\n            if(pos >= barcodes.length){\n                pos = 1;\n            }\n        }\n        \n        count.remove(maxKey); // Since that character is done, we don't need to fill it again\n        \n        //Fill the remaining Characters.\n        for(int key: count.keySet()){\n            curr = count.get(key);\n            \n            while(curr-- > 0){\n                barcodes[pos] = key;\n                pos += 2;\n                if(pos >= barcodes.length){\n                    pos = 1;\n                }\n            }\n        }\n        \n        return barcodes;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    struct comp{\n        bool operator()(pair<int,int>&a, pair<int,int>&b){\n            return a.first < b.first;\n        }\n    };\n    \n    vector<int> rearrangeBarcodes(vector<int>& barcodes) {\n        unordered_map<int,int> hmap;\n        int n = barcodes.size();\n        if(n==1)return barcodes;\n        \n        for(auto &bar : barcodes){\n            hmap[bar]++;\n        }\n        \n        vector<int> ans;\n        priority_queue<pair<int,int>, vector<pair<int,int>>, comp> pq;\n        \n        for(auto &it : hmap){\n            pq.push({it.second, it.first});\n        }\n        \n        while(pq.size()>1){\n            \n            auto firstBar = pq.top();\n            pq.pop();\n            \n            auto secondBar = pq.top();\n            pq.pop();\n            \n            ans.push_back(firstBar.second);\n            ans.push_back(secondBar.second);\n            \n            --firstBar.first;\n            --secondBar.first;\n            \n            if(firstBar.first > 0){\n                pq.push(firstBar);\n            }\n            \n            if(secondBar.first > 0){\n                pq.push(secondBar);\n            }\n        }\n        \n        if(pq.size()){\n            ans.push_back(pq.top().second);\n            pq.pop();\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Shift 2D Grid",
        "algo_input": "Given a 2D grid of size m x n&nbsp;and an integer k. You need to shift the grid&nbsp;k times.\n\nIn one shift operation:\n\n\n\tElement at grid[i][j] moves to grid[i][j + 1].\n\tElement at grid[i][n - 1] moves to grid[i + 1][0].\n\tElement at grid[m&nbsp;- 1][n - 1] moves to grid[0][0].\n\n\nReturn the 2D grid after applying shift operation k times.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[9,1,2],[3,4,5],[6,7,8]]\n\n\nExample 2:\n\nInput: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n\n\nExample 3:\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput: [[1,2,3],[4,5,6],[7,8,9]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm ==&nbsp;grid.length\n\tn ==&nbsp;grid[i].length\n\t1 &lt;= m &lt;= 50\n\t1 &lt;= n &lt;= 50\n\t-1000 &lt;= grid[i][j] &lt;= 1000\n\t0 &lt;= k &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n        m, n = len(grid), len(grid[0])\n        cache = []\n        for i in range(m):\n            for j in range(n):\n                cache.append(grid[i][j])\n        \n        k %= len(cache)\n        new_vals = cache[-k:] + cache[:-k]\n        \n        cur = 0\n        for i in range(m):\n            for j in range(n):\n                grid[i][j] = new_vals[cur]\n                cur += 1\n        \n        return grid",
        "solution_js": "/**\n * @param {number[][]} grid\n * @param {number} k\n * @return {number[][]}\n */\nvar shiftGrid = function(grid, k) {\n\n    let m = grid.length\n    let n = grid[0].length\n\n    for (let r = 0; r < k; r++) {\n        const newGrid = Array(m).fill(\"X\").map(() => Array(n).fill(\"X\"))\n        for (let i = 0; i < m; i++) {\n            for (let j = 1; j < n; j++) {\n                newGrid[i][j] = grid[i][j-1]\n            }\n         }\n\n        for (let i = 1; i < m; i++) {\n            newGrid[i][0] = grid[i-1][n-1]\n        }\n\n        newGrid[0][0] = grid[m-1][n-1]\n\n        //copy the new grid for the next iteration\n        grid = newGrid\n    }\n\n    return grid\n\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> shiftGrid(int[][] grid, int k) {\n        // just bruteforce??? O(i*j*k)\n        // instead we calculate the final position at once!\n        \n        int m = grid.length;  // row\n        int n = grid[0].length;  // column\n        \n        int[][] arr = new int[m][n];\n        \n        // Since moving m*n times will result in same matrix, we do this:\n        k = k % (m*n);\n        \n        // Then we move each element\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                // for calculating column, it back to the original position\n                // every n steps\n                int column = (j + k) % n;\n                \n                // for calculating row, we move to the next row each time\n                // it exceed the last element on the current row.\n                // For example when 2 moves k=5 steps it turns to the (+2) row.\n                // Thus it's original row + ((original column + steps) / n)\n                // But if 2 moves k=8 steps it turns to the (0,0),\n                // and row + ((original column + steps) / n) gives 0+(9/3)=3 (out of bounds)\n                // so we'll need to % number of rows to get 0. (circle back)\n                int row = (i + ((j + k) / n)) % m;\n                arr[row][column] = grid[i][j];\n            }\n        }\n        return (List) Arrays.asList(arr);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {\n        \n        deque<int>dq;\n        \n        for(int i=0;i<grid.size();i++){\n            for(int j=0;j<grid[i].size();j++){\n                dq.push_back(grid[i][j]);\n            }\n        }\n        \n        int last = dq.size()-1;\n        while(k--){\n            int a = dq[last];\n            dq.push_front(a);\n            dq.pop_back();\n        }\n        \n        int p = 0;\n        \n        for(int i=0;i<grid.size();i++){\n            for(int j=0;j<grid[i].size();j++){\n                grid[i][j] = dq[p];\n                p++;\n            }\n        }\n        \n        return grid;\n    }\n};"
    },
    {
        "title": "Count Number of Homogenous Substrings",
        "algo_input": "Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.\n\nA string is homogenous if all the characters of the string are the same.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abbcccaa\"\nOutput: 13\nExplanation: The homogenous substrings are listed as below:\n\"a\"   appears 3 times.\n\"aa\"  appears 1 time.\n\"b\"   appears 2 times.\n\"bb\"  appears 1 time.\n\"c\"   appears 3 times.\n\"cc\"  appears 2 times.\n\"ccc\" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\n\nExample 2:\n\nInput: s = \"xy\"\nOutput: 2\nExplanation: The homogenous substrings are \"x\" and \"y\".\n\nExample 3:\n\nInput: s = \"zzzzz\"\nOutput: 15\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase letters.\n",
        "solution_py": "class Solution:\n    def countHomogenous(self, s: str) -> int:\n        res, count, n = 0, 1, len(s)\n        for i in range(1,n):\n            if s[i]==s[i-1]:\n                count+=1\n            else:\n                if count>1:\n                    res+=(count*(count-1)//2)\n                count=1    \n        if count>1:\n            res+=(count*(count-1)//2)\n        return (res+n)%(10**9+7)",
        "solution_js": "var countHomogenous = function(s) {\n    let mod = 1e9 + 7\n    let n = s.length\n    let j=0, res = 0\n    \n    for(let i=0; i<n; i++){\n        if(i>0 && s[i-1] != s[i]){\n            let x = i-j\n            res += x*(x+1) / 2\n            j = i\n        }\n    }\n    \n    let x = n-j\n    res += x*(x+1) / 2\n\n    return res%mod\n};",
        "solution_java": "class Solution {\n    public int countHomogenous(String s) {\n        int res = 1;\n        int carry = 1;\n        int mod = 1000000007;\n        for(int i =1;i<s.length();i++){\n            if(s.charAt(i) == s.charAt(i-1)) carry++;\n            else carry = 1;\n            res = (res + carry) % mod;\n        }\n\n        return res;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countHomogenous(string s) {\n        int mod=1e9+7,size=s.size(),i=0,j=0,count=0;\n        while(j<size){\n            if(s[j]!=s[j+1]){\n                long n=j-i+1;\n                count = count + (n*(n+1)/2)%mod;\n                i=j+1;\n            }\n            j++;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Construct the Rectangle",
        "algo_input": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:\n\n\n\tThe area of the rectangular web page you designed must equal to the given target area.\n\tThe width W should not be larger than the length L, which means L &gt;= W.\n\tThe difference between length L and width W should be as small as possible.\n\n\nReturn an array [L, W] where L and W are the length and width of the&nbsp;web page you designed in sequence.\n\n&nbsp;\nExample 1:\n\nInput: area = 4\nOutput: [2,2]\nExplanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.\n\n\nExample 2:\n\nInput: area = 37\nOutput: [37,1]\n\n\nExample 3:\n\nInput: area = 122122\nOutput: [427,286]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= area &lt;= 107\n\n",
        "solution_py": "class Solution:\n    def constructRectangle(self, area: int):\n        y = Solution.mySqrt(area)\n        for i in range(y, 0, -1):\n            if not area%i:\n                return [int(area/i), i]\n\n    def mySqrt(x):\n        if x == 0:\n            return 0\n        n = x\n        count = 0\n        while True:\n            count += 1\n            root = 0.5 * (n + (x / n))\n            if abs(root - n) < 0.9:\n                break\n            n = root\n        return int(root)",
        "solution_js": "/**\n * @param {number} area\n * @return {number[]}\n */\nvar constructRectangle = function(area) {\n    let w = Math.floor(Math.sqrt(area))\n    while(area % w != 0)    w--\n    return [area/w, w]\n};",
        "solution_java": "class Solution {\n    public int[] constructRectangle(int area) {\n        int minDiff = Integer.MAX_VALUE;\n        int[] result = new int[2];\n        \n        for (int w = 1; w*w <= area; w++) {\n            if (area % w == 0) {\n                int l = area / w;\n                int diff = l - w;\n                if (diff < minDiff) {\n                    result[0] = l;\n                    result[1] = w;\n                    minDiff = diff;\n                }\n            }\n        }\n        \n        return result;\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    vector<int> constructRectangle(int area)\n    {\n        int sq = sqrt(area);\n        while (sq > 1)\n        {\n            if (area % sq == 0)\n                break;\n            sq--;\n        }\n        return {area / sq, sq};\n    }\n};"
    },
    {
        "title": "Complex Number Multiplication",
        "algo_input": "A complex number can be represented as a string on the form \"real+imaginaryi\" where:\n\n\n\treal is the real part and is an integer in the range [-100, 100].\n\timaginary is the imaginary part and is an integer in the range [-100, 100].\n\ti2 == -1.\n\n\nGiven two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.\n\n&nbsp;\nExample 1:\n\nInput: num1 = \"1+1i\", num2 = \"1+1i\"\nOutput: \"0+2i\"\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n\n\nExample 2:\n\nInput: num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput: \"0+-2i\"\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n\n\n&nbsp;\nConstraints:\n\n\n\tnum1 and num2 are valid complex numbers.\n\n",
        "solution_py": "class Solution:\n    def complexNumberMultiply(self, num1: str, num2: str) -> str:\n        i1=num1.index('+')\n        i2=num2.index('+')\n        a=int(num1[0:i1])\n        x=int(num2[0:i2])\n        b=int(num1[i1+1:len(num1)-1])\n        y=int(num2[i2+1:len(num2)-1])\n        ans1=a*x+(-1)*b*y\n        ans2=a*y+b*x\n        return str(ans1)+'+'+(str(ans2)+'i')",
        "solution_js": "var complexNumberMultiply = function(num1, num2) {\n\tlet [realA, imaginaryA] = num1.split('+');\n\tlet [realB, imaginaryB] = num2.split('+');\n\timaginaryA = parseInt(imaginaryA);\n\timaginaryB = parseInt(imaginaryB);\n\tconst real = realA * realB - imaginaryA * imaginaryB;\n\tconst imaginary = realA * imaginaryB + imaginaryA * realB;\n\n\treturn `${real}+${imaginary}i`;\n};",
        "solution_java": "class Solution {\n    public String complexNumberMultiply(String num1, String num2) {\n        int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+')));\n        int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1));\n        int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+')));\n        int val4 = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1));\n        \n        return \"\" + (val1*val3 - val2*val4) + \"+\" + (val1*val4 + val3*val2) + \"i\";\n    }\n}",
        "solution_c": "class Solution {\npublic: \n    pair<int,int> seprateRealAndImg(string &s){\n        int i = 0;\n        string real,img;\n        while(s[i] != '+') real += s[i++];\n        while(s[++i] != 'i') img += s[i];\n        \n        return {stoi(real),stoi(img)};\n    }\n    string complexNumberMultiply(string num1, string num2) {\n        pair<int,int> x = seprateRealAndImg(num1);\n        pair<int,int> y = seprateRealAndImg(num2);\n        \n        int a1 = x.first,b1 = x.second;\n        int a2 = y.first,b2 = y.second;\n        \n        int real = (a1 * a2) - (b1*b2);\n        int img = (b1*a2) + (a1 * b2);\n        \n        return to_string(real) + \"+\" + to_string(img) + \"i\";\n    }\n};"
    },
    {
        "title": "Palindrome Partitioning III",
        "algo_input": "You are given a string s containing lowercase letters and an integer k. You need to :\n\n\n\tFirst, change some characters of s to other lowercase English letters.\n\tThen divide s into k non-empty disjoint substrings such that each substring is a palindrome.\n\n\nReturn the minimal number of characters that you need to change to divide the string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abc\", k = 2\nOutput: 1\nExplanation:&nbsp;You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n\n\nExample 2:\n\nInput: s = \"aabbc\", k = 3\nOutput: 0\nExplanation:&nbsp;You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n\nExample 3:\n\nInput: s = \"leetcode\", k = 8\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= s.length &lt;= 100.\n\ts only contains lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def palindromePartition(self, s: str, t: int) -> int:\n        n=len(s)\n        @lru_cache(None)\n        def is_palin(s):                #This function returns min no of chars to change to make s as a palindrome\n            cnt=0\n            for c1,c2 in zip(s,s[::-1]):\n                if c1!=c2: cnt+=1\n            if len(s)%2==0:\n                return cnt//2\n            return (cnt+1)//2\n        @lru_cache(None)\n        def dp(i,j,k):            #We analyse string s[i:j+1] with k divisions left\n            if j==n:\n                return 0 if k==0 else sys.maxsize\n            if k==0: \n                return sys.maxsize\n            ans=sys.maxsize\n            cnt=is_palin(s[i:j+1])\n            #terminate here\n            ans=min(ans,dp(j+1,j+1,k-1)+cnt)\n            #dont terminate\n            ans=min(ans,dp(i,j+1,k))\n            return ans\n        return dp(0,0,t)\n                        \n                \n            ",
        "solution_js": "var palindromePartition = function(s, k) {\n    const len = s.length;\n\n    const cost = (i = 0, j = 0) => {\n        let c = 0;\n        while(i <= j) {\n            if(s[i] != s[j]) c++;\n            i++, j--;\n        }\n        return c;\n    }\n\n    const dp = Array.from({ length: len }, () => {\n        return new Array(k + 1).fill(-1);\n    })\n\n    const splitHelper = (idx = 0, sl = k) => {\n        if(sl < 0) return Infinity;\n        if(idx == len) {\n            if(sl == 0) return 0;\n            return Infinity;\n        }\n\n        if(dp[idx][sl] != -1) return dp[idx][sl];\n\n        let ans = Infinity;\n\n        for(let i = idx; i < len; i++) {\n            ans = Math.min(ans, splitHelper(i + 1, sl - 1) + cost(idx, i));\n        }\n        return dp[idx][sl] = ans;\n    }\n\n    return splitHelper();\n};",
        "solution_java": "class Solution {\n    public int mismatchCount(String s) {\n        int n = s.length()-1;\n        int count = 0;\n        for(int i=0,j=n;i<j;i++,j--) {\n            if(s.charAt(i) != s.charAt(j))\n                count++;\n        }\n        return count;\n    }\n    public int helper(String s, int n, int i, int j, int k, Integer[][][] dp) {\n        if(j>=n)\n            return 105;\n        if(k<0)\n            return 105;\n        if(dp[i][j][k] != null) {\n            return dp[i][j][k];\n        }\n        if(n-j<k)\n            return dp[i][j][k] = 105;\n        if(n-j==k)\n            return dp[i][j][k] = mismatchCount(s.substring(i,j+1));\n        int stop = mismatchCount(s.substring(i,j+1)) + helper(s,n,j+1,j+1,k-1,dp);\n        int cont = helper(s,n,i,j+1,k,dp);\n        return dp[i][j][k] = Math.min(stop, cont);\n    }\n    public int palindromePartition(String s, int k) {\n        int n = s.length();\n        Integer[][][] dp = new Integer[n][n][k+1];\n        return helper(s,s.length(),0,0,k,dp);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n\tint dp[105][105];\n\t/// Count Number of changes to be done\n\t/// to make substring of s from i to j \n\t/// to palindrome\n\tint changes(int i , int j , string& s){\n\t\tint cnt = 0;\n\t\twhile(i < j){\n\t\t\tcnt += (s[i++] != s[j--]);\n\t\t}\n\t\treturn cnt;\n\t}\n\n\tint recur(int idx, int k, string &s){\n\n\t\t/// If Reached end of s and found partions to be done 0\n\t\t/// return 0 , otherwise return INT_MAX/any big number\n\t\tif(idx == s.size()){\n\t\t\treturn (k == 0) ? 0 : 1e7;\n\t\t}\n\n\t\t/// Partitions to be done have completed , but\n\t\t/// we are not at the end of the string \n\t\t/// return INT_MAX/any big number\n\t\tif(k == 0){\n\t\t\treturn 1e7;\n\t\t}\n\n\t\tif (dp[idx][k] != -1){\n\t\t\treturn dp[idx][k];\n\t\t}\n\n\t\t/// Partitioning the String\n\t\tint ans = INT_MAX;\n\t\tfor (int i = idx ; i < s.size() ; i++){\n\t\t\tans = min(ans , changes(idx , i , s) + recur(i + 1, k - 1, s));\n\t\t}\n\t\treturn dp[idx][k] = ans;\n\t}\n\n\tint palindromePartition(string s, int k) {\n\n\t\t/// Edge Case\n\t\tif(k == s.size()){\n\t\t\treturn 0;\n\t\t}\n\t\tmemset(dp , -1 , sizeof(dp));\n\t\treturn recur(0 , k , s);\n\t}\n\n};"
    },
    {
        "title": "N-ary Tree Postorder Traversal",
        "algo_input": "Given the root of an n-ary tree, return the postorder traversal of its nodes' values.\n\nNary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [5,6,3,2,4,1]\n\n\nExample 2:\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: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t0 &lt;= Node.val &lt;= 104\n\tThe height of the n-ary tree is less than or equal to 1000.\n\n\n&nbsp;\nFollow up: Recursive solution is trivial, could you do it iteratively?\n",
        "solution_py": "\"\"\"\n# Definition for a Node.\nclass Node:\n    def __init__(self, val=None, children=None):\n        self.val = val\n        self.children = children\n\"\"\"\n\nclass Solution:\n    def postorder(self, root: 'Node') -> List[int]:\n        ans=[]\n        def post(root):\n            nonlocal ans\n            if not root:\n                return\n            for i in root.children:\n                post(i)\n            ans.append(root.val)\n        post(root)\n        return ans",
        "solution_js": "var postorder = function(root) {\n    const res = [];\n    function post(node) {\n        if (!node) return;\n        for (let child of node.children) {\n            post(child);\n        }\n        res.push(node.val);\n    }\n    post(root);\n    return res;\n};",
        "solution_java": "class Solution {\n    List<Integer> result = new ArrayList<>();\n    public List<Integer> postorder(Node root) {\n        addNodes(root);\n        return result;\n    }\n    \n    void addNodes(Node root) {\n        if (root == null) return;\n        for (Node child : root.children) addNodes(child);\n        result.add(root.val);\n    }\n}",
        "solution_c": " class Solution {\npublic:\n    void solve(Node*root,vector<int>&ans){\n        if(root==NULL)return;\n        for(int i=0;i<root->children.size();i++){\n            solve(root->children[i],ans);\n        }\n        ans.push_back(root->val);\n    }\n    vector<int> postorder(Node* root) {\n        vector<int>ans;\n        solve(root,ans);\n        return ans;\n    }\n\t\t"
    },
    {
        "title": "Find the Kth Smallest Sum of a Matrix With Sorted Rows",
        "algo_input": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.\n\nYou are allowed to choose exactly one element from each row to form an array.\n\nReturn the kth smallest array sum among all possible arrays.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,3,11],[2,4,6]], k = 5\nOutput: 7\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\n\n\nExample 2:\n\nInput: mat = [[1,3,11],[2,4,6]], k = 9\nOutput: 17\n\n\nExample 3:\n\nInput: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput: 9\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  \n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat.length[i]\n\t1 &lt;= m, n &lt;= 40\n\t1 &lt;= mat[i][j] &lt;= 5000\n\t1 &lt;= k &lt;= min(200, nm)\n\tmat[i] is a non-decreasing array.\n\n",
        "solution_py": "class Solution:\n    def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n        def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n            h = [(nums1[0]+nums2[0],0,0)]\n            visited = set()\n            res = []\n            while h and k > 0:\n                e, i, j = heappop(h)\n                if (i,j) in visited: continue\n                res.append(e)\n                visited.add((i,j))\n                if j+1 < len(nums2):\n                    heappush(h,(nums1[i]+nums2[j+1],i,j+1))\n                if i+1 < len(nums1):\n                    heappush(h,(nums1[i+1]+nums2[j],i+1,j))\n                k -= 1\n            return res\n        res = mat[0]\n        for i in range(1, len(mat)):\n            res = kSmallestPairs(res, mat[i], k)\n        return res[-1]",
        "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number}\n */\nvar kthSmallest = function(mat, k) {\n    var m = mat.length;\n    var n = m ? mat[0].length : 0;\n    if (!m || !n) return -1;\n    var sums = [0];\n    for (var idx = 0; idx < m; idx++) {\n        var newSums = []\n        for (var sum of sums) {\n            for (var i = 0; i < n && i < k; i++) {\n                var newSum = sum + mat[idx][i];\n                if (newSums.length < k) {\n                    newSums.push(newSum);\n                } else if (newSum < newSums[k-1]) {\n                    newSums.pop();\n                    newSums.push(newSum);\n                } else {\n                    break;\n                }\n                newSums.sort((a, b) => a - b);\n            }\n        }\n        sums = newSums;\n    }\n    return sums[k-1];\n};",
        "solution_java": "class Solution {\n    public int kthSmallest(int[][] mat, int k) {\n        int[] row = mat[0];\n        \n        for(int i=1; i<mat.length; i++) {\n            row = findKthSmallest(row, mat[i], k);\n        }\n        \n        return row[k-1];\n    }\n    \n    private int[] findKthSmallest(int[] num1, int[] num2, int k) {\n        List<Integer> list = new ArrayList<>();\n        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a,b) -> (a[0]+a[1]) - (b[0]+b[1]));\n        \n        for(int i=0; i<num1.length && i<k; i++) {\n            minHeap.offer(new int[]{num1[i], num2[0], 0});\n        }\n        \n        for(int i=0; i<k && !minHeap.isEmpty(); i++) {\n            int[] candidate = minHeap.poll();\n            list.add(candidate[0] + candidate[1]); // SUM;\n            int num2Idx = candidate[2];\n            \n            if(num2Idx<num2.length-1) {\n                minHeap.offer(new int[]{candidate[0], num2[num2Idx+1], num2Idx+1});\n            }\n        }\n        \n        return list.stream().mapToInt(i->i).toArray();\n    }\n}",
        "solution_c": "class Solution {\npublic:\nvector<int> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {\n        auto cmp = [&nums1,&nums2](pair<int,int> a, pair<int,int>b){\n            return nums1[a.first]+nums2[a.second] >\n                nums1[b.first]+nums2[b.second];\n        };\n        int n = nums1.size();\n        int m = nums2.size();\n        vector<int> ans;\n        if(n==0 || m==0)\n            return ans;\n        priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)>pq(cmp);\n        pq.push({0,0});\n        while(k-- && !pq.empty())\n        {\n            int i = pq.top().first;\n            int j = pq.top().second;\n            pq.pop();\n            \n            if(j+1<m)\n                pq.push({i,j+1});\n            if(j==0 && i+1 <n)\n                pq.push({i+1,j});\n            \n            ans.push_back(nums1[i]+nums2[j]);\n        }\n        return ans;\n    }\n    int kthSmallest(vector<vector<int>>& mat, int k) {\n        vector<int> nums1 = mat[0];\n        int n =  mat.size();\n        for(int i = 1; i<n; ++i)\n        {\n            nums1 = kSmallestPairs(nums1,mat[i],k);\n        }\n        return nums1[k-1];\n    }\n};"
    },
    {
        "title": "Fruit Into Baskets",
        "algo_input": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.\n\nYou want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:\n\n\n\tYou only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.\n\tStarting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.\n\tOnce you reach a tree with fruit that cannot fit in your baskets, you must stop.\n\n\nGiven the integer array fruits, return the maximum number of fruits you can pick.\n\n&nbsp;\nExample 1:\n\nInput: fruits = [1,2,1]\nOutput: 3\nExplanation: We can pick from all 3 trees.\n\n\nExample 2:\n\nInput: fruits = [0,1,2,2]\nOutput: 3\nExplanation: We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].\n\n\nExample 3:\n\nInput: fruits = [1,2,3,2,2]\nOutput: 4\nExplanation: We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= fruits.length &lt;= 105\n\t0 &lt;= fruits[i] &lt; fruits.length\n\n",
        "solution_py": "class Solution:\n    def totalFruit(self, fruits: List[int]) -> int:\n        ans=0\n        fruitdict=defaultdict()\n        stack=[]\n        i,j=0,0\n\n        while j<len(fruits):\n            if fruits[j] not in fruitdict and len(fruitdict)<2:\n                stack.append(fruits[j])\n                fruitdict[fruits[j]]=j\n                j+=1\n\n            elif  fruits[j] in fruitdict:\n                fruitdict[fruits[j]]=j\n                j+=1\n\n            else:  \n                if fruitdict[stack[0]]>fruitdict[stack[1]]  :\n                    i = fruitdict[stack[1]]+1\n                    del fruitdict[stack[1]]\n                    stack.pop()\n                else:\n                    i = fruitdict[stack[0]]+1\n                    del fruitdict[stack[0]] \n                    stack.pop(0)              \n            \n            ans=max(ans,j-i)\n        return ans",
        "solution_js": "var totalFruit = function(fruits) {\n    let myFruits = {};\n    let n = fruits.length;\n    let windowStart = 0;\n    let ans = -Number.MAX_VALUE;\n    \n    for(let windowEnd = 0; windowEnd < n; windowEnd++) {\n        let fruit = fruits[windowEnd];\n        \n        if(fruit in myFruits) {\n            myFruits[fruit]++;\n        }\n        else {\n            myFruits[fruit] = 1;\n        }\n        \n        while(Object.keys(myFruits).length > 2) {\n            let throwOut = fruits[windowStart];\n            myFruits[throwOut]--;\n            if(myFruits[throwOut] == 0) {\n                delete myFruits[throwOut];\n            }\n            windowStart++;\n        }\n        ans = Math.max(ans, windowEnd - windowStart + 1);\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int totalFruit(int[] fruits) {\n        if (fruits == null || fruits.length == 0) {\n            return 0;\n        }\n        int start = 0, end = 0, res = 0;\n        HashMap<Integer, Integer> map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit\n\n        while (end < fruits.length) {\n            if (map.size() <= 2) {\n                map.put(fruits[end], end);\n                end++;\n            }\n\n            if (map.size() > 2) {\n                int leftMost = fruits.length;\n                for (int num : map.values()) {\n                    leftMost = Math.min(leftMost, num);\n                }\n                map.remove(fruits[leftMost]);\n                start = leftMost + 1;\n            }\n\n            res = Math.max(res, end - start);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int totalFruit(vector<int>& fruits) {\n        int i=0, j=0, ans = 1;\n        unordered_map<int, int>mp;\n        while(j<fruits.size()){\n            mp[fruits[j]]++;\n            \n            if(mp.size()<2){\n                ans = max(ans, j-i+1);\n                j++;\n            }\n            else if(mp.size()==2){\n                ans = max(ans, j-i+1);\n                j++;\n            }\n            else if(mp.size()>2){\n                while(mp.size()>2){\n                    mp[fruits[i]]--;\n                    if(mp[fruits[i]]==0)\n                        mp.erase(fruits[i]);\n                    i++;\n                }\n                if(mp.size()==2){\n                    ans = max(ans, j-i+1);\n                }\n                j++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Convert 1D Array Into 2D Array",
        "algo_input": "You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with  m rows and n columns using all the elements from original.\n\nThe elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.\n\nReturn an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.\n\n&nbsp;\nExample 1:\n\nInput: original = [1,2,3,4], m = 2, n = 2\nOutput: [[1,2],[3,4]]\nExplanation: The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\n\n\nExample 2:\n\nInput: original = [1,2,3], m = 1, n = 3\nOutput: [[1,2,3]]\nExplanation: The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.\n\n\nExample 3:\n\nInput: original = [1,2], m = 1, n = 1\nOutput: []\nExplanation: There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= original.length &lt;= 5 * 104\n\t1 &lt;= original[i] &lt;= 105\n\t1 &lt;= m, n &lt;= 4 * 104\n\n",
        "solution_py": "class Solution:\n    def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n        return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []\n        ",
        "solution_js": "var construct2DArray = function(original, m, n) {\n    if (original.length !== (m*n)) return []\n    let result = []\n    let arr = []\n    for (let i = 0; i < original.length; i++){\n        arr.push(original[i])\n        if (arr.length === n){\n            result.push(arr)\n            arr = []\n        }\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public int[][] construct2DArray(int[] original, int m, int n) {        \n        if (original.length != m * n) return new int[0][];\n        \n        int[][] ans = new int[m][n];\n        int currRow = 0, currCol = 0;\n        \n        for (int num : original) {\n            ans[currRow][currCol++] = num;\n            \n            if (currCol == n) {\n                currCol = 0;\n                currRow++;\n            }\n        }\n        \n        return ans;\n    }\n}\n\n// TC: O(n), SC: O(m * n)",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {\n        if (m * n != original.size()) return {};\n\n        vector<vector<int>> res;\n        for (int i = 0; i < m*n; i+=n)\n            res.push_back(vector<int>(original.begin()+i, original.begin()+i+n));\n\n        return res;\n    }\n};"
    },
    {
        "title": "Integer Replacement",
        "algo_input": "Given a positive integer n,&nbsp;you can apply one of the following&nbsp;operations:\n\n\n\tIf n is even, replace n with n / 2.\n\tIf n is odd, replace n with either n + 1 or n - 1.\n\n\nReturn the minimum number of operations needed for n to become 1.\n\n&nbsp;\nExample 1:\n\nInput: n = 8\nOutput: 3\nExplanation: 8 -&gt; 4 -&gt; 2 -&gt; 1\n\n\nExample 2:\n\nInput: n = 7\nOutput: 4\nExplanation: 7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1\nor 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1\n\n\nExample 3:\n\nInput: n = 4\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def integerReplacement(self, n: int) -> int:\n        dp = {}\n        def dfs(num):\n            if num == 1:\n                return 0\n\n            if num in dp:\n                return dp[num]\n\n            # if num is even, we have only one option -> n / 2\n            even = odd = 0\n            if num % 2 == 0:\n                even = 1 + dfs(num // 2)\n            else:\n                # if num is odd, we have two option, either we increment the num or decrement the num\n                odd1 = 1 + dfs(num - 1)\n                odd2 = 1 + dfs(num + 1)\n                # take the min of both operation\n                odd = min(odd1, odd2)\n\n            dp[num] = even + odd\n            return dp[num]\n\n        return dfs(n)",
        "solution_js": "var integerReplacement = function(n) {\n    let count=0;\n    while(n>1){\n       if(n%2===0){n/=2;}\n       else{\n         if(n!==3 && (n+1)%4===0){n++;}\n         else{n--;}\n       } \n      count++;  \n    }\n    return count;  \n};        ",
        "solution_java": "class Solution {\n    public int integerReplacement(int n) {\n        return (int)calc(n,0);\n    }\n    public long calc(long n,int i){\n        if(n==1) \n            return i;\n        if(n<1) \n            return 0;\n        \n        long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE;\n        \n        if(n%2==0) \n            a=calc(n/2,i+1);\n        else{\n            b=calc(n-1,i+1);\n            c=calc(n+1,i+1);\n        }\n        long d=Math.min(a,Math.min(b,c));\n        return d;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int integerReplacement(int n) {\n\n        return helper(n);\n    }\n\n    int helper(long n)\n    {\n        if(n == 1)\n            return 0;\n\n        if(n % 2)\n            return 1 + min(helper(n - 1), helper(n + 1));\n\n        return 1 + helper(n / 2);\n    }\n};"
    },
    {
        "title": "Root Equals Sum of Children",
        "algo_input": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.\n\nReturn true if the value of the root is equal to the sum of the values of its two children, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: root = [10,4,6]\nOutput: true\nExplanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.\n\n\nExample 2:\n\nInput: root = [5,3,1]\nOutput: false\nExplanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe tree consists only of the root, its left child, and its right child.\n\t-100 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def checkTree(self, root: Optional[TreeNode]) -> bool:\n        return root.val == (root.left.val + root.right.val)",
        "solution_js": "var checkTree = function(root) {\n    return root.val === root.left.val + root.right.val;\n};",
        "solution_java": "class Solution\n{\n    public boolean checkTree(TreeNode root)\n    {\n        return root.val == root.left.val + root.right.val; // O(1)\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkTree(TreeNode* root) {\n        if(root->left->val+root->right->val==root->val){\n            return true;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Concatenated Words",
        "algo_input": "Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.\n\nA concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\nOutput: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\nExplanation: \"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".\n\nExample 2:\n\nInput: words = [\"cat\",\"dog\",\"catdog\"]\nOutput: [\"catdog\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 104\n\t1 &lt;= words[i].length &lt;= 30\n\twords[i] consists of only lowercase English letters.\n\tAll the strings of words are unique.\n\t1 &lt;= sum(words[i].length) &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n                \n        set_words = set(words)\n\n        def check(word, seen):\n            if word == '':\n                return True\n            for i in range(len(word) if seen else len(word) - 1):\n                if word[:i+1] in set_words:\n                    if check(word[i+1:], seen | {word[:i+1]}):\n                        return True\n            return False\n\n        return [word for word in words if check(word, set())]",
        "solution_js": "class Node {\n    val;\n    children;\n    isWord = false;\n    constructor(val) {\n        this.val = val;\n    }\n\n}\nclass Trie {\n    nodes = Array(26);\n    addWord(w) {\n        let idx = this.getIdx(w[0]);\n        let node = this.nodes[idx] || new Node(w[0]);\n        this.nodes[idx] = node;\n        for (let i=1; i < w.length; ++i) {\n            node.children = node.children || Array(26);\n            idx = this.getIdx(w[i]);\n            let childNode = node.children[idx] || new Node(w[i]);\n            node.children[idx] = childNode;\n            node = childNode;\n        }\n\n        node.isWord = true;\n    }\n\n    getExistingWords(w, start) {\n        const rslt = [];\n        let node = {children: this.nodes};\n        for (let i=start; i < w.length; ++i) {\n            node = (node.children || [])[this.getIdx(w[i])];\n            if (!node) {\n                break;\n            }\n\n            if (node.isWord) {\n                rslt.push(i-start+1);\n            }\n        }\n\n        return rslt;\n    }\n\n    getIdx(ch) {\n        return ch.charCodeAt(0) - \"a\".charCodeAt(0);\n    }\n}\n\nvar findAllConcatenatedWordsInADict = function(words) {\n    const rslt = [];\n    words = words.sort((a,b) => a.length-b.length);\n    let start = 0;\n    if (words[0].length === 0) {\n        ++start;\n    }\n    const tr = new Trie();\n    for (let i = start; i < words.length; ++i) {\n        if (check(words[i], 0, tr, Array(words[i].length))) {\n            rslt.push(words[i]);\n        }\n        tr.addWord(words[i]);\n    }\n\n    return rslt;\n};\n\nfunction check(word, i, trie, dp) {\n    if (i > word.length || dp[i] === false) {\n        return false;\n    }\n    if (i === word.length || dp[i] === true) {\n        return true;\n    }\n    const lens = trie.getExistingWords(word, i);\n    if (!lens.length) {\n        dp[i] = false;\n        return false;\n    }\n\n    dp[i] = true;\n    for (let l of lens) {\n        if (check(word, i+l, trie, dp)) {\n            return true;\n        }\n    }\n\n    dp[i] = false;\n\n    return false;\n}",
        "solution_java": "class Solution {\n\tSet<String> set = new HashSet<>();\n\tSet<String> res = new HashSet<>();\n\tint index = 0;\n    public List<String> findAllConcatenatedWordsInADict(String[] words) {\n        for (String word: words) set.add(word);\n\t\tfor (String word: words) {\n\t        int len = word.length();\n\t        index = 0;\n\t        backtrack(len, word, 0);\n        }\n        List<String> list = new ArrayList<>();\n        for (String word: res) list.add(word);\n        return list;\n    }\n\tpublic void backtrack (int len, String word, int num) {\n\t    if (index == len && num >= 2) {\n            res.add(word);\n        }\n\t    int indexCopy = index;\n\t    for (int i = index + 1; i <= len; i++) {\n\t\t    if (set.contains(word.substring(index, i))) {\n\t            index = i;\n\t            backtrack(len, word, num + 1);\n\t            index = indexCopy;\n            } \n        }\n        return;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int checkForConcatenation( unordered_set<string>& st, string w, int i, vector<int>& dp){\n        if(i == w.size()) return 1;\n        if(dp[i] != -1) return dp[i];\n        for(int j = i; j < w.size(); ++j ){\n            string t = w.substr(i, j-i+1);\n            if(t.size() != w.size() && st.find(t) != st.end()){\n                if(checkForConcatenation(st, w, j+1, dp)) return dp[i] = 1;\n            }\n        }\n        return dp[i] = 0;\n    }\n    \n    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {\n        vector<string> ans;\n        unordered_set<string> st;\n        for(auto w: words) st.insert(w);\n        for(auto w: words){\n            vector<int> dp(w.size(), -1);\n            if(checkForConcatenation(st, w, 0, dp)) ans.push_back(w);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "K-Similar Strings",
        "algo_input": "Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.\n\nGiven two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.\n\n&nbsp;\nExample 1:\n\nInput: s1 = \"ab\", s2 = \"ba\"\nOutput: 1\n\n\nExample 2:\n\nInput: s1 = \"abc\", s2 = \"bca\"\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s1.length &lt;= 20\n\ts2.length == s1.length\n\ts1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.\n\ts2 is an anagram of s1.\n\n",
        "solution_py": "class Solution:\n    def kSimilarity(self, s1: str, s2: str) -> int:\n        n = len(s1)\n        \n        def helper(i, curr, dp):\n            if curr == s2:\n                return 0\n            \n            if curr not in dp[i]:\n                if curr[i] == s2[i]:\n                    dp[i][curr] = helper(i+1, curr, dp)\n                else:\n                    temp = sys.maxsize\n                    for j in range(i+1, n):\n                        if curr[j] == s2[i]:\n                            temp = min(temp, 1+helper(i+1, curr[:i]+curr[j]+curr[i+1:j]+curr[i]+curr[j+1:], dp))\n\n                    dp[i][curr] = temp\n            return dp[i][curr]\n        \n        dp = [{} for _ in range(n)]\n        return helper(0, s1, dp)",
        "solution_js": "var kSimilarity = function(s1, s2) {\n    // abc --> bca\n    // swap from 0: a !== b, find next b, swap(0,1) --> bac\n    // swap from 1: a !== c, find next c, swap(1,2) --> bca\n    return bfs(s1, s2);    \n};\n\nconst bfs = (a,b)=>{\n    if(a===b)\n        return 0;\n    const visited = new Set();\n    const queue = [];\n    queue.push([a,0,0]); // str, idx, swapCount\n    while(queue.length>0)\n    {\n        let [s, idx, cnt] = queue.shift();\n        while(s[idx]===b[idx])\n        {\n                idx++;\n        }\n        for(let j = idx+1; j<s.length; j++)\n        {\n            if(s[j]===b[idx]) {\n                s = swap(s, idx, j);\n                \n                if(s===b) {\n                    return cnt+1;\n                }\n            \n                if(!visited.has(s))\n                {\n                    queue.push([s.slice(), idx, cnt+1]);\n                    visited.add(s.slice());\n                }\n                \n                // swap back for later index\n                s = swap(s, idx, j);\n            }\n        }\n    }\n    return -1;\n}\n\nconst swap = (s, i, j)=>{\n  let arr = s.split('');\n  let tmp = arr[i];\n  arr[i] = arr[j];\n  arr[j] = tmp;\n  return arr.join('');\n}",
        "solution_java": "class Solution {\n    public int kSimilarity(String s1, String s2) {\n        HashSet<String> vis = new HashSet<>();\n        \n        ArrayDeque<String> queue = new ArrayDeque<>();\n        int level = 0;\n        queue.add(s1);\n        \n        while(queue.size() > 0){\n            int size = queue.size();\n            for(int i=0;i<size;i++){\n                \n                String rem = queue.remove();        // remove\n                \n                if(vis.contains(rem)){              // Mark*\n                    continue;\n                }\n                vis.add(rem);\n                \n                if(rem.equals(s2)){                 // Work\n                    return level;\n                }\n                \n                // Add\n                for(String s : getNeighbors(rem,s2)){\n                    if(!vis.contains(s)){\n                        queue.add(s);\n                    }\n                }\n            }\n            level++;\n        }\n        return -1;\n    }\n    \n    public ArrayList<String> getNeighbors(String rem,String s2){\n        ArrayList<String> res = new ArrayList<>();\n        \n        int idx = -1;\n        for(int i=0;i<rem.length();i++){\n            if(rem.charAt(i) != s2.charAt(i)){\n                idx = i;\n                break;\n            }\n        }\n        \n        for(int j=idx+1;j<rem.length();j++){\n            if(rem.charAt(j) == s2.charAt(idx)){\n                String s = swap(rem,idx,j);\n                res.add(s);\n            }\n        }\n        \n        return res;\n    }\n    \n    public String swap(String str,int i,int j){\n        StringBuilder sb = new StringBuilder(str);\n        char chi = sb.charAt(i);\n        char chj = sb.charAt(j);\n        \n        sb.setCharAt(i,chj);\n        sb.setCharAt(j,chi);\n        \n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    unordered_map<string,int>m;\n    int solve(string &s1,string &s2,int i)\n    {\n        if(i==s1.length())\n            return 0;\n        if(m.find(s1)!=m.end())return m[s1];\n        if(s1[i]==s2[i])\n            return m[s1]=solve(s1,s2,i+1);\n        int ans=1e5;\n        for(int j=i+1;j<s1.length();j++)\n        {\n            if(s1[j]==s2[i])\n            {\n                swap(s1[j],s1[i]);\n                ans=min(ans,1+solve(s1,s2,i+1));\n                swap(s1[j],s1[i]);\n            }\n        }\n        return m[s1]=ans;\n    }\n    int kSimilarity(string s1, string s2) {\n        return solve(s1,s2,0);\n    }\n};"
    },
    {
        "title": "Time Based Key-Value Store",
        "algo_input": "Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.\n\nImplement the TimeMap class:\n\n\n\tTimeMap() Initializes the object of the data structure.\n\tvoid set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.\n\tString get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev &lt;= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns \"\".\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]\nOutput\n[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]\n\nExplanation\nTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1);  // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1);         // return \"bar\"\ntimeMap.get(\"foo\", 3);         // return \"bar\", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is \"bar\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4);         // return \"bar2\"\ntimeMap.get(\"foo\", 5);         // return \"bar2\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= key.length, value.length &lt;= 100\n\tkey and value consist of lowercase English letters and digits.\n\t1 &lt;= timestamp &lt;= 107\n\tAll the timestamps timestamp of set are strictly increasing.\n\tAt most 2 * 105 calls will be made to set and get.\n\n",
        "solution_py": "class TimeMap:\n\n    def __init__(self):\n        self.dict = {}\n        \n\n    def set(self, key: str, value: str, timestamp: int) -> None:\n        if key not in self.dict:\n            self.dict[key] = ([], [])\n            self.dict[key][0].append(value)\n            self.dict[key][1].append(timestamp)\n        else:\n            self.dict[key][0].append(value)\n            self.dict[key][1].append(timestamp)\n    \n    \n    def bsearch(self, nums, target):\n        beg = 0\n        end = len(nums)-1\n        lastIndex = len(nums)-1\n        \n        while beg<=end:\n            mid = (beg+end)//2\n            if target == nums[mid]:\n                return mid\n            elif target < nums[mid]:\n                end = mid-1\n            elif target > nums[mid]:\n                beg = mid+1\n        \n        \n        if target < nums[mid] and mid == 0:\n            return -1\n        if target > nums[mid]:\n            return mid\n        return mid-1\n            \n    def get(self, key: str, timestamp: int) -> str:\n        if key not in self.dict:\n            return \"\"\n        \n        index = self.bsearch(self.dict[key][1], timestamp)\n        return self.dict[key][0][index] if 0 <= index < len(self.dict[key][0]) else \"\"\n    \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)",
        "solution_js": "var TimeMap = function() {\n    this.data = new Map();\n};\n\n/** \n * @param {string} key \n * @param {string} value \n * @param {number} timestamp\n * @return {void}\n */\nTimeMap.prototype.set = function(key, value, timestamp) {\n        if(!this.data.has(key)){\n        this.data.set(key, [{timestamp: timestamp, value: value}])\n    } else {\n        let temp_store = this.data.get(key);\n        temp_store.push({timestamp: timestamp, value: value});\n        this.data.set(key, temp_store);\n    }\n};\n\n/** \n * @param {string} key \n * @param {number} timestamp\n * @return {string}\n */\nTimeMap.prototype.get = function(key, timestamp) {\n    if(this.data.has(key)){\n        const keyArray = this.data.get(key);\n        \n        //Optimize with binary search - Ordered by insert time, O(log n) devide and conq method (Like searching a dictionary)\n        const index = keyArray.binarySearch(timestamp);           \n        if(keyArray[index].timestamp > timestamp){\n            return ''\n        }\n        \n        return keyArray[index].value || prev;\n    }\n    \n    return '';\n};\n\nArray.prototype.binarySearch = function(key){\n        let left = 0;\n        let right = this.length - 1;\n        \n        while (left < right) {\n            const i = Math.floor((left + right + 1) / 2);\n            if (this[i].timestamp > key) {\n                right = i - 1;\n            } else {\n                left = i;\n            }\n        }\n        \n        return left;\n}\n\n\n/** \n * Your TimeMap object will be instantiated and called as such:\n * var obj = new TimeMap()\n * obj.set(key,value,timestamp)\n * var param_2 = obj.get(key,timestamp)\n */",
        "solution_java": "class TimeMap {\n    private Map<String, List<Entry>> map;\n    private final String NOT_FOUND = \"\";\n    public TimeMap() {\n        map = new HashMap<>();\n    }\n    \n    public void set(String key, String value, int timestamp) {\n        List<Entry> entries = map.getOrDefault(key, new ArrayList<>());\n        entries.add(new Entry(value, timestamp));\n        map.put(key, entries);\n    }\n    \n    public String get(String key, int timestamp) {\n        List<Entry> entries = map.get(key);\n        if (entries == null) {\n            return NOT_FOUND;\n        }\n        return binarySearch(entries, timestamp);\n    }\n    \n    private String binarySearch(List<Entry> entries, int timestamp) {\n        int lo = 0, hi = entries.size() - 1, mid = -1;\n        String ans = \"\";\n        \n        // Base cases - if value is not set, return empty\n        if (entries.get(lo).timestamp > timestamp) {\n            return NOT_FOUND;\n        }\n        // If timestamp is equal or greater, return the last value saved in map against this key, since that will have the largest timestamp\n        else if (entries.get(hi).timestamp <= timestamp) {\n            return entries.get(hi).value;\n        }\n        \n        // Else apply binary search to get correct value\n        while (lo <= hi) {\n            mid = lo + (hi-lo)/2;\n            Entry entry = entries.get(mid);\n            // System.out.println(\"mid: \"+mid);\n            if (entry.timestamp == timestamp) {\n                return entry.value;\n            }\n            // Save ans, and look for ans on right half to find greater timestamp\n            else if (entry.timestamp < timestamp) {\n                ans = entry.value;\n                lo = mid + 1;\n            }\n            else {\n                hi = mid - 1;\n            }\n        }\n        return ans;\n    }\n}\n\nclass Entry {\n    String value;\n    int timestamp;\n    \n    public Entry(String value, int timestamp) {\n        this.value = value;\n        this.timestamp = timestamp;\n    }\n}",
        "solution_c": "class TimeMap {\npublic:\n    map<string,vector<pair<int,string>>> mp;\n    string Max;\n    TimeMap() {\n        Max = \"\";\n    }\n    \n    void set(string key, string value, int timestamp) {\n        mp[key].push_back(make_pair(timestamp,value));\n        Max = max(Max,value);\n    }\n    \n    string get(string key, int timestamp) {\n        pair<int,string> p = make_pair(timestamp,Max);\n        int l = upper_bound(mp[key].begin(),mp[key].end(),p)-mp[key].begin();\n        if(l==0){\n            return \"\";\n        }\n        return mp[key][l-1].second;\n    }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */"
    },
    {
        "title": "Number of Students Doing Homework at a Given Time",
        "algo_input": "Given two integer arrays startTime and endTime and given an integer queryTime.\n\nThe ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].\n\nReturn the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.\n\n&nbsp;\nExample 1:\n\nInput: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput: 1\nExplanation: We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\n\n\nExample 2:\n\nInput: startTime = [4], endTime = [4], queryTime = 4\nOutput: 1\nExplanation: The only student was doing their homework at the queryTime.\n\n\n&nbsp;\nConstraints:\n\n\n\tstartTime.length == endTime.length\n\t1 &lt;= startTime.length &lt;= 100\n\t1 &lt;= startTime[i] &lt;= endTime[i] &lt;= 1000\n\t1 &lt;= queryTime &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def busyStudent(self, startTime, endTime, queryTime):\n        res = 0\n        for i in range(len(startTime)):\n            if startTime[i] <= queryTime <= endTime[i]:\n                res += 1\n            else:\n                pass\n        return res",
        "solution_js": "var busyStudent = function(startTime, endTime, queryTime) {\n    let res = 0;\n\n    for (let i = 0; i < startTime.length; i++) {\n        if (startTime[i] <= queryTime && endTime[i] >= queryTime) res++;\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public int busyStudent(int[] startTime, int[] endTime, int queryTime) {\n        int count = 0;\n        for (int i = 0; i < startTime.length; ++i) {\n            if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {\n        int ans = 0 ;\n        for(int i = 0 ; i < size(startTime); ++i )\n            if(queryTime >= startTime[i] and queryTime <= endTime[i]) ++ans ;\n        \n        return ans ;\n    }\n};"
    },
    {
        "title": "Distance Between Bus Stops",
        "algo_input": "A bus&nbsp;has n stops numbered from 0 to n - 1 that form&nbsp;a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number&nbsp;i and (i + 1) % n.\n\nThe bus goes along both directions&nbsp;i.e. clockwise and counterclockwise.\n\nReturn the shortest distance between the given&nbsp;start&nbsp;and destination&nbsp;stops.\n\n&nbsp;\nExample 1:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 1\nOutput: 1\nExplanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\n\n&nbsp;\n\nExample 2:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 2\nOutput: 3\nExplanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\n\n\n&nbsp;\n\nExample 3:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 3\nOutput: 4\nExplanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n&nbsp;&lt;= 10^4\n\tdistance.length == n\n\t0 &lt;= start, destination &lt; n\n\t0 &lt;= distance[i] &lt;= 10^4\n",
        "solution_py": "class Solution:\n    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n        # switch start and destination if destination is before start\n        if start>destination:    \n            start,destination=destination,start\n        #find minimum for clockwise and counterclockwise direction\n        return  min(sum(distance[start:destination]),sum(distance[:start]+distance[destination:]))",
        "solution_js": "/**\n * @param {number[]} distance\n * @param {number} start\n * @param {number} destination\n * @return {number}\n */\nlet sumArray = (arr) => {\n    return arr.reduce((prev, curr) => prev + curr, 0)\n}\n\nvar distanceBetweenBusStops = function(distance, start, destination) {\n    let dist = sumArray(distance.slice((start < destination)?start:destination, (start < destination)?destination:start));\n    return Math.min(dist, sumArray(distance) - dist)\n};",
        "solution_java": "class Solution {\n    public int distanceBetweenBusStops(int[] distance, int start, int destination) {\n        int firstDistance = 0;\n        int secondDistance = 0;\n        if (start < destination) {\n            //check clockwise rotation\n            for (int i = start; i < destination; i++)\n                firstDistance += distance[i];\n            //check clockwise rotation from destination to end\n            for (int i = destination; i < distance.length; i++)\n                secondDistance += distance[i];\n            //continues checking till start (if needed)\n            for (int i = 0; i < start; i++)\n                secondDistance += distance[i];\n        }\n        else {\n            for (int i = start; i < distance.length; i++)\n                firstDistance += distance[i];\n            for (int i = 0; i < destination; i++)\n                firstDistance += distance[i];\n            for (int i = start - 1; i >= destination; i--)\n                secondDistance += distance[i];\n        }\n        return Math.min(firstDistance, secondDistance);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {\n        int n = distance.size();\n        if (start == destination)\n            return 0;\n\n        int one_way = 0;\n        int i = start;\n        while (i != destination) // find distance of one way\n        {\n            one_way += distance[i];\n            i = (i+1)%n;\n        }\n        \n        int second_way = 0;\n        i = destination;\n        while (i != start) // find distance of second way\n        {\n            second_way += distance[i];\n            i = (i+1)%n;\n        }\n        \n        return one_way<second_way? one_way : second_way; // return the minimum\n    }\n};"
    },
    {
        "title": "Hamming Distance",
        "algo_input": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nGiven two integers x and y, return the Hamming distance between them.\n\n&nbsp;\nExample 1:\n\nInput: x = 1, y = 4\nOutput: 2\nExplanation:\n1   (0 0 0 1)\n4   (0 1 0 0)\n       ↑   ↑\nThe above arrows point to positions where the corresponding bits are different.\n\n\nExample 2:\n\nInput: x = 3, y = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;=&nbsp;x, y &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def hammingDistance(self, x: int, y: int) -> int:\n\t\t# First, using XOR Bitwise Operator, we take all distinct set bits.\n        z = x ^ y\n\t\t# We inicialize our answer with zero.\n        ans = 0\n\t\t# Iterate while our z is not zero.\n        while z:\n\t\t\t# Every iteration we add one to our answer.\n            ans += 1\n\t\t\t# Using the expression z & (z - 1), we erase the lowest set bit in z.\n            z &= z - 1\n        return ans",
        "solution_js": "var hammingDistance = function(x, y) {\n  x = x.toString(2).split('')\n  y = y.toString(2).split('')\n  \n  let count = 0;\n  const len = Math.max(x.length,y.length);\n\n  if (x.length < y.length) {\n    x = Array(len - x.length).fill('0').concat(x)\n  } else {\n    y = Array(len - y.length).fill('0').concat(y)\n  } \n\n  for (let i = 1; i <= len; i++) {\n    x.at(-i) !== y.at(-i)? count++ : null    \n  }\n\n  return count\n};",
        "solution_java": "class Solution {\n    public int hammingDistance(int x, int y) {\n        int ans=x^y;\n        int count=0;\n        while(ans>0){\n            count+=ans&1;\n            ans>>=1;\n        }\n        \n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int hammingDistance(int x, int y) {\n        int val = (x^y);\n        int ans = 0;\n        for(int i = 31; i >= 0; --i){\n            if(val & (1 << i)) ans++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Self Dividing Numbers",
        "algo_input": "A self-dividing number is a number that is divisible by every digit it contains.\n\n\n\tFor example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\n\n\nA self-dividing number is not allowed to contain the digit zero.\n\nGiven two integers left and right, return a list of all the self-dividing numbers in the range [left, right].\n\n&nbsp;\nExample 1:\nInput: left = 1, right = 22\nOutput: [1,2,3,4,5,6,7,8,9,11,12,15,22]\nExample 2:\nInput: left = 47, right = 85\nOutput: [48,55,66,77]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= left &lt;= right &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n        res = []\n        for num in range(left, right + 1):\n            num_str = str(num)\n            if '0' in num_str:\n                continue\n            elif all([num % int(digit_str) == 0 for digit_str in num_str]):\n                res.append(num)\n        return res",
        "solution_js": "/**\n * @param {number} left\n * @param {number} right\n * @return {number[]}\n */\nvar selfDividingNumbers = function(left, right) {\n  const selfDivisibles = [];\n  for (let i = left; i <= right; i++) {\n    if (checkDivisibility(i)) {\n      selfDivisibles.push(i);\n    }\n  }\n  return selfDivisibles;\n};\n\nfunction checkDivisibility(num) {\n  let status = true;\n  let mod;\n  let original = num;\n  while (num !== 0) {\n    mod = Math.trunc(num % 10);\n    if (original % mod !== 0) {\n      status = false;\n      break;\n    }\n    num = Math.trunc(num / 10);\n  }\n  return status;\n}",
        "solution_java": "class Solution {\n    public List<Integer> selfDividingNumbers(int left, int right) {\n        List<Integer> ans= new ArrayList<>();\n        while(left<=right){\n            if(fun(left))\n                ans.add(left);        \n            left++;\n        }\n        return ans;\n    }\n    boolean fun(int x){\n        int k=x;\n        while(k>0)\n        {\n            int y=k%10;\n            k=k/10;\n            if(y==0||x%y!=0)\n                return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool check(int n){\n        vector<bool> isif(10);\n        for(int i = 1; i <= 9; i++){\n            if(n % i == 0) isif[i] = 1;\n        }\n        \n        while(n > 0){\n            if(isif[n%10] == 0) return false;\n            n /= 10;\n        }\n        return true;\n    }\n    vector<int> selfDividingNumbers(int left, int right) {\n        vector<int> ans;\n        for(int i = left; i <= right; i++){\n            if(check(i)) ans.push_back(i);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Valid Palindrome",
        "algo_input": "A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.\n\nGiven a string s, return true if it is a palindrome, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\nExplanation: \"amanaplanacanalpanama\" is a palindrome.\n\n\nExample 2:\n\nInput: s = \"race a car\"\nOutput: false\nExplanation: \"raceacar\" is not a palindrome.\n\n\nExample 3:\n\nInput: s = \" \"\nOutput: true\nExplanation: s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 2 * 105\n\ts consists only of printable ASCII characters.\n\n",
        "solution_py": "class Solution:\n    def isPalindrome(self, s: str) -> bool:\n        cleaned = \"\"\n        for c in s:\n            if c.isalnum():\n                cleaned += c.lower()\n        return (cleaned == cleaned[::-1])\n\n            ",
        "solution_js": "var isPalindrome = function(s) {\n  const toLower = s.toLowerCase().replace(/[\\W_\\s]+/g, '').replace(/ /g, '')\n  let m = 0\n  let n = toLower.length - 1\n\n  while (m < n) {\n    if (toLower[m] !== toLower[n]) {\n      return false\n    }\n    m++\n    n--\n  }\n  return true\n}",
        "solution_java": "class Solution {\n    public boolean isPalindrome(String s) {\n        if(s.length()==1 || s.length()==0)\n        {\n            return true;\n        }\n\n        s=s.trim().toLowerCase();\n        //s=s.toLowerCase();\n        String a=\"\";\n        boolean bool=false;\n        for(int i=0;i<s.length();i++)\n        {\n            if((s.charAt(i)>='a' && s.charAt(i)<='z') || (s.charAt(i)>='0' && s.charAt(i)<='9'))\n            {\n                a=a+s.charAt(i);\n            }\n        }\n        if(a.length()==1 || a.length()==0)\n        {\n            return true;\n        }\n        for(int i=0;i<a.length()/2;i++)\n        {\n            if(a.charAt(i)==a.charAt(a.length()-i-1))\n            {\n                bool=true;\n            }\n            else{\n                return false;\n            }\n        }\n\n        return bool;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPalindrome(string s) {\n        auto it = remove_if(s.begin(), s.end(), [](char const &c) {\n            return !isalnum(c);\n        });\n\n        s.erase(it, s.end());\n        transform(s.begin(), s.end(), s.begin(), ::tolower);\n\n        int i = 0;\n        int j = s.size()-1;\n\n        while(i <= j) {\n            if(s[i] != s[j]) return false;\n            i++; j--;\n        }\n\n        return true;\n    }\n};"
    },
    {
        "title": "Find Smallest Letter Greater Than Target",
        "algo_input": "Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.\n\nNote that the letters wrap around.\n\n\n\tFor example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.\n\n\n&nbsp;\nExample 1:\n\nInput: letters = [\"c\",\"f\",\"j\"], target = \"a\"\nOutput: \"c\"\n\n\nExample 2:\n\nInput: letters = [\"c\",\"f\",\"j\"], target = \"c\"\nOutput: \"f\"\n\n\nExample 3:\n\nInput: letters = [\"c\",\"f\",\"j\"], target = \"d\"\nOutput: \"f\"\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= letters.length &lt;= 104\n\tletters[i] is a lowercase English letter.\n\tletters is sorted in non-decreasing order.\n\tletters contains at least two different characters.\n\ttarget is a lowercase English letter.\n\n",
        "solution_py": "class Solution:\n    def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n        beg = 0\n        end = len(letters)-1\n        while beg <= end:\n            mid = (beg+end)//2\n            if letters[mid]>target:\n                end = mid -1\n            else:\n                beg = mid +1\n        return letters[beg] if beg<len(letters) else letters[0]",
        "solution_js": "/**\n * @param {character[]} letters\n * @param {character} target\n * @return {character}\n */\nvar nextGreatestLetter = function(letters, target) {\n    let result=[]\n    for (letter of letters){\n        if (letter>target){\n            result.push(letter);\n        }\n    }\n    if (result.length){\n        return result[0];\n    }\n    else{\n        return letters[0];\n    }\n    \n};",
        "solution_java": "class Solution {\n    public char nextGreatestLetter(char[] letters, char target) {\n        int start=0,end=letters.length-1;\n    while(start<=end){\n      int mid=start+(end-start)/2;\n      if(letters[mid]>target){    //strictly greater is the solution we want\n        end = mid-1;\n      }else{\n        start=mid+1;\n      }\n    }\n    return letters[start % letters.length];    // this is the wrap around condition , we use modulo %\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    char nextGreatestLetter(vector<char>& letters, char target) {\n\n        int siz = letters.size();\n        bool isPresent = false;\n        char ans;\n        char temp = target;\n\n        if (target == letters[siz-1]) return letters[0];\n\n        for(int i=0; i<siz-1; i++) {\n            if (target == letters[i] && target != letters[i+1]) {\n                ans = letters[i+1];\n                isPresent = true;\n                break;\n            }\n        }\n\n        // if target not in letters\n        while (!isPresent) {\n            temp = temp +1;\n            isPresent = binary_search(letters.begin(), letters.end(), temp); // used STL !!\n            if(isPresent) {\n                ans=temp;\n                break;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimize Deviation in Array",
        "algo_input": "You are given an array nums of n positive integers.\n\nYou can perform two types of operations on any element of the array any number of times:\n\n\n\tIf the element is even, divide it by 2.\n\n\t\n\t\tFor example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].\n\t\n\t\n\tIf the element is odd, multiply it by 2.\n\t\n\t\tFor example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].\n\t\n\t\n\n\nThe deviation of the array is the maximum difference between any two elements in the array.\n\nReturn the minimum deviation the array can have after performing some number of operations.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n\n\nExample 2:\n\nInput: nums = [4,1,5,20,3]\nOutput: 3\nExplanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n\n\nExample 3:\n\nInput: nums = [2,10,8]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t2 &lt;= n &lt;= 5 * 104\n\t1 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n\tdef minimumDeviation(self, nums: List[int]) -> int:\n\n\t\tfrom sortedcontainers import SortedList\n\n\t\tfor i in range(len(nums)):\n\n\t\t\tif nums[i]%2!=0:\n\t\t\t\tnums[i]=nums[i]*2\n\n\t\tnums = SortedList(nums)\n\n\t\tresult = 100000000000\n\n\t\twhile True:\n\t\t\tmin_value = nums[0]\n\t\t\tmax_value = nums[-1]\n\n\t\t\tif max_value % 2 == 0:\n\t\t\t\tnums.pop()\n\t\t\t\tnums.add(max_value // 2)\n\t\t\t\tmax_value = nums[-1]\n\t\t\t\tmin_value = nums[0]\n\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\telse:\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\t\tbreak\n\n\t\treturn result",
        "solution_js": "var minimumDeviation = function(nums) {\n    let pq = new MaxPriorityQueue({priority: x => x})\n    for (let n of nums) {\n        if (n % 2) n *= 2\n        pq.enqueue(n)\n    }\n    let ans = pq.front().element - pq.back().element\n    while (pq.front().element % 2 === 0) {\n        pq.enqueue(pq.dequeue().element / 2)\n        ans = Math.min(ans, pq.front().element - pq.back().element)\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public int minimumDeviation(int[] nums) {\n        TreeSet<Integer> temp = new TreeSet<>();\n        for(int i: nums){\n            if(i % 2 == 0){\n                temp.add(i);\n            }\n            else{\n                temp.add(i * 2);\n            }\n        }\n\n        int md = temp.last() - temp.first();\n        int m = 0;\n\n        while(temp.size() > 0 && temp.last() % 2 == 0){\n            m = temp.last();\n            temp.remove(m);\n            temp.add(m / 2);\n\n            md = Math.min(md, temp.last() - temp.first());\n        }\n        return md;\n    }\n}",
        "solution_c": "\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n    int minimumDeviation(vector<int>& nums) {\n        int n = nums.size();\n        int mx = INT_MIN, mn = INT_MAX;\n        \n        // Increasing all elements to as maximum as it can and tranck the minimum,\n        // number and also the resutl\n        for(int i = 0; i<n; ++i)\n        {\n            if((nums[i]%2) != 0)    // multiplication by 2 if nums[i] is odd\n                nums[i] *= 2;   // maximising all odd numbers\n\n        \n            mx = max(mx,nums[i]);\n            mn = min(mn,nums[i]);\n        }\n        \n        int min_deviation = mx - mn;\n        \n        priority_queue<int> pq;\n        // Inserting into Priority queue (Max Heap) and try to decrease as much we can\n        for(int i = 0; i<n; ++i)\n        {\n            pq.push(nums[i]);\n        }\n        \n        while((pq.top()) % 2 == 0)\n        {\n            int top = pq.top();\n            pq.pop(); // popped the top element\n            \n            min_deviation = min(min_deviation, top - mn);\n            top /= 2;\n            mn = min(mn, top);  // updating min\n            pq.push(top);   // pushing again the top as we have to minimize the max\n        }\n        \n        min_deviation = min(min_deviation, pq.top() - mn);\n        \n        // we are returning mx - mn\n        \n        return min_deviation;\n    }\n};"
    },
    {
        "title": "Set Matrix Zeroes",
        "algo_input": "Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.\n\nYou must do it in place.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: [[1,0,1],[0,0,0],[1,0,1]]\n\n\nExample 2:\n\nInput: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[0].length\n\t1 &lt;= m, n &lt;= 200\n\t-231 &lt;= matrix[i][j] &lt;= 231 - 1\n\n\n&nbsp;\nFollow up:\n\n\n\tA straightforward solution using O(mn) space is probably a bad idea.\n\tA simple improvement uses O(m + n) space, but still not the best solution.\n\tCould you devise a constant space solution?\n\n",
        "solution_py": "class Solution:\n    def setZeroes(self, matrix: List[List[int]]) -> None:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        visited=set()\n        for r in range(rows):\n            for c in range(cols):\n                \n                if matrix[r][c]==0 and (r,c) not in visited :\n                    for t in range(cols):\n                        if matrix[r][t]!=0:\n                            matrix[r][t]=0\n                            visited.add((r,t))\n                    for h in range(rows):\n                        if matrix[h][c]!=0:\n                            matrix[h][c]=0\n                            visited.add((h,c))\n        ##Time Complexity :- O(m*n)\n        ##Space Complexity:- O(m+n)\n\t\t\n\t\t```",
        "solution_js": "var setZeroes = function(matrix) {\nlet rows = new Array(matrix.length).fill(0); //to store the index of rows to be set to 0\nlet cols = new Array(matrix[0].length).fill(0);//to store the index of columns to be set to 0\nfor(let i=0; i<matrix.length; i++){\n    for(let j=0; j<matrix[i].length; j++){\n        if(matrix[i][j]===0){//for zero value both row and column will be set to 0\n            rows[i] = 1;\n            cols[j] = 1;\n        }\n    }\n}\n\nfor(let i=0; i<matrix.length; i++){\n    for(let j=0; j<matrix[i].length; j++){\n        if(rows[i]===1 || cols[j]===1){//if either row or col val is set, poulate it with 0\n            matrix[i][j] = 0;\n        }\n    }\n}\n};",
        "solution_java": "class Solution {\n    public void setZeroes(int[][] matrix) {        \n\t\tif (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n\t\t\treturn;\n\n\t\tint row = matrix.length;\n\t\tint col = matrix[0].length;\n\n\t\tboolean firstColumnZero = false;\n\t\tboolean firstRowZero = false;\n\n\t\t// Check if first column should be made zero\n\t\tfor (int i = 0; i < row; i++) {\n\t\t\tif (matrix[i][0] == 0) {\n\t\t\t\tfirstColumnZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Check if first row should be made zero\n\t\tfor (int i = 0; i < col; i++) {\n\t\t\tif (matrix[0][i] == 0) {\n\t\t\t\tfirstRowZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse the matrix excluding first row and column\n\t\t// If zero is found, update the same in first row and column\n\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][j] == 0) {\n\t\t\t\t\tmatrix[i][0] = 0;\n\t\t\t\t\tmatrix[0][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Now traverse again and update\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][0] == 0 || matrix[0][j] == 0) {\n\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first column\n\t\tif (firstColumnZero) {\n\t\t\tfor (int i = 0; i < row; i++) {\n\t\t\t\tmatrix[i][0] = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first row\n\t\tif (firstRowZero) {\n\t\t\tfor (int j = 0; j < col; j++) {\n\t\t\t\tmatrix[0][j] = 0;\n\t\t\t}\n\t\t}\n\n\t\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void setZeroes(vector<vector<int>>& matrix) {\n        unordered_map<int,int>ump;\n        unordered_map<int,int>mp;\n        for(int i=0;i<matrix.size();i++){\n            for(int j=0;j<matrix[0].size();j++){\n                if(matrix[i][j]==0){\n                    ump[i]=1;\n                    mp[j]=1;\n                }\n            }\n        }\n        for(int i=0;i<matrix.size();i++){\n            for(int j=0;j<matrix[0].size();j++){\n                if(ump[i] || mp[j]){\n                    matrix[i][j]=0;\n                }\n            }\n        }\n\n\n        \n        \n    }\n};"
    },
    {
        "title": "Greatest English Letter in Upper and Lower Case",
        "algo_input": "Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.\n\nAn English letter b is greater than another letter a if b appears after a in the English alphabet.\n\n&nbsp;\nExample 1:\n\nInput: s = \"lEeTcOdE\"\nOutput: \"E\"\nExplanation:\nThe letter 'E' is the only letter to appear in both lower and upper case.\n\n\nExample 2:\n\nInput: s = \"arRAzFif\"\nOutput: \"R\"\nExplanation:\nThe letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.\n\n\nExample 3:\n\nInput: s = \"AbCdEfGhIjK\"\nOutput: \"\"\nExplanation:\nThere is no letter that appears in both lower and upper case.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of lowercase and uppercase English letters.\n\n",
        "solution_py": "class Solution:\n    def greatestLetter(self, s: str) -> str:\n        cnt = Counter(s)\n        return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), \"\")",
        "solution_js": "var greatestLetter = function(s) {\n    let set=new Set(s.split(\"\"));\n\t// ASCII(A-Z, a-z)=(65-90, 97-122).\n    for(let i=90; i>=65; i--){\n        if(set.has(String.fromCharCode(i)) && set.has(String.fromCharCode(i+32))){\n            return String.fromCharCode(i);\n        }\n    }\n    return \"\";\n};",
        "solution_java": "class Solution\n{\n    public String greatestLetter(String s)\n    {\n        Set<Character> set = new HashSet<>();\n        for(char ch : s.toCharArray())\n            set.add(ch);\n        \n        for(char ch = 'Z'; ch >= 'A'; ch--)\n            if(set.contains(ch) && set.contains((char)('a'+(ch-'A'))))\n               return \"\"+ch;\n        return \"\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    string greatestLetter(string s)\n    {\n        vector<int> low(26), upp(26); //storing occurences of lower and upper case letters\n        string res = \"\";\n\n        for(auto it : s) //iterate over each char and mark it in respective vector\n        {\n            if(it-'A'>=0 && it-'A'<26)\n                upp[it-'A']++;\n            else\n                low[it-'a']++;\n        }\n\n        for(int i=25; i>=0; i--) //start from greater char\n        {\n            if(low[i] && upp[i]) //if char found in upp and low that will be the result\n            {\n                res += 'A'+i;\n                break;\n            }\n\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Wildcard Matching",
        "algo_input": "Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:\n\n\n\t'?' Matches any single character.\n\t'*' Matches any sequence of characters (including the empty sequence).\n\n\nThe matching should cover the entire input string (not partial).\n\n&nbsp;\nExample 1:\n\nInput: s = \"aa\", p = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\n\n\nExample 2:\n\nInput: s = \"aa\", p = \"*\"\nOutput: true\nExplanation:&nbsp;'*' matches any sequence.\n\n\nExample 3:\n\nInput: s = \"cb\", p = \"?a\"\nOutput: false\nExplanation:&nbsp;'?' matches 'c', but the second letter is 'a', which does not match 'b'.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length, p.length &lt;= 2000\n\ts contains only lowercase English letters.\n\tp contains only lowercase English letters, '?' or '*'.\n\n",
        "solution_py": "class Solution:\n    def isMatch(self, s: str, p: str) -> bool:\n        m= len(s)\n        n= len(p)\n\n        dp = [[False]*(n+1) for i in range(m+1)]\n\n        dp[0][0] = True\n\n        for j in range(len(p)):\n            if p[j] == \"*\":\n                dp[0][j+1] = dp[0][j]\n\n        for i in range(1,m+1):\n            for j in range(1,n+1):\n                if p[j-1] == \"*\":\n                    dp[i][j] = dp[i-1][j] or dp[i][j-1]\n\n                elif s[i-1] == p[j-1] or p[j-1] == \"?\":\n                    dp[i][j] = dp[i-1][j-1]\n\n        return dp[-1][-1]",
        "solution_js": "var isMatch = function(s, p) {\n    const slen = s.length, plen = p.length;\n    const dp   = new Map();\n    \n    const solve = (si = 0, pi = 0) => {\n        // both are compared and are equal till end\n        if(si == slen && pi == plen) return true;\n        // we have consumed are wildcard string and still s is remaining\n        if(pi == plen) return false;\n        // we still have wildcard characters remaining\n        if(si == slen) {\n            while(p[pi] == '*') pi++;\n            return pi == plen;\n        }\n           \n        const key = [si, pi].join(':');\n        if(dp.has(key)) return dp.get(key);\n        \n        let ans = false;\n        if(p[pi] == '*') {\n\t\t\t// drop * or use it\n            ans = solve(si, pi + 1) || solve(si + 1, pi);\n        } else {\n            const match = s[si] == p[pi] || p[pi] == '?';\n            if(match) ans = solve(si + 1, pi + 1);   \n        }\n        \n        dp.set(key, ans);\n        \n        return ans;\n    }\n    return solve();\n};",
        "solution_java": "class Solution {\n    public boolean isMatch(String s, String p) {\n        int i=0;\n        int j=0;\n        int starIdx=-1;\n        int lastMatch=-1;\n\n        while(i<s.length()){\n            if(j<p.length() && (s.charAt(i)==p.charAt(j) ||\n              p.charAt(j)=='?')){\n                i++;\n                j++;\n            }else if(j<p.length() && p.charAt(j)=='*'){\n                starIdx=j;\n                lastMatch=i;\n                j++;\n            }else if(starIdx!=-1){\n            //there is a no match and there was a previous star, we will reset the j to indx after star_index\n            //lastMatch will tell from which index we start comparing the string if we encounter * in pattern\n                j=starIdx+1;\n                lastMatch++; // we are saying we included more characters in * so we incremented the index\n                i=lastMatch;\n\n            }else{\n                return false;\n            }\n        }\n\n        while(j<p.length() && p.charAt(j)=='*') j++;\n\n        if(i!=s.length() || j!=p.length()) return false;\n\n        return true;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool match(int i, int j, string &a, string &b, vector<vector<int>>&dp)\n    {\n        if(i<0 && j<0) return true;\n        if(i>=0 && j<0) return false;\n        if(i<0 && j>=0)\n        {\n            for(;j>-1;j--) if(b[j]!='*') return false;\n            return true;\n        }\n        if(dp[i][j]!=-1) return dp[i][j];\n        if(a[i]==b[j] || b[j]=='?') return dp[i][j] = match(i-1,j-1,a,b,dp);\n        if(b[j]=='*') return dp[i][j] = (match(i-1,j,a,b,dp) | match(i,j-1,a,b,dp));\n        return false;\n    }\n    bool isMatch(string s, string p) {\n        int n=s.size(), m=p.size();\n        vector<vector<int>>dp(n+1,vector<int>(m+1,-1));\n        return match(n-1,m-1,s,p,dp);\n    }\n};"
    },
    {
        "title": "Reverse Linked List II",
        "algo_input": "Given the head of a singly linked list and two integers left and right where left &lt;= right, reverse the nodes of the list from position left to position right, and return the reversed list.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5], left = 2, right = 4\nOutput: [1,4,3,2,5]\n\n\nExample 2:\n\nInput: head = [5], left = 1, right = 1\nOutput: [5]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 &lt;= n &lt;= 500\n\t-500 &lt;= Node.val &lt;= 500\n\t1 &lt;= left &lt;= right &lt;= n\n\n\n&nbsp;\nFollow up: Could you do it in one pass?",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n        # revrese api\n        def reverse(start, end):\n            prev = None\n            cur = start\n            while prev != end:\n                nextNode = cur.next\n                cur.next = prev\n                prev = cur\n                cur = nextNode\n            return prev\n        \n        if not head or not head.next or right <= left:\n            return head\n        \n        start, end = head, head\n        node, afterRight = 0, 0\n        \n        # At the begining\n        if left == 1:\n            # start index \n            inc = left-1\n            while inc > 0:\n                start = start.next\n                inc -= 1\n            # end index\n            inc = right-1\n            while inc > 0:\n                end = end.next\n                inc -= 1\n            afterRight = end.next\n            reverse(start, end)\n            head = end\n        else: # Left other then begining\n            # start index \n            inc = left-2\n            while inc > 0:\n                start = start.next\n                inc -= 1\n            # end index\n            inc = right-1\n            while inc > 0:\n                end = end.next\n                inc -= 1\n            afterRight = end.next\n            begin = start # node before left\n            start = start.next\n            reverse(start, end)\n            begin.next = end\n            \n        # If their's ll chain left agter right chain it to the updated ll\n        if afterRight:\n            start.next = afterRight\n\n        return head\n    \n\"\"\"\nTC : O(n)\nSc : O(1)\n\n\"\"\"",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\n\nvar reverseBetween = function(head, left, right) {\n    \n    if (!head || !head.next || left === right) {\n        \n        return head;\n    }\n        \n        let dummyHead = new ListNode(-1);\n\n        dummyHead.next = head;\n\n        let prev = dummyHead;\n\n        for (let i = 1; i < left; i++) {\n            \n            prev = prev.next;\n        }\n\n        let curr = prev.next;\n\n        for (let i = left; i < right; i++) {\n\n            let next = curr.next;\n            curr.next = next.next;\n            next.next = prev.next;\n            prev.next = next;\n        }\n        \n        return dummyHead.next;\n};",
        "solution_java": "class Solution {\n    public ListNode reverseBetween(ListNode head, int left, int right) {\n        if(left==right) return head;\n        ListNode last = null;\n        ListNode present = head;\n        \n        for(int i=0; present != null && i<left-1;i++){\n            last = present;\n            present = present.next;\n        }\n        ListNode finalEnd = present;\n        \n        ListNode prev = last;\n        ListNode next = present.next;\n        \n        for(int i=0; present != null && i<right-left+1;i++){\n            present.next = prev;\n            prev = present;\n            present = next;\n            if(next!= null){\n                next = next.next;\n            }\n        }\n        if(last != null){\n            last.next = prev;\n        }\n        else{\n            head = prev;\n        } \n        finalEnd.next = present;\n        return head;\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n\n    ListNode* reverse(ListNode* head)\n    {\n        ListNode* prev = NULL;\n        while(head != NULL)\n        {\n            ListNode* temp = head->next;\n            head->next = prev;\n            prev = head;\n            head = temp;\n        }\n        return prev;\n    }\n\n    ListNode* reverseN(ListNode* head,int right)\n    {\n        ListNode* temp = head;\n        while(right != 1)\n            temp = temp->next,right--;\n\n        ListNode* temp2 = temp->next;\n        temp->next = NULL;\n\n        ListNode* ans = reverse(head);\n        head->next = temp2;\n        return ans;\n\n    }\n\n    ListNode* reverseBetween(ListNode* head, int left, int right) {\n\n          if(left == right)\n              return head;\n\n          if(left == 1)\n          {\n              return reverseN(head,right);\n          }\n          else\n          {\n              ListNode* temp = head;\n              right--;\n              while(left != 2)\n              {\n                  temp = temp->next;\n                  left--;\n                  right--;\n              }\n              ListNode* temp2 = reverseN(temp->next,right);\n              temp->next = temp2;\n              return head;\n          }\n\n         return NULL;\n\n    }\n};"
    },
    {
        "title": "Count Operations to Obtain Zero",
        "algo_input": "You are given two non-negative integers num1 and num2.\n\nIn one operation, if num1 &gt;= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.\n\n\n\tFor example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.\n\n\nReturn the number of operations required to make either num1 = 0 or num2 = 0.\n\n&nbsp;\nExample 1:\n\nInput: num1 = 2, num2 = 3\nOutput: 3\nExplanation: \n- Operation 1: num1 = 2, num2 = 3. Since num1 &lt; num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 &gt; num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.\n\n\nExample 2:\n\nInput: num1 = 10, num2 = 10\nOutput: 1\nExplanation: \n- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num1, num2 &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def countOperations(self, num1: int, num2: int) -> int:\n        ct=0\n        while num2 and num1:\n            if num1>=num2:\n                num1=num1-num2\n            else:\n                num2=num2-num1\n            ct+=1\n        return ct",
        "solution_js": "/**\n * @param {number} num1\n * @param {number} num2\n * @return {number}\n */\nvar countOperations = function(num1, num2) {\n    let count = 0;\n    while (num1 !== 0 && num2 !== 0) {\n        if (num1 <= num2) num2 -= num1;\n        else num1 -= num2;\n        count++;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int countOperations(int num1, int num2) {\n        int count=0;\n        while(num1!=0 && num2!=0){\n            if(num1<num2){\n                count+=num2/num1;\n                num2=num2%num1;\n            }else{\n                count+=num1/num2;\n                num1=num1%num2;\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countOperations(int num1, int num2) {\n        if(num1==0 || num2==0) return 0;\n        if(num1>=num2) num1=num1-num2;\n        else if(num2>num1) num2=num2-num1;\n        return 1+countOperations(num1,num2);\n    }\n};"
    },
    {
        "title": "Delete Columns to Make Sorted",
        "algo_input": "You are given an array of n strings strs, all of the same length.\n\nThe strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as:\n\nabc\nbce\ncae\n\n\nYou want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.\n\nReturn the number of columns that you will delete.\n\n&nbsp;\nExample 1:\n\nInput: strs = [\"cba\",\"daf\",\"ghi\"]\nOutput: 1\nExplanation: The grid looks as follows:\n  cba\n  daf\n  ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.\n\n\nExample 2:\n\nInput: strs = [\"a\",\"b\"]\nOutput: 0\nExplanation: The grid looks as follows:\n  a\n  b\nColumn 0 is the only column and is sorted, so you will not delete any columns.\n\n\nExample 3:\n\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: The grid looks as follows:\n  zyx\n  wvu\n  tsr\nAll 3 columns are not sorted, so you will delete all 3.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == strs.length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= strs[i].length &lt;= 1000\n\tstrs[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def minDeletionSize(self, strs: List[str]) -> int:\n\n        cols={}\n        l=len(strs)\n        l_s = len(strs[0])\n        delete = set()\n        for i in range(l):\n            for col in range(l_s):\n                if col in cols:\n                    if cols[col]>strs[i][col]:\n                        delete.add(col)\n                cols[col] = strs[i][col]\n        return len(delete)",
        "solution_js": "/**\n * @param {string[]} strs\n * @return {number}\n */\nvar minDeletionSize = function(strs) {\n    let count = 0;\n    for(let i=0; i<strs[0].length; i++){\n        for(let j=0; j<strs.length-1; j++){\n            if(strs[j].charAt(i) > strs[j+1].charAt(i)){\n                count++;\n                break;\n            }\n        }\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int minDeletionSize(String[] strs) {\n        int count = 0;\n        for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column\n            for(int j = 0; j < strs.length-1; j++){\n                if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(i)){\n                    continue;\n                }else{\n                    count++;\n                    break;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minDeletionSize(vector<string>& strs) {\n        int col = strs[0].size();\n        int row = strs.size();\n        int count = 0;\n        for(int c = 0 ; c < col ; c++){\n            for(int r = 1 ; r < row ; r++){\n                if(strs[r][c] - strs[r - 1][c] < 0){\n                    count++;\n                    break;\n                }\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Shuffle the Array",
        "algo_input": "Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\n\nReturn the array in the form [x1,y1,x2,y2,...,xn,yn].\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,5,1,3,4,7], n = 3\nOutput: [2,3,5,4,1,7] \nExplanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,4,3,2,1], n = 4\nOutput: [1,4,2,3,3,2,4,1]\n\n\nExample 3:\n\nInput: nums = [1,1,2,2], n = 2\nOutput: [1,2,1,2]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 500\n\tnums.length == 2n\n\t1 &lt;= nums[i] &lt;= 10^3\n",
        "solution_py": "'''\nFirst of all, I'm making a few tuples  using zip function.\nThen extracting every created tuple. (for tup in zip())\nAfter that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup)\n'''\nclass Solution:\n    def shuffle(self, nums: List[int], n: int) -> List[int]:\n        return [number for tup in zip(nums[:n], nums[n:]) for number in tup]",
        "solution_js": "var shuffle = function(nums, n) {\n    while (n--) {\n        nums.splice(n + 1, 0, nums.pop());\n    }\n    return nums;\n};",
        "solution_java": "class Solution {\n    public int[] shuffle(int[] nums, int n)\n    {\n        int[] arr = new int[2*n];\n        int j = 0;\n        int k = n;\n        for(int i =0; i<2*n; i++)\n        {\n            if(i%2==0)\n            {\n                arr[i] = nums[j];\n                j++;\n            }\n            else\n            {\n                arr[i] = nums[k];\n                k++;\n            }\n        }\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> shuffle(vector<int>& nums, int n) {\n        vector<int> ans;\n        int size = nums.size();\n        int i = 0, j =0;\n        for(i=0,j=n; i<n && j<size; i++, j++){\n            ans.push_back(nums[i]);\n            ans.push_back(nums[j]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Players With Zero or One Losses",
        "algo_input": "You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.\n\nReturn a list answer of size 2 where:\n\n\n\tanswer[0] is a list of all players that have not lost any matches.\n\tanswer[1] is a list of all players that have lost exactly one match.\n\n\nThe values in the two lists should be returned in increasing order.\n\nNote:\n\n\n\tYou should only consider the players that have played at least one match.\n\tThe testcases will be generated such that no two matches will have the same outcome.\n\n\n&nbsp;\nExample 1:\n\nInput: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\nOutput: [[1,2,10],[4,5,7,8]]\nExplanation:\nPlayers 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].\n\n\nExample 2:\n\nInput: matches = [[2,3],[1,3],[5,4],[6,4]]\nOutput: [[1,2,5,6],[]]\nExplanation:\nPlayers 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= matches.length &lt;= 105\n\tmatches[i].length == 2\n\t1 &lt;= winneri, loseri &lt;= 105\n\twinneri != loseri\n\tAll matches[i] are unique.\n\n",
        "solution_py": "class Solution:\n    def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n        winners, losers, table = [], [], {}\n        for winner, loser in matches:\n            # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.\n            # map.get(key, 0) returns map[key] if key exists and 0 if it does not.\n            table[winner] = table.get(winner, 0) # Winner\n            table[loser] = table.get(loser, 0) + 1\n        for k, v in table.items(): # Player k with losses v\n            if v == 0:\n                winners.append(k) # If player k has no loss ie v == 0\n            if v == 1:\n                losers.append(k) # If player k has one loss ie v == 1\n        return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.",
        "solution_js": "/**\n * @param {number[][]} matches\n * @return {number[][]}\n */\nvar findWinners = function(matches) {\n    var looser = {};\n    var allPlayer={};\n    for(var i=0; i<matches.length; i++)\n        {\n            if(looser[matches[i][1]])\n                looser[matches[i][1]]++;\n            else\n                looser[matches[i][1]]=1\n\n            if(!allPlayer[matches[i][0]])\n                allPlayer[matches[i][0]]=1\n            if(!allPlayer[matches[i][1]])\n                allPlayer[matches[i][1]]=1\n        }\n    var first=[], second=[];\n    for(var key in allPlayer)\n        {\n            if(!looser[key])\n                first.push(key);\n            if(looser[key] == 1)\n                second.push(key);\n        }\n    return [first, second]\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> findWinners(int[][] matches) {\n        int[] won = new int[100001];\n        int[] loss = new int[100001];\n        \n        for(int[] match : matches) {\n            won[match[0]]++;\n            loss[match[1]]++;\n        }\n        \n        // System.out.print(Arrays.toString(won));\n        // System.out.print(Arrays.toString(loss));\n        \n        List<List<Integer>> ans  = new ArrayList<>();\n        \n        List<Integer> wonAllMatches = new ArrayList<>();\n        List<Integer> lostOneMatch = new ArrayList<>();\n        \n        for(int i = 0; i < won.length; i++) {\n            if(won[i] > 0 && loss[i] == 0) { //for checking players that have not lost any match.\n                wonAllMatches.add(i);\n            }\n            \n            if(loss[i] == 1) {\n                lostOneMatch.add(i); //for checking players that have lost exactly one match.\n            }\n        }\n        \n        ans.add(wonAllMatches);\n        ans.add(lostOneMatch);\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> findWinners(vector<vector<int>>& matches) {\n        unordered_map<int,int> umap;\n        vector<vector<int>> result(2);\n        for(int i=0;i<matches.size();i++)\n        {\n            umap[matches[i][1]]++;\n        }\n        for(auto i=umap.begin();i!=umap.end();i++)\n        {\n            if(i->second==1)\n            {\n                result[1].push_back(i->first);\n            }\n        }\n        for(int i=0;i<matches.size();i++)\n        {\n            if(umap[matches[i][0]]==0)\n            {\n                result[0].push_back(matches[i][0]);\n                umap[matches[i][0]]=1;\n            }\n        }\n\n        sort(result[0].begin(),result[0].end());\n\n        sort(result[1].begin(),result[1].end());\n\n        return result;\n    }\n};"
    },
    {
        "title": "Binary Tree Zigzag Level Order Traversal",
        "algo_input": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[20,9],[15,7]]\n\n\nExample 2:\n\nInput: root = [1]\nOutput: [[1]]\n\n\nExample 3:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 2000].\n\t-100 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution(object):\n    def zigzagLevelOrder(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: List[List[int]]\n        \"\"\"\n        if not root: return []\n        \n        ans = []\n        \n        node = root \n        \n        q = collections.deque([node])\n        \n        order = -1 \n        \n        while q:\n            order = -order\n            level = []\n            for _ in range(len(q)):\n                node = q.popleft()\n                \n                level.append(node.val)\n                \n                if node.left:\n                    q.append(node.left)\n                if node.right:\n                    q.append(node.right)\n                    \n            ans.append(level[::order])\n                \n        return ans",
        "solution_js": "var zigzagLevelOrder = function(root) {\n    let result = []\n    if(root == null) return result\n    \n    let queue = []\n    let leftToRight = true\n    \n    queue.push(root)\n    \n    while(queue.length != 0) {\n        let qSize = queue.length\n        let ans = []\n        \n        // Processing level\n        for(let i=0;i<qSize;i++) {\n            let front = queue.shift()\n            \n            let index = leftToRight ? i : qSize-i-1\n            ans[index] = front.val\n            \n            if(front.left) queue.push(front.left)\n            if(front.right) queue.push(front.right)\n        }\n        // changing order of operation\n        leftToRight = !leftToRight\n        \n        result.push(ans)\n    }\n    \n    return result\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n        Queue<TreeNode> q=new LinkedList<TreeNode>();\n        List<List<Integer>> res=new ArrayList<>();\n        if(root==null){\n            return res;\n        }\n        q.offer(root);\n        boolean flag=true;\n        while(!q.isEmpty()){\n            int size=q.size();\n            List<Integer> curr=new ArrayList<>();\n            for(int i=0;i<size;i++){\n                if(q.peek().left!=null){\n                    q.offer(q.peek().left);\n                }\n                if(q.peek().right!=null){\n                    q.offer(q.peek().right);\n                }\n                if(flag==true){\n                    curr.add(q.poll().val);\n                }else{\n                    curr.add(0,q.poll().val);\n                }\n            }\n            if(flag==true){\n                flag=false;\n            }else{\n                flag=true;\n            }\n            res.add(curr);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n    vector<vector<int>> ans;\n    if(!root) return ans;\n    vector<int> r;\n    queue<TreeNode*> q;\n    int count=1;\n    q.push(root);\n    q.push(NULL);\n    while(1){\n        if(q.front()==NULL){\n            q.pop();\n            if(count%2==0) reverse(r.begin(),r.end());\n            ans.push_back(r);\n            if (q.empty()) return ans;\n            q.push(NULL);\n            r.resize(0);\n            count++;\n            continue;\n        }\n        \n            r.push_back((q.front())->val);\n            if(q.front()->left)q.push((q.front())->left); \n            if(q.front()->right)q.push((q.front())->right);\n            \n            q.pop();\n    }\n    return ans;\n\n    }\n};"
    },
    {
        "title": "Minimum Number of Swaps to Make the Binary String Alternating",
        "algo_input": "Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.\n\nThe string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n\nAny two characters may be swapped, even if they are&nbsp;not adjacent.\n\n&nbsp;\nExample 1:\n\nInput: s = \"111000\"\nOutput: 1\nExplanation: Swap positions 1 and 4: \"111000\" -&gt; \"101010\"\nThe string is now alternating.\n\n\nExample 2:\n\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating, no swaps are needed.\n\n\nExample 3:\n\nInput: s = \"1110\"\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\ndef minSwaps(self, st: str) -> int:\n    \n    def swap(st,c):\n        n = len(st)\n        mis = 0\n        for i in range(n):\n            if i%2==0 and st[i]!=c:\n                mis+=1\n            if i%2==1 and st[i]==c:\n                mis+=1\n        return mis//2\n            \n    dic = Counter(st)\n    z = dic['0']\n    o = dic['1']\n    res=0\n    if abs(z-o)>1:\n        return -1\n    elif z>o:\n        res = swap(st,'0')\n    elif o>z:\n        res = swap(st,'1')\n    else:\n        res = min(swap(st,'0'),swap(st,'1'))\n    \n    return res",
        "solution_js": "var minSwaps = function(s) {\n    let ones = 0;\n    let zeroes = 0;\n    \n    for(let c of s) {\n        if(c === \"1\") ones++\n        else zeroes++\n    }\n    \n    if(Math.abs(ones - zeroes) > 1) return -1\n    \n    function count(i) {\n        let res = 0\n        for(let c of s) {\n            if(i !== c) res++;\n            if(i === \"1\") i = \"0\";\n            else i = \"1\";\n        }\n        \n        return res/2;\n    };\n    \n    if(ones > zeroes) return count(\"1\")\n    if(zeroes > ones) return count(\"0\")\n\n    return Math.min(count(\"1\"), count(\"0\"));\n};",
        "solution_java": "class Solution {\n    public int minSwaps(String s) {\n        int cntZero=0 , cntOne=0;\n        for(char ch:s.toCharArray()){\n            if(ch=='0') cntZero++;\n            else cntOne++;\n        }\n        \n        //Invalid\n        if(Math.abs(cntOne-cntZero)>1) return -1;\n        \n        \n        if(cntOne>cntZero){  //one must be at even posotion\n            return countSwaps(s,'1');    \n        }else if(cntOne<cntZero){\n            return countSwaps(s,'0'); //zero must be at even position\n        }\n        \n        return Math.min(countSwaps(s,'0'),countSwaps(s,'1'));    \n    }\n    \n    //wrong count \n    private int countSwaps(String s,char start){\n        int wrongPosition=0;\n        for(int i=0;i<s.length();i+=2){\n            if(s.charAt(i)!=start) wrongPosition++;\n        }\n        return wrongPosition;\n    }\n} ",
        "solution_c": "class Solution {\n    \n    int minFillPos(string& s, char ch, int current = 0) {\n        int count = 0;\n        for(int i=0; i<s.size(); i+=2) {\n            if(s[i] != ch) count++;\n        }\n        return count;\n    }\n    \npublic:\n    int minSwaps(string s) {\n        int oneCount = count(s.begin(), s.end(), '1');\n        int zeroCount = count(s.begin(), s.end(), '0');\n        if(abs(oneCount-zeroCount) > 1) return -1;\n        if(oneCount > zeroCount) return minFillPos(s,'1');\n        if(zeroCount > oneCount) return minFillPos(s,'0');\n        return min(minFillPos(s,'0'), minFillPos(s,'1'));\n    }\n};"
    },
    {
        "title": "Corporate Flight Bookings",
        "algo_input": "There are n flights that are labeled from 1 to n.\n\nYou are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.\n\nReturn an array answer of length n, where answer[i] is the total number of seats reserved for flight i.\n\n&nbsp;\nExample 1:\n\nInput: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput: [10,55,45,25,25]\nExplanation:\nFlight labels:        1   2   3   4   5\nBooking 1 reserved:  10  10\nBooking 2 reserved:      20  20\nBooking 3 reserved:      25  25  25  25\nTotal seats:         10  55  45  25  25\nHence, answer = [10,55,45,25,25]\n\n\nExample 2:\n\nInput: bookings = [[1,2,10],[2,2,15]], n = 2\nOutput: [10,25]\nExplanation:\nFlight labels:        1   2\nBooking 1 reserved:  10  10\nBooking 2 reserved:      15\nTotal seats:         10  25\nHence, answer = [10,25]\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 104\n\t1 &lt;= bookings.length &lt;= 2 * 104\n\tbookings[i].length == 3\n\t1 &lt;= firsti &lt;= lasti &lt;= n\n\t1 &lt;= seatsi &lt;= 104\n\n",
        "solution_py": "class Solution:\n\tdef corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n\t\tflights = [0]*n\n\t\tfor start,end,seats in bookings:\n\t\t\tflights[start-1] += seats\n\t\t\tif end < n: flights[end] -= seats\n\t\tfor i in range(n-1):\n\t\t\tflights[i+1] += flights[i]\n\t\treturn flights",
        "solution_js": "var corpFlightBookings = function(bookings, n) {\n    \n    // +1 as dummy guard on the tail, which allow us not to check right boundary every time\n    let unitStep = Array(n+1).fill(0);\n    \n    for(const [first, last, seatVector ] of bookings ){\n        \n        // -1 because booking flight is 1-indexed, given by description\n        let [left, right] = [first-1, last-1];\n        \n        unitStep[ left ] += seatVector;\n        unitStep[ right+1 ] -= seatVector;\n    }\n    \n    // Reconstruct booking as drawing combination of retangle signal, built with unit step impulse\n    for( let i = 1; i < unitStep.length ; i++ ){\n        unitStep[ i ] += unitStep[ i-1 ];\n    }\n    \n    \n    // last one is dummy guard on the tail, no need to return\n    return unitStep.slice(0, n);\n};",
        "solution_java": "class Solution {\n    public int[] corpFlightBookings(int[][] bookings, int n) {\n        // nums all equals to zero\n        int[] nums = new int[n];\n        // construct the diffs\n        Difference df = new Difference(nums);\n\n        for (int[] booking : bookings) {\n            // pay attention to the index\n            int i = booking[0] - 1;\n            int j = booking[1] - 1;\n            int val = booking[2];\n            // increase nums[i..j] by val\n            df.increment(i, j, val);\n        }\n        // return the final array\n        return df.result();\n    }\n\n    class Difference {\n        // diff array\n        private int[] diff;\n\n        public Difference(int[] nums) {\n            assert nums.length > 0;\n            diff = new int[nums.length];\n            // construct the diffs\n            diff[0] = nums[0];\n            for (int i = 1; i < nums.length; i++) {\n                diff[i] = nums[i] - nums[i - 1];\n            }\n        }\n\n        // increase nums[i..j] by val\n        public void increment(int i, int j, int val) {\n            diff[i] += val;\n            if (j + 1 < diff.length) {\n                diff[j + 1] -= val;\n            }\n        }\n\n        public int[] result() {\n            int[] res = new int[diff.length];\n            // contract the diff array based on the result\n            res[0] = diff[0];\n            for (int i = 1; i < diff.length; i++) {\n                res[i] = res[i - 1] + diff[i];\n            }\n            return res;\n        }\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {\n        vector<int> arr(n);\n        for (const auto& b : bookings) {\n            int start = b[0] - 1, end = b[1], seats = b[2];\n            arr[start] += seats;\n            if (end < n) {\n                arr[end] -= seats;\n            }\n        }\n        partial_sum(begin(arr), end(arr), begin(arr));\n        return arr;\n    }\n};"
    },
    {
        "title": "Max Chunks To Make Sorted",
        "algo_input": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].\n\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\n\nReturn the largest number of chunks we can make to sort the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [4,3,2,1,0]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\n\n\nExample 2:\n\nInput: arr = [1,0,2,3,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == arr.length\n\t1 &lt;= n &lt;= 10\n\t0 &lt;= arr[i] &lt; n\n\tAll the elements of arr are unique.\n\n",
        "solution_py": "class Solution(object):\n    def maxChunksToSorted(self, arr):\n        n= len(arr)\n\n        count=0\n        currentmax= -2**63\n        for i in range(0,n):\n            currentmax=max(currentmax, arr[i])\n            if (currentmax==i):\n                count+=1\n        return count\n        \n        \n    ",
        "solution_js": "var maxChunksToSorted = function(arr) {\n    let count = 0, cumSum = 0;\n    arr.forEach((el, index) => {\n        cumSum += el-index;\n        if (cumSum === 0) count++;\n    });\n    return count;\n};",
        "solution_java": "class Solution {\n    public int maxChunksToSorted(int[] arr) {\n\n        int max=0, count=0;\n        for(int i=0; i<arr.length; i++){\n            max = Math.max(arr[i],max);\n            if(i==max) count++;\n        }return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxChunksToSorted(vector<int>& arr) {\n        // using chaining technique\n        int maxi=INT_MIN;\n        int ans =0;\n\n        for(int i=0;i<size(arr);i++)\n\n        {\n            maxi = max(maxi,arr[i]);\n\n            if(maxi==i)\n            {\n                //.. found partition\n                ans++;\n\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Ways to Split a String",
        "algo_input": "Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.\n\nReturn the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n\"1|010|1\"\n\"1|01|01\"\n\"10|10|1\"\n\"10|1|01\"\n\n\nExample 2:\n\nInput: s = \"1001\"\nOutput: 0\n\n\nExample 3:\n\nInput: s = \"0000\"\nOutput: 3\nExplanation: There are three ways to split s in 3 parts.\n\"0|0|00\"\n\"0|00|0\"\n\"00|0|0\"\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def numWays(self, s: str) -> int:\n        ones = 0\n\n        # Count number of Ones\n        for char in s:\n            if char == \"1\":\n                ones += 1\n\n        # Can't be grouped equally if the ones are not divisible by 3\n        if ones > 0 and ones % 3 != 0:\n            return 0\n\n        # Ways of selecting two dividers from n - 1 dividers \n        if ones == 0:\n            n = len(s)\n\t\t\t# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }\n            return (((n - 1) * (n - 2)) // 2) % ((10 ** 9) + 7)\n\n        # Number of ones in each group\n        ones_interval = ones // 3\n\n        # Number of zeroes which lie on the borders\n        left, right = 0, 0\n\n        # Iterator\n        i = 0\n        temp = 0\n\n        # Finding the zeroes on the left and right border\n        while i < len(s):\n            temp += int(s[i]) & 1\n            if temp == ones_interval:\n                if s[i] == '0':\n                    left += 1\n            if temp == 2 * ones_interval:\n                if s[i] == '0':\n                    right += 1\n            i += 1\n        \n        # The result is the product of number of (left + 1) and (right + 1)\n        # Because let's assume it as we only want to fill up the middle group\n        # The solution would be if we have zero then there might be a zero in the middle\n        # Or there might not be the zero, so this might case is added and then\n\t\t# the events are independent so product of both the events\n        return ((left + 1) * (right + 1)) % ((10 ** 9) + 7)",
        "solution_js": "var numWays = function(s) {\n    let one = 0;\n    let list = [];\n    for(let i = 0; i < s.length; i++){\n        if(s[i]===\"1\") one++, list.push(i);\n    }\n    if(one%3!==0) return 0;\n    if(one===0) return ((s.length-1)*(s.length-2)/2) % 1000000007;\n    one/=3;\n    return ((list[one]-list[one-1])*(list[2*one]-list[2*one-1])) % 1000000007;\n};",
        "solution_java": "class Solution {\n    public int numWays(String s) {\n        long n=s.length();\n        long one=0;//to count number of ones\n        long mod=1_000_000_007;\n        char[] c=s.toCharArray();\n        for(int i=0;i<c.length;i++)\n        {\n            if(c[i]=='1')\n                one++;\n        }\n        \n             //there will be 3 cases\n            // 1.no ones present in the string\n            // 2.number of ones present in the string isnt divisible by 3(since we need to cut 3 parts)\n            // 3.number of ones divisible by 3\n        \n        if(one==0)//case 1\n        {\n            return (int)((((n-1)*(n-2))/2)%mod);\n        }\n        if(one%3!=0)//case 2,which means we cant split ones equally\n            return 0;\n        //case 3\n        long ones=one/3;//number of ones that should be present in each part\n        one=0;\n        long part1=0;//number of ways in which part1 and part2 can be split\n        long part2=0;\n        for(int i=0;i<c.length;i++)\n        {\n            if(c[i]=='1')\n                one++;\n            if(one==ones)\n                part1++;\n            if(one==2*ones)\n                part2++;\n        }\n        \n        return (int)((part1*part2)%mod);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int MOD = 1e9 + 7 ;\n    int numWays(string s) {\n        int ones = count(begin(s),end(s),'1') , n = s.size() ;\n        if(ones % 3) return 0 ;\n        if(!ones) return (((n-1) * 1LL * (n-2) * 1LL) / 2) % MOD ; /// n- 1 C 2\n        \n        int left = 0 , right = 0 , count = 0 , i = 0 ;\n        while(count <= ones / 3){\n            count += s[i++] == '1' ;\n            if(count == ones/3) ++left ;\n        }\n        i = n - 1 , count = 0 ;\n        while(count <= ones/3){\n            count += s[i--] == '1' ;\n            if(count == ones/3) ++ right ;\n        }\n        \n        return (left * 1LL * right * 1LL) % MOD ;\n    }\n};"
    },
    {
        "title": "Hand of Straights",
        "algo_input": "Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.\n\nGiven an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput: true\nExplanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]\n\n\nExample 2:\n\nInput: hand = [1,2,3,4,5], groupSize = 4\nOutput: false\nExplanation: Alice's hand can not be rearranged into groups of 4.\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= hand.length &lt;= 104\n\t0 &lt;= hand[i] &lt;= 109\n\t1 &lt;= groupSize &lt;= hand.length\n\n\n&nbsp;\nNote: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/\n",
        "solution_py": "#####################################################################################################################\n# Problem: Hand of Straights\n# Solution : Hash Table, Min Heap\n# Time Complexity : O(n logn)\n# Space Complexity : O(n)\n#####################################################################################################################\n\nclass Solution:\n    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n        if len(hand) % groupSize:\n            return False\n\n        freq = collections.defaultdict(int)\n\n        for num in hand:\n            freq[num] += 1\n\n        min_heap = list(freq.keys())\n        heapq.heapify(min_heap)\n\n        while min_heap:\n            smallest = min_heap[0]\n            for num in range(smallest, smallest + groupSize):\n                if num not in freq:\n                    return False\n                freq[num] -= 1\n\n                if freq[num] == 0:\n                    if num != min_heap[0]:\n                        return False\n                    heapq.heappop(min_heap)\n        return True",
        "solution_js": "var isNStraightHand = function(hand, groupSize) {\n    if(hand.length%groupSize!==0) return false;\n\t\n    const map = new Map();\n    hand.forEach(h=>{\n        map.set(h,map.get(h)+1||1);\n    });\n    \n\t// sort based on the key in asc order\n    const sortedMap = new Map([...map.entries()].sort((a,b)=>a[0]-b[0]));\n    \n    while(sortedMap.size){\n\t// getting the first key\n        const firstKey = sortedMap.keys().next().value; \n        for(let i=firstKey;i<firstKey+groupSize;++i){\n            if(!sortedMap.has(i)){\n                return false\n            }\n            const freq = sortedMap.get(i);\n            if(freq===1){\n                sortedMap.delete(i)\n            }else{\n                sortedMap.set(i,sortedMap.get(i)-1);\n            }\n        }\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isNStraightHand(int[] hand, int groupSize) {\n        if(hand.length % groupSize != 0)\n            return false;\n\n        Map<Integer, Integer> map = new HashMap<>();\n        PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n\n        for(int card : hand){\n            if(map.containsKey(card))\n                map.put(card, map.get(card) + 1);\n            else {\n                map.put(card, 1);\n                minHeap.add(card);\n            }\n        }\n\n        while(!minHeap.isEmpty()){\n            int min = minHeap.peek();\n            for(int i=min; i < min + groupSize; i++){\n                if(!map.containsKey(i) || map.get(i) == 0)\n                    return false;\n                map.put(i, map.get(i) - 1);\n                if(map.get(i) == 0){\n                    if(minHeap.peek() != i)\n                        return false;\n                    minHeap.poll();\n                }\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isNStraightHand(vector<int>& hand, int groupSize) {\n        int n = hand.size();\n        if(n%groupSize != 0)   // We can't rearrange elements of size groupsize so return false\n            return false;\n        map<int,int>mp;\n        for(auto it : hand)\n            mp[it]++;\n        while(mp.size() > 0){\n            int start = mp.begin()->first;   // Taking the topmost element of map\n\n            for(int i=0; i<groupSize; i++){\n                if(mp.find(start) != mp.end()){\n                    mp[start]--;\n                    if(mp[start] == 0)\n                        mp.erase(start);\n                    start++;                // Increasing for finding next consecutive element of start. \n                }\n                else\n                    return false;\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Matchsticks to Square",
        "algo_input": "You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.\n\nReturn true if you can make this square and false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: matchsticks = [1,1,2,2,2]\nOutput: true\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n\n\nExample 2:\n\nInput: matchsticks = [3,3,3,3,4]\nOutput: false\nExplanation: You cannot find a way to form a square with all the matchsticks.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= matchsticks.length &lt;= 15\n\t1 &lt;= matchsticks[i] &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def makesquare(self, matchsticks: List[int]) -> bool:\n        target,m=divmod(sum(matchsticks),4)\n        if m:return False\n        targetLst=[0]*4\n        length=len(matchsticks)\n        matchsticks.sort(reverse=True)\n        def bt(i):\n            if i==length:\n                return len(set(targetLst))==1\n            for j in range(4):\n                if matchsticks[i]+targetLst[j]>target:\n                    continue\n                targetLst[j]+=matchsticks[i]\n                if bt(i+1):\n                    return True\n                targetLst[j]-=matchsticks[i]\n                if not targetLst[j]:break\n            return False\n        return matchsticks[0]<=target and bt(0)",
        "solution_js": "var makesquare = function(matchsticks) {\n    const perimeter = matchsticks.reduce((a, b) => a + b, 0);\n    if(perimeter % 4 != 0 || matchsticks.length < 4) return false;\n    \n    const sideLen = perimeter / 4;\n    // find a way to divide the array in 4 group of sum side length\n    const sides = new Array(4).fill(0);\n    const len = matchsticks.length;\n    matchsticks.sort((a, b) => b - a);\n    \n    const solve = (x = 0) => {\n        if(x == len) {\n            return sides.every(side => side == sideLen);\n        }\n        \n        for(let i = 0; i < 4; i++) {\n            if(sides[i] + matchsticks[x] > sideLen) {\n                continue;\n            }\n            sides[i] += matchsticks[x];\n            if(solve(x + 1)) return true;\n            sides[i] -= matchsticks[x];\n        }\n        return false;\n    }\n    return solve();\n};",
        "solution_java": "/*\n    Time complexity: O(2 ^ n)\n    Space complexity: O(n)\n\n    Inutition:\n    ---------\n    Same as \"Partition to K Equal Sum Subsets\"\n*/\n\nclass Solution {\n    public boolean backtrack(int[] nums, int idx, int k, int subsetSum, int target, boolean[] vis) {\n        // base case\n        if (k == 0)\n            return true;\n        if (target == subsetSum) {\n            // if one of the side is found then keep finding the other k - 1 sides starting again from the beginning\n            return backtrack(nums, 0, k - 1, 0, target, vis);\n        }\n\n        // hypothesis\n        for(int i = idx; i < nums.length; i++) {\n            // if number is already visited or sum if out of range then skip\n            if (vis[i] || subsetSum + nums[i] > target)\n                continue;\n\n            // Pruning\n            // if the last position (i - 1) is not visited, that means the current combination didn't work,\n            // and since this position (i) has the same value, it won't work for it as well. Thus, skip it.\n            if (i - 1 >= 0 && nums[i] == nums[i - 1] && !vis[i - 1])\n                continue;\n\n            vis[i] = true;\n            if (backtrack(nums, i + 1, k, subsetSum + nums[i], target, vis))\n                return true;\n\n            // backtrack\n            vis[i] = false;\n        }\n\n        return false;\n    }\n\n    private void reverse(int[] arr) {\n        for (int i = 0, j = arr.length - 1; i < j; i++, j--) {\n            int tmp = arr[i];\n            arr[i] = arr[j];\n            arr[j] = tmp;\n        }\n    }\n\n    public boolean makesquare(int[] matchsticks) {\n        int sum = 0;\n        int k = 4;\n        int n = matchsticks.length;\n        // sort the array in descending order to make the recursion hit the base case quicker\n        Arrays.sort(matchsticks);\n        reverse(matchsticks);\n\n        for(int match: matchsticks)\n            sum += match;\n\n        if (sum % k != 0)\n            return false;\n\n        int target = sum / k;\n        boolean[] vis = new boolean[n];\n\n        return backtrack(matchsticks, 0, k, 0, target, vis);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool makesquare(vector<int>& matchsticks) {\n        int goal = 0, totalSum = 0;\n        for (int i : matchsticks) {\n            totalSum += i;\n        }\n        goal = totalSum / 4;\n        sort(matchsticks.begin(), matchsticks.end(), [](auto left, auto right) {\n            return left > right;\n        });\n        int b = 0;\n        if (totalSum % 4) {\n            return false;\n        }\n        return backtrack(0, b, 0, goal, 4, matchsticks);\n    }\n    \n    bool backtrack(int start, int &b, int sum, int &goal, int groups, vector<int>& matchsticks) {\n        if (sum == goal) {\n            //set sum to 0, groups--\n            return backtrack(0, b, 0, goal, groups-1, matchsticks);\n        }\n        if (groups == 1) {\n            return true;\n        }\n        for (int i = start; i < matchsticks.size(); i++) {\n            if ((i > 0) && (!(b & (1 << (i - 1)))) && (matchsticks[i] == matchsticks[i-1])) {\n                continue;\n            }\n            //if element not used and element value doesnt go over group sum\n            if (((b & (1 << i)) == 0) && (sum + matchsticks[i] <= goal)) {\n                //set element to used, recursion\n                b ^= (1 << i); \n                if (backtrack(i + 1, b, sum + matchsticks[i], goal, groups, matchsticks)) {\n                    return true;\n                }\n                //if here, received a false, set element to unused again\n                b ^= (1 << i);\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Construct Binary Tree from Inorder and Postorder Traversal",
        "algo_input": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.\n\n&nbsp;\nExample 1:\n\nInput: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput: [3,9,20,null,null,15,7]\n\n\nExample 2:\n\nInput: inorder = [-1], postorder = [-1]\nOutput: [-1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= inorder.length &lt;= 3000\n\tpostorder.length == inorder.length\n\t-3000 &lt;= inorder[i], postorder[i] &lt;= 3000\n\tinorder and postorder consist of unique values.\n\tEach value of postorder also appears in inorder.\n\tinorder is guaranteed to be the inorder traversal of the tree.\n\tpostorder is guaranteed to be the postorder traversal of the tree.\n\n",
        "solution_py": "import bisect\n# Definition for a binary tree node.\n# class TreeNode(object):\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution(object):\n\n    def buildTree(self, inorder, postorder):\n        \"\"\"\n        7\n         2\n       -8 \n        :type inorder: List[int]\n        :type postorder: List[int]\n        :rtype: TreeNode\n        ([-4,-10,3,-1], [7]) ((11,-8,2), [7])\n        \"\"\"\n        currentSplits = [(inorder, [], [])]\n        nodeDirectory = {}\n        finalSplits = []\n        for nodeVal in reversed(postorder):\n            nodeDirectory[nodeVal] = TreeNode(nodeVal)\n            for splits, nodes, directions in reversed(currentSplits):\n                removing = None\n                if nodeVal in splits:\n                    removing = (splits, nodes, directions)\n                    left = splits[:splits.index(nodeVal)]\n                    right = splits[splits.index(nodeVal)+1:]\n                    currentSplits.append((left, nodes+[nodeVal], directions + ['left']))\n                    if len(left) <= 1:\n                        finalSplits.append((left, nodes+[nodeVal], directions + ['left']))\n                    currentSplits.append((right, nodes+[nodeVal], directions + ['right']))\n                    if len(right) <= 1:\n                        finalSplits.append((right, nodes+[nodeVal], directions + ['right']))\n                    break\n                if removing:\n                    currentSplits.remove(removing)\n        finalSplits = [splits for splits in finalSplits if splits[0]]\n\n        while finalSplits:\n            nodeVal, nodes, directions = finalSplits.pop()\n            bottomNode = nodeDirectory[nodeVal[0]] if nodeVal else None\n            while nodes:\n                attachingNode = nodeDirectory[nodes.pop()]\n                attachingDir = directions.pop()\n                if attachingDir == 'left':\n                    attachingNode.left = bottomNode\n                else:\n                    attachingNode.right = bottomNode\n                bottomNode = attachingNode\n        return nodeDirectory[postorder[-1]]",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number[]} inorder\n * @param {number[]} postorder\n * @return {TreeNode}\n */\nvar buildTree = function(inorder, postorder) {\n    let postIndex = postorder.length - 1\n\n    const dfs = (left, right) => {\n        if (left > right) return null\n\n        const val = postorder[postIndex--]\n        const mid = inorder.findIndex(e => e === val)\n        const root = new TreeNode(val)\n\n        root.right = dfs(mid + 1, right)\n        root.left = dfs(left, mid - 1)\n\n        return root\n    }\n\n    return dfs(0, inorder.length - 1)\n};",
        "solution_java": "class Solution {\n    int[] io; int[] po;\n    int n;   // nth post order node \n    public TreeNode buildTree(int[] inorder, int[] postorder) {\n        this.n = inorder.length-1; this.io = inorder; this.po = postorder; \n        return buildTree(0, n); \n    }\n    public TreeNode buildTree(int low, int high) {\n        if(n < 0 || low > high) return null;\n        int currNode = po[n--];\n        int idxInInorder = low;\n        TreeNode root = new TreeNode(currNode); \n        if(low == high) return root;   // no more nodes\n        \n        while(io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder\n        root.right = buildTree(idxInInorder+1, high);\n        root.left = buildTree(low, idxInInorder-1);\n        return root;    \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* buildTree(vector<int>& ino, vector<int>& post) {\n    int i1 = post.size()-1;\n        return solve(i1,ino,post,0,ino.size()-1);\n    }\n    TreeNode* solve(int &i,vector<int> &in,vector<int> &post,int l,int r){\n        if(l>r)return NULL;\n        int x = r;\n        while(post[i] != in[x]){\n            x--;\n        }\n        i--;\n        // cout<<in[x]<<\" \";\n        TreeNode* root = new TreeNode(in[x]);\n        root->right = solve(i,in,post,x+1,r);\n        root->left = solve(i,in,post,l,x-1);\n        return root;\n    }\n};"
    },
    {
        "title": "Remove Sub-Folders from the Filesystem",
        "algo_input": "Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.\n\nIf a folder[i] is located within another folder[j], it is called a sub-folder of it.\n\nThe format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.\n\n\n\tFor example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not.\n\n\n&nbsp;\nExample 1:\n\nInput: folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput: [\"/a\",\"/c/d\",\"/c/f\"]\nExplanation: Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.\n\n\nExample 2:\n\nInput: folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput: [\"/a\"]\nExplanation: Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".\n\n\nExample 3:\n\nInput: folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput: [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= folder.length &lt;= 4 * 104\n\t2 &lt;= folder[i].length &lt;= 100\n\tfolder[i] contains only lowercase letters and '/'.\n\tfolder[i] always starts with the character '/'.\n\tEach folder name is unique.\n\n",
        "solution_py": "# a TrieNode class for creating new node\nclass TrieNode():\n    def __init__(self):\n        self.children = {}\n        self.main = False\n        \n# the main class\nclass Solution(object):\n    def removeSubfolders(self, folder):     \n        node = TrieNode()\n        res = []\n        # sort the list to prevent adding the subfolder to the Trie first\n        folder.sort()\n        for dir in folder:\n            name = dir.split(\"/\")\n            if self.addTrie(name,node):\n                res.append(dir)\n        return res\n\n    # usign the same addTrie template and modify the else part\n    def addTrie(self,name,node):    \n        trie = node\n        for c in name:\n            if c not in trie.children:\n                trie.children[c] = TrieNode()\n            # if char is in trie,\n            else:\n                # check if it's the last sub folder. \n                if trie.children[c].main == True:\n                    return False\n            trie = trie.children[c]\n        trie.main = True\n        return True",
        "solution_js": "var removeSubfolders = function(folder) {\n    folder = folder.sort()\n    const result = [];\n    for(let i in folder){\n        const f = folder[i];\n        if(result.length == 0 || !f.startsWith(result[result.length -1] + \"/\"))\n            result.push(f);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    TrieNode root;\n    public List<String> removeSubfolders(String[] folder) {\n        List<String> res = new ArrayList<>();\n        Arrays.sort(folder, (a, b) -> (a.length() - b.length()));\n        root = new TrieNode();\n        for (String f : folder) {\n            if (insert(f)) {\n                res.add(f);\n            }\n        }\n        return res;\n    }\n    \n    private boolean insert(String folder) {\n        TrieNode node = root;\n        char[] chs = folder.toCharArray();\n        for (int i = 0; i < chs.length; i++) {\n            char ch = chs[i];\n            node.children.putIfAbsent(ch, new TrieNode());\n            node = node.children.get(ch);\n            if (node.isFolder && (i+1 < chs.length && chs[i+1] == '/')) {\n                return false;\n            }\n        }\n        node.isFolder = true;\n        return true;\n    }\n}\n\nclass TrieNode {\n    Map<Character, TrieNode> children = new HashMap<>();\n    boolean isFolder;\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int check(string &s,unordered_map<string,int>&mp)\n    {\n        string temp;\n        temp.push_back(s[0]); //for maintaining prefix string \n        \n        for(int i=1;i<s.size();i++)\n        {\n            if(s[i]=='/')\n            {\n                if(mp.count(temp)) //for checking prefix exist in map\n                    return true;        \n                temp+=s[i];\n            }\n            else temp+=s[i];\n        }\n        mp[s]=1;    //if string doesnot exist put it in map\n        return false;\n    }\n    vector<string> removeSubfolders(vector<string>& folder) {\n      unordered_map<string,int>mp;\n      sort(folder.begin(),folder.end());\n     vector<string>ans;\n        \n        for(auto it:folder)\n        {\n            if(!check(it,mp))\n                ans.push_back(it);\n        }\n        \n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Longest Palindrome",
        "algo_input": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome&nbsp;that can be built with those letters.\n\nLetters are case sensitive, for example,&nbsp;\"Aa\" is not considered a palindrome here.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abccccdd\"\nOutput: 7\nExplanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7.\n\n\nExample 2:\n\nInput: s = \"a\"\nOutput: 1\nExplanation: The longest palindrome that can be built is \"a\", whose length is 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 2000\n\ts consists of lowercase and/or uppercase English&nbsp;letters only.\n\n",
        "solution_py": "class Solution:\n    def longestPalindrome(self, s: str) -> int:\n        letters = {} \n        for letter in s: #count each letter and update letters dict\n            if letter in letters:\n                letters[letter] += 1\n            else:\n                letters[letter] = 1\n        \n        \n        plus1 = 0 # if there is a letter with count of odd ans must +=1 \n        ans = 0\n        for n in letters.values():\n            if n == 1: #1 can only appear in the middle of our word\n                plus1 = 1\n            elif n%2 == 0:\n                ans += n\n            else:\n                ans += n - 1\n                plus1 = 1\n                \n        return ans + plus1",
        "solution_js": "var longestPalindrome = function(s) {\n    const hashMap = {};\n    let ouput = 0;\n    let hashOdd = false;\n\n    for (let i = 0; i < s.length; i++) {\n        if (!hashMap[s[i]]) {\n            hashMap[s[i]] = 0;\n        }\n        hashMap[s[i]] += 1;\n    }\n\n    Object.values(hashMap)?.forEach(character => {\n        ouput += character%2 ? character - 1 : character;\n        if (character%2 && !hashOdd) {\n            hashOdd = true;\n        }\n    });\n\n    return ouput + (hashOdd ? 1 : 0);\n};",
        "solution_java": "class Solution {\n    public int longestPalindrome(String s) {\n        HashMap<Character, Integer> map = new HashMap<>();\n\n        int evenNo = 0;\n        int oddNo = 0;\n\n        for ( int i = 0; i < s.length(); i++) {\n            char c = s.charAt(i);\n            if (map.containsKey(c)) {\n                map.put(c, map.get(c) + 1);\n            } else {\n                map.put(c, 1);\n            }\n\n        }\n        for (Map.Entry e : map.entrySet()) {\n            int n = (int) e.getValue();\n            if (n % 2 != 0) {\n                oddNo += n;\n            }\n            evenNo += (n / 2) * 2;\n        }\n\n        if (oddNo > 0) {\n            evenNo += 1;\n        }\n        return evenNo;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestPalindrome(string s) {\n        map<char,int> mp;\n        for(int i=0;i<s.length();i++){\n            mp[s[i]]++;\n        }\n        int ans = 0;\n        int odd = 0;\n        for(auto i:mp){\n            if(i.second % 2 == 1){\n                odd = 1;\n            }\n            ans = ans + (i.second/2)*2;\n        }\n        return ans+odd;\n    }\n};"
    },
    {
        "title": "Product of Array Except Self",
        "algo_input": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].\n\nThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n\nYou must write an algorithm that runs in&nbsp;O(n)&nbsp;time and without using the division operation.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,3,4]\nOutput: [24,12,8,6]\nExample 2:\nInput: nums = [-1,1,0,-3,3]\nOutput: [0,0,9,0,0]\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t-30 &lt;= nums[i] &lt;= 30\n\tThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n\n\n&nbsp;\nFollow up:&nbsp;Can you solve the problem in O(1)&nbsp;extra&nbsp;space complexity? (The output array does not count as extra space for space complexity analysis.)\n",
        "solution_py": "class Solution:\n    def productExceptSelf(self, nums: List[int]) -> List[int]:\n        pre = [1]* (len(nums)+1)\n        back = [1]*(len(nums)+1)\n\n        for i in range(len(nums)):\n            pre[i+1] = pre[i]*nums[i]\n\n        for i in range(len(nums)-1,-1,-1):\n            back[i-1] = back[i]*nums[i]\n        for i in range(len(pre)-1):\n            nums[i]=pre[i]*back[i]\n\n        return nums",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar productExceptSelf = function(nums) {\n  let result = [];\n  let len = nums.length;\n\n  let prefix = 1;\n  for (let i = 0; i < len; i++) {\n    result[i] = prefix;\n    prefix *= nums[i];\n  }\n  let postfix = 1;\n  for (let i = len - 1; i >= 0; i--) {\n    result[i] *= postfix;\n    postfix *= nums[i];\n  }\n  return result;\n};",
        "solution_java": "class Solution {\n    public int[] productExceptSelf(int[] nums) {\n        int n = nums.length;\n        int pre[] = new int[n];\n        int suff[] = new int[n];\n        pre[0] = 1;\n        suff[n - 1] = 1;\n        \n        for(int i = 1; i < n; i++) {\n            pre[i] = pre[i - 1] * nums[i - 1];\n        }\n        for(int i = n - 2; i >= 0; i--) {\n            suff[i] = suff[i + 1] * nums[i + 1];\n        }\n        \n        int ans[] = new int[n];\n        for(int i = 0; i < n; i++) {\n            ans[i] = pre[i] * suff[i];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> productExceptSelf(vector<int>& nums) {\n        int zero=0,product=1;\n        for(auto i:nums){\n            if(i==0)\n                zero++;\n            else product*=i;\n        }\n        for(int i=0;i<nums.size();i++){\n            if(nums[i] == 0 && zero>1){\n                nums[i]=0;\n            }\n            else if(nums[i] == 0){\n                nums[i]=product;\n            }\n            else if(zero > 0){\n                nums[i]=0;\n            }\n            else nums[i]=product/nums[i];\n        }\n        return nums;\n    }\n};"
    },
    {
        "title": "Maximum Equal Frequency",
        "algo_input": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\n\nIf after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,2,1,1,5,3,3,5]\nOutput: 7\nExplanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n\n\nExample 2:\n\nInput: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput: 13\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maxEqualFreq(self, nums: List[int]) -> int:\n        ans = 0\n        n = len(nums)\n        countToFreq = defaultdict(int)\n        # key = count value = Freq ex 2 occured 3 times  in nums so 2 : 3\n        freqToCount = defaultdict(int)\n        # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3\n        \n        for i,val in enumerate(nums):\n            \n            x = countToFreq[val] + 1\n            freqToCount[x - 1] -= 1\n            if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)\n            freqToCount[x] += 1\n            countToFreq[val] = x\n            \n            # if a single item is repeated for i + 1 times like [1,1,1]\n            if countToFreq[val] == i + 1 :ans = i + 1\n            \n            # if all items are having same frequency like [2,2,1,1,3,3]\n            elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1\n            \n            # if all items have same frequency except one having 1 freq like [2,2,3,3,1]\n            elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1\n            \n            # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]\n            elif len(freqToCount) == 2:\n                keys,values = [],[]\n                for j in freqToCount:keys.append(j) , values.append(freqToCount[j])\n                if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1\n        return ans",
        "solution_js": "// *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value\n\nvar maxEqualFreq = function(nums) {\n  // create cache to count the frequency of each number\n  const numCnt = {};\n  \n  // create cache to count the number of 'number of frequencies'\n  // e.g. [1,2,3,2,4,4,3,1,5]\n  //        {  1: 1           1 number appeared with a frequency of 1\n  //           2: 3   }      3 numbers appeared with a frequency of 2\n  const cntFreq = {};\n  \n  // holds the maximum frequency a number has appeared\n  let maxFreq = 0;\n  \n  // holds solution\n  let result = 0;\n  \n  // iterate through numbers\n  for (let i = 0; i < nums.length; i++) {\n      // get current number;\n      const num = nums[i];\n\t  \n\t  // subtract one from the current frequency of the current number\n      cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] - 1 : -1;\n\t  \n\t  // increase the count of the current number\n      numCnt[num] = numCnt[num] ? numCnt[num] + 1 : 1;\n\t  \n\t  // add one to the current frequency of the current number\n      cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] + 1 : 1;\n\t  \n\t  // if the current frequency is more than the max frequency update the max frequency\n      if (maxFreq < numCnt[num]) maxFreq = numCnt[num];\n\t  \n\t  // if max frequency is 1 or\n\t  // if the max frequency multiplied by the number of values with that frequency equals the current index or\n\t  // if the result of the 1 less than the max frequency equals to the current index\n\t  // update result\n      if (maxFreq === 1 || maxFreq * cntFreq[maxFreq] === i || (maxFreq - 1) * (cntFreq[maxFreq - 1] + 1) === i) {\n          result = i + 1;\n      }\n  }\n  return result;\n};",
        "solution_java": "import java.util.TreeMap;\nimport java.util.NavigableMap;\nclass Solution {\n    public int maxEqualFreq(int[] nums) {\n        Map<Integer, Integer> F          = new HashMap<>(); //Frequencies\n        NavigableMap<Integer, Integer> V = new TreeMap<>(); //Values for frequencies\n        int max = 0;\n        for (int i = 0; i < nums.length; i++) {\n            increaseCount(F, nums[i]);\n            int frequency = F.get(nums[i]);\n            decreaseCount(V, frequency - 1);\n            increaseCount(V, frequency);\n            if (isPossibleToRemove(V)) max = i;\n        }\n        return max + 1;\n    }\n    \n    public boolean isPossibleToRemove(NavigableMap<Integer, Integer> frequenciesMap) {\n        if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies\n        Map.Entry<Integer, Integer> first = frequenciesMap.firstEntry();\n        Map.Entry<Integer, Integer> last  = frequenciesMap.lastEntry();\n        if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d]\n        int firstReduced = removeElement(first);\n        int lastReduced  = removeElement(last);\n        if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false;\n        return true;\n    }\n    \n    //Try to remove element which contributes to this frequency:\n    //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1\n    //if there are more than 1 occurences of such frequency, removing 1 element will not change it\n    public int removeElement(Map.Entry<Integer, Integer> frequencyValue) {\n        if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1;\n        return frequencyValue.getKey();\n    }\n    \n    public void decreaseCount(Map<Integer, Integer> map, int element) {\n        if (!map.containsKey(element)) return;\n        map.put(element, map.get(element) - 1);\n        if (map.get(element) == 0) map.remove(element);\n    }\n    \n    public void increaseCount(Map<Integer, Integer> map, int element) {\n        if (!map.containsKey(element)) map.put(element, 0);\n        map.put(element, map.get(element) + 1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxEqualFreq(vector<int>& nums) {\n        int n=nums.size();\n        unordered_map<int,int> mp1,mp2; //one to store the frequency of each number , and one which will store the frequency of the frequency\n        int ans=0;\n        for(int i=0;i<n;i++)\n        {\n            int c=nums[i];\n            mp1[c]++;\n            mp2[mp1[c]]++;\n            if(i!=n-1 && mp2[mp1[c]]*mp1[c]==i+1)\n            //when curernt length is equal to the total same frequency of numbers then we need one more\n            //number which may be anything so doesn't matter .\n            //so we just traverse till n-2 and that's it.\n\n                ans=i+2;\n            if(mp2[mp1[c]]*mp1[c]==i)\n            //when current length is equal to the total same frequency of numbers plus one extra no.\n            //( so here taken ==i (i+1-1)) which can be 1. same as any number present 2. different number ..\n            //but doesn't matter and our condition just satisfies ... so just take the current length .\n\n                ans=i+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Design Front Middle Back Queue",
        "algo_input": "Design a queue that supports push and pop operations in the front, middle, and back.\n\nImplement the FrontMiddleBack class:\n\n\n\tFrontMiddleBack() Initializes the queue.\n\tvoid pushFront(int val) Adds val to the front of the queue.\n\tvoid pushMiddle(int val) Adds val to the middle of the queue.\n\tvoid pushBack(int val) Adds val to the back of the queue.\n\tint popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1.\n\tint popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1.\n\tint popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1.\n\n\nNotice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:\n\n\n\tPushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5].\n\tPopping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].\n\n\n&nbsp;\nExample 1:\n\nInput:\n[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]\nOutput:\n[null, null, null, null, null, 1, 3, 4, 2, -1]\n\nExplanation:\nFrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1);   // [1]\nq.pushBack(2);    // [1, 2]\nq.pushMiddle(3);  // [1, 3, 2]\nq.pushMiddle(4);  // [1, 4, 3, 2]\nq.popFront();     // return 1 -&gt; [4, 3, 2]\nq.popMiddle();    // return 3 -&gt; [4, 2]\nq.popMiddle();    // return 4 -&gt; [2]\nq.popBack();      // return 2 -&gt; []\nq.popFront();     // return -1 -&gt; [] (The queue is empty)\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= val &lt;= 109\n\tAt most&nbsp;1000&nbsp;calls will be made to&nbsp;pushFront,&nbsp;pushMiddle,&nbsp;pushBack, popFront, popMiddle, and popBack.\n\n",
        "solution_py": "class FrontMiddleBackQueue:\n\n    def __init__(self):\n        self.front = deque()\n        self.back = deque()\n\n    def _correct_size(self):\n        while len(self.back) > len(self.front):\n            self.front.append(self.back.popleft())\n\n        while len(self.front) > len(self.back) + 1:\n            self.back.appendleft(self.front.pop())\n\n    def pushFront(self, val: int) -> None:\n        self.front.appendleft(val)\n        self._correct_size()\n\n    def pushMiddle(self, val: int) -> None:\n        if len(self.front) > len(self.back):\n            self.back.appendleft(self.front.pop())\n        self.front.append(val)\n        self._correct_size()\n\n    def pushBack(self, val: int) -> None:\n        self.back.append(val)\n        self._correct_size()\n\n    def popFront(self) -> int:\n        front = self.front if self.front else self.back\n        ret = front.popleft() if front else -1\n        self._correct_size()\n        return ret\n\n    def popMiddle(self) -> int:\n        ret = self.front.pop() if self.front else -1\n        self._correct_size()\n        return ret\n\n    def popBack(self) -> int:\n        back = self.back if self.back else self.front\n        ret = back.pop() if back else -1\n        self._correct_size()\n        return ret",
        "solution_js": "// T.C: \n// O(1) for init and methods other than pushMiddle(), popMiddle()\n// O(N) for pushMiddle(), popMiddle()\n// S.C: O(N) for storage \n\n// Doubly linked list node\nfunction ListNode(val, prev, next) {\n    this.val = val || 0;\n    this.prev = prev || null;\n    this.next = next || null;\n}\n\nvar FrontMiddleBackQueue = function() {\n    this.head = null;\n    this.tail = null;\n    this.len = 0;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushFront = function(val) {\n    if (this.len === 0) {\n        this.head = new ListNode(val);\n        this.tail = this.head;\n        this.len += 1;\n        return;\n    }\n    \n    let newNode = new ListNode(val);\n    newNode.next = this.head;\n    this.head.prev = newNode;\n    this.head = newNode; // the new node becomes the new head\n    this.len += 1;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushMiddle = function(val) {\n    if (this.len <= 1) {\n        this.pushFront(val);\n        return;\n    }\n    let cur = this.head;\n    for (let i = 1; i < Math.floor(this.len / 2); i++) { // we go to previous node of median\n        cur = cur.next;    \n    }\n    let newNode = new ListNode(val);\n    let next = cur.next;\n    cur.next = newNode;\n    newNode.prev = cur;\n    newNode.next = next;\n    if (next) next.prev = newNode;\n    this.len += 1;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushBack = function(val) {\n    if (this.len === 0) {\n        this.pushFront(val);\n        return;\n    }\n    \n    let newNode = new ListNode(val);\n    this.tail.next = newNode;\n    newNode.prev = this.tail;\n    this.tail = newNode; // end node becomes the new tail\n    this.len += 1;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popFront = function() {\n    if (this.len === 0) {\n        return -1;\n    }\n    let front = this.head;\n    let next = front.next;\n    if (next) next.prev = null;\n    this.head = next;\n    this.len -= 1;\n    return front.val;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popMiddle = function() {\n    if (this.len <= 2) {\n        return this.popFront();\n    }\n    let cur = this.head;\n    for (let i = 1; i < Math.ceil(this.len / 2); i++) { // we go to median node\n        cur = cur.next;    \n    }\n\n    let prev = cur.prev;\n    let next = cur.next;\n    cur.prev = null;\n    cur.next = null;\n    if (prev) prev.next = next;    \n    if (next) next.prev = prev;\n    this.len -= 1;\n    return cur.val;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popBack = function() {\n    if (this.len <= 1) {\n        return this.popFront();\n    }\n    let end = this.tail;\n    let prev = end.prev;\n    end.prev = null;\n    prev.next = null;\n    this.tail = prev;\n    this.len -= 1;\n    return end.val;\n};\n\n/** \n * Your FrontMiddleBackQueue object will be instantiated and called as such:\n * var obj = new FrontMiddleBackQueue()\n * obj.pushFront(val)\n * obj.pushMiddle(val)\n * obj.pushBack(val)\n * var param_4 = obj.popFront()\n * var param_5 = obj.popMiddle()\n * var param_6 = obj.popBack()\n */",
        "solution_java": "class FrontMiddleBackQueue {\n\n    Deque<Integer> dq1, dq2;\n    public FrontMiddleBackQueue() {        \n        dq1 = new ArrayDeque<Integer>();\n        dq2 = new ArrayDeque<Integer>();\n    }\n    \n    public void pushFront(int val) {\n        dq1.addFirst(val);\n    }    \n    \n    public void pushBack(int val) {\n        dq2.addLast(val);\n    }   \n    \n    public void pushMiddle(int val) {\n        while(dq1.size() + 1 < dq2.size())\n            dq1.addLast(dq2.removeFirst());       \n        while(dq1.size() > dq2.size())\n            dq2.addFirst(dq1.removeLast());        \n        dq1.addLast(val);        \n    }     \n    \n    public int popFront() {\n        if(!dq1.isEmpty())\n            return dq1.removeFirst();\n        if(!dq2.isEmpty())\n            return dq2.removeFirst();\n        return -1;    \n    }  \n    \n    public int popMiddle() {\n        if(dq1.isEmpty() && dq2.isEmpty())\n            return -1;        \n        while(dq1.size() < dq2.size())\n            dq1.addLast(dq2.removeFirst());     \n        while(dq1.size() > dq2.size() + 1)\n            dq2.addFirst(dq1.removeLast());\n        return !dq1.isEmpty() ? dq1.removeLast() : dq2.removeFirst();\n    }    \n    \n    public int popBack() {\n        if(!dq2.isEmpty())\n            return dq2.removeLast();\n        if(!dq1.isEmpty())\n            return dq1.removeLast();\n        return -1;            \n    }    \n}",
        "solution_c": "class FrontMiddleBackQueue {\npublic:\n    deque<int> list1;\n    deque<int> list2;\n    int size;\n    \n    FrontMiddleBackQueue() {\n        size = 0;        \n    }\n    \n    void pushFront(int val) {\n        \n        if(list1.size()- list2.size() == 0)\n        {\n            list1.push_front(val);\n        }\n        else\n        {\n            list1.push_front(val);\n            list2.push_front(list1.back());\n            list1.pop_back();\n        }\n        \n        size++;\n    }\n    \n    void pushMiddle(int val) {\n        \n        if(list1.size() - list2.size() == 0)\n        {\n            list1.push_back(val);\n        }\n        else\n        {\n            list2.push_front(list1.back());\n            list1.pop_back();\n            list1.push_back(val);\n        }\n        \n        size++;\n    }\n    \n    void pushBack(int val) {\n            \n        if(list1.size() - list2.size() == 0)\n        {\n            list2.push_back(val);\n            list1.push_back(list2.front());\n            list2.pop_front();\n        }\n        else\n        {\n            list2.push_back(val);\n        }\n        \n        size++;\n    }\n    \n    int popFront() {\n\n        if(size ==0) return -1;\n        \n        int val = list1.front();\n        list1.pop_front();\n        \n        if(list1.size()<list2.size())\n        {\n            list1.push_back(list2.front());\n            list2.pop_front();\n        }\n        \n        size--;\n        return val;\n    }\n    \n    int popMiddle() {\n        \n        if(size ==0) return -1;\n        \n        int val = list1.back();\n        list1.pop_back();\n\n        if(list1.size() < list2.size())\n        {\n            list1.push_back(list2.front());\n            list2.pop_front();\n        }\n        \n        size--;\n        return val;\n        \n    }\n    \n    int popBack() {\n        \n        if(size ==0) return -1;\n        \n        int val;\n        if(size==1)\n        {\n            val = list1.front();\n            list1.pop_front();\n        }\n        else\n        {\n            val = list2.back();\n            list2.pop_back();\n\n            int s1 = list1.size();\n            int s2 = list2.size();\n\n            if(list1.size() - list2.size() > 1)\n            {\n                list2.push_front(list1.back());\n                list1.pop_back();\n            }                   \n        }\n        \n        size--;\n        return val;       \n    }\n};"
    },
    {
        "title": "Maximize Sum Of Array After K Negations",
        "algo_input": "Given an integer array nums and an integer k, modify the array in the following way:\n\n\n\tchoose an index i and replace nums[i] with -nums[i].\n\n\nYou should apply this process exactly k times. You may choose the same index i multiple times.\n\nReturn the largest possible sum of the array after modifying it in this way.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,2,3], k = 1\nOutput: 5\nExplanation: Choose index 1 and nums becomes [4,-2,3].\n\n\nExample 2:\n\nInput: nums = [3,-1,0,2], k = 3\nOutput: 6\nExplanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\n\n\nExample 3:\n\nInput: nums = [2,-3,-1,5,-4], k = 2\nOutput: 13\nExplanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-100 &lt;= nums[i] &lt;= 100\n\t1 &lt;= k &lt;= 104\n\n",
        "solution_py": "from heapq import heapify, heapreplace\n\nclass Solution:\n    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:\n        heapify(nums)\n        while k and nums[0] < 0:\n            heapreplace(nums, -nums[0])\n            k -= 1\n        if k % 2:\n            heapreplace(nums, -nums[0])\n        return sum(nums)",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar largestSumAfterKNegations = function(nums, k) {\n    let negations = k\n    let index = 0\n    const sortedNums = [...nums]\n\n    // Sort in increasing order\n    sortedNums.sort((a, b) => a - b)\n\n    // loop into the sorted array using the\n    // number of negations\n    while (negations > 0) {\n        negations--\n\n        const currentNumber = -sortedNums[index]\n        const nextNumber = sortedNums[index + 1]\n\n        sortedNums[index] = currentNumber\n\n        // if the number is 0, undefined or\n        // the current number is less than the\n        // next number (meaning it will be\n        // less the amount if it's a negative\n        // number) just use the same number\n        // again to flip.\n        if (\n                currentNumber === 0 ||\n                nextNumber === undefined ||\n                currentNumber < nextNumber\n        ) continue\n\n        index++\n    }\n\n    return sortedNums.reduce((sum, num) => sum + num, 0)\n};",
        "solution_java": "class Solution {\n    public int largestSumAfterKNegations(int[] nums, int k) {\n\n        PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n        for(int val : nums) minHeap.add(val);\n\n        while(k > 0){\n\n            int curr = minHeap.poll();\n            minHeap.add(-curr);\n            k--;\n        }\n\n        int sum = 0;\n        while(!minHeap.isEmpty()){\n            sum += minHeap.poll();\n        }\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largestSumAfterKNegations(vector<int>& A, int k) {\n       priority_queue<int, vector<int>, greater<int>> pq(A.begin(), A.end());\n        while(k--){\n            int t=pq.top();pq.pop();\n            pq.push(t*-1);\n        }\n    \n        int n=0;\n       while(!pq.empty()){\n           int t=pq.top();pq.pop();\n           n+=t;\n       }\n        return n;\n    }\n};"
    },
    {
        "title": "Minimum Difference Between Highest and Lowest of K Scores",
        "algo_input": "You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.\n\nPick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.\n\nReturn the minimum possible difference.\n\n&nbsp;\nExample 1:\n\nInput: nums = [90], k = 1\nOutput: 0\nExplanation: There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.\n\n\nExample 2:\n\nInput: nums = [9,4,1,7], k = 2\nOutput: 2\nExplanation: There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minimumDifference(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        cur = float('inf')\n        for i in range(len(nums)-k+1):\n            cur = min(cur, nums[i+k-1]-nums[i])",
        "solution_js": "```/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minimumDifference = function(nums, k) {\n    nums.sort((a,b)=>a-b)\n    let min=nums[0],max=nums[k-1],diff=max-min\n    for(let i=k;i<nums.length;i++){\n        diff=Math.min(diff,nums[i]-nums[i-k+1])\n    }\n    return diff\n};``",
        "solution_java": "class Solution {\n    public int minimumDifference(int[] nums, int k) {\n        if(k == 1)return 0;\n        int i = 0,j = k-1,res = Integer.MAX_VALUE;\n\n        Arrays.sort(nums);\n        while(j < nums.length){\n            res = Math.min(res,nums[j] - nums[i]);\n            j++;\n            i++;\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumDifference(vector<int>& nums, int k) {\n        sort(nums.begin(), nums.end());\n        int res = nums[k-1] - nums[0];\n        for (int i = k; i < nums.size(); i++) res = min(res, nums[i] - nums[i-k+1]);\n        return res;\n    }\n};"
    },
    {
        "title": "Number Complement",
        "algo_input": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\n\n\n\tFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n\n\nGiven an integer num, return its complement.\n\n&nbsp;\nExample 1:\n\nInput: num = 5\nOutput: 2\nExplanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\n\n\nExample 2:\n\nInput: num = 1\nOutput: 0\nExplanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt; 231\n\n\n&nbsp;\nNote: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/\n",
        "solution_py": "class Solution:\n    def findComplement(self, num: int) -> int:\n        i = 0\n        while(2**i <= num):\n            i += 1\n        return (2**i - num - 1)",
        "solution_js": "var findComplement = function(num) {\n    return num ^ parseInt(Array(num.toString(2).length).fill(\"1\").join(\"\"), 2)\n}",
        "solution_java": "class Solution {\n    public int findComplement(int num) {\n       int x=0;int sum=0;\n        while(num>0){\n           int i = num%2;\n            if(i==0){\n               sum+=Math.pow(2,x++);\n            }\n            else{\n                x++;\n            }\n            num/=2;\n        }\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findComplement(int num) {\n        long n=1;\n        while(n-1<num)\n        {\n            n<<=1;\n        }\n        n--;\n        return n-num;\n    }\n};"
    },
    {
        "title": "Minimum Subsequence in Non-Increasing Order",
        "algo_input": "Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non&nbsp;included elements in such subsequence.&nbsp;\n\nIf there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.&nbsp;\n\nNote that the solution with the given constraints is guaranteed to be&nbsp;unique. Also return the answer sorted in non-increasing order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,3,10,9,8]\nOutput: [10,9] \nExplanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.&nbsp;\n\n\nExample 2:\n\nInput: nums = [4,4,7,6,7]\nOutput: [7,7,6] \nExplanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.  \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 500\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minSubsequence(self, nums: List[int]) -> List[int]:\n        nums.sort(reverse=True)\n        val = sum(nums)\n        temp = []\n        for i in range(len(nums)):\n            temp.append(nums[i])\n            if sum(temp)>val-sum(temp):\n                return temp\n            ",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar minSubsequence = function(nums) {\n  const target = nums.reduce((a, b) => a + b) / 2;\n  nums.sort((a, b) => b - a);\n  let i = 0, sum = 0;\n  while (sum <= target) {\n    sum += nums[i++];\n  }\n  return nums.slice(0, i);\n};",
        "solution_java": "class Solution {\n    public List<Integer> minSubsequence(int[] nums) {\n        int total = 0;\n        for(int i=0;i<nums.length;i++){\n            total += nums[i];\n        }\n        Arrays.sort(nums);\n        int sum = 0;\n        ArrayList<Integer> ans = new ArrayList<>();\n        for(int i=nums.length-1;i>=0;i--){\n            ans.add(nums[i]);\n            sum += nums[i];\n            if(sum>total-sum){\n                return ans;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> minSubsequence(vector<int>& nums) {\n        \n        sort(nums.begin(), nums.end(),greater<int>());\n        vector<int> res;\n        int sum = 0;\n        for(int i: nums)\n            sum += i;\n        \n        int x=0;\n        for(int i=0; i<nums.size(); i++)\n        {\n            x += nums[i];\n            sum -= nums[i];\n            res.push_back(nums[i]);\n            if(x>sum)\n                break;\n            \n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Filling Bookcase Shelves",
        "algo_input": "You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.\n\nWe want to place these books in order onto bookcase shelves that have a total width shelfWidth.\n\nWe choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.\n\nNote that at each step of the above process, the order of the books we place is the same order as the given sequence of books.\n\n\n\tFor example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.\n\n\nReturn the minimum possible height that the total bookshelf can be after placing shelves in this manner.\n\n&nbsp;\nExample 1:\n\nInput: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4\nOutput: 6\nExplanation:\nThe sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.\n\n\nExample 2:\n\nInput: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= books.length &lt;= 1000\n\t1 &lt;= thicknessi &lt;= shelfWidth &lt;= 1000\n\t1 &lt;= heighti &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def minHeightShelves(self, books, shelf_width: int) -> int:\n        n, dp = len(books), [float('inf')] * (len(books)+1)\n        dp[0] = 0\n\n        for i in range(1, n+1):\n            max_width, max_height, j = shelf_width, 0, i - 1\n            \n            while j >= 0 and max_width - books[j][0] >= 0:\n                max_width -= books[j][0]\n                max_height = max(max_height, books[j][1])\n                dp[i] = max_height\n                j -= 1\n\n            if j >= 0 and max_width - books[j][0] < 0:\n                j = i - 1\n                dp[i] = float('inf')\n                width, height = 0, 0\n                while j >= 0 and width + books[j][0] <= shelf_width:\n                    width = width + books[j][0]\n                    height = max(books[j][1], height)\n                    dp[i] = min(dp[i], height + dp[j])\n                    j -= 1\n\n        return dp[n]",
        "solution_js": "var minHeightShelves = function(books, shelfWidth) {\n    let booksArr = []\n\n    for(let i = 0; i < books.length; i++) {\n        let remainingWidth = shelfWidth - books[i][0]\n        let bookHeight = books[i][1]\n\n        let maxHeight = bookHeight\n\n        let prevSum = booksArr[i - 1] !== undefined ? booksArr[i - 1] : 0\n        let minSumHeight = bookHeight + prevSum\n\n        for(let x = i - 1; x >= 0 ; x--) {\n\n            let prevBookWidth = books[x][0]\n            let prevBookHeight = books[x][1]\n            if(remainingWidth - prevBookWidth < 0) break\n            remainingWidth -= prevBookWidth\n\n            prevSum = booksArr[x - 1] !== undefined ? booksArr[x - 1] : 0\n\n            maxHeight = Math.max(maxHeight, prevBookHeight)\n\n            minSumHeight = Math.min(prevSum + maxHeight, minSumHeight)\n        }\n        booksArr[i] = minSumHeight\n    }\n\n    return booksArr[books.length - 1]\n};",
        "solution_java": "class Solution {\n    int[][] books;\n    int shefWidth;\n\n    Map<String, Integer> memo = new HashMap();\n\n    public int findMinHeight(int curr, int maxHeight, int wRem) {\n        String key = curr  + \":\" + wRem ;\n        \n        if(memo.containsKey(key)) return memo.get(key);\n\n\n        if(curr == books.length ) return maxHeight;\n        int[] currBook = books[curr];\n\n        memo.put( key, currBook[0] <= wRem ? Math.min(   maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0]) , // new shelf\n                  findMinHeight(curr + 1, Math.max(maxHeight, currBook[1]),wRem - currBook[0] )) // same shelf\n                : maxHeight + findMinHeight(curr + 1,  currBook[1], shefWidth - currBook[0])\n        ); // new shelf\n\n        return memo.get(key);\n    }\n\n\n    public int minHeightShelves(int[][] books, int shelfWidth) {\n        this.books = books;\n        this.shefWidth = shelfWidth;\n        return findMinHeight(0, 0,  shelfWidth);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minHeightShelves(vector<vector<int>>& books, int shelfWidth) {\n        int n=books.size();\n        vector<vector<int>> cost(n+1,vector<int>(n+1));\n        for(int i=1;i<=n;i++)\n        {\n            int height=books[i-1][1];\n            int width=books[i-1][0];\n            cost[i][i]=height;\n            for(int j=i+1;j<=n;j++)\n            {\n                height=max(height,books[j-1][1]);\n                width+=books[j-1][0];\n                if(width<=shelfWidth) cost[i][j]=height;\n                else cost[i][j]=-1;\n            }\n        }\n        vector<int> ans(n+1);\n        ans[0]=0;\n        for(int i=1;i<=n;i++)\n        {\n            ans[i]=INT_MAX;\n            for(int j=1;j<=i;j++)\n            {\n                if(cost[j][i]==-1) continue;\n                if(ans[j-1]!=INT_MAX) ans[i]=min(ans[i],ans[j-1]+cost[j][i]);\n            }\n        }\n        return ans[n];\n    }\n};"
    },
    {
        "title": "First Bad Version",
        "algo_input": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.\n\nSuppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.\n\nYou are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, bad = 4\nOutput: 4\nExplanation:\ncall isBadVersion(3) -&gt; false\ncall isBadVersion(5)&nbsp;-&gt; true\ncall isBadVersion(4)&nbsp;-&gt; true\nThen 4 is the first bad version.\n\n\nExample 2:\n\nInput: n = 1, bad = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= bad &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def firstBadVersion(self, n: int) -> int:\n        fast, slow = int(n/2), n\n        diff = abs(fast-slow)\n        while isBadVersion(fast) == isBadVersion(slow) or diff > 1:\n            fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast\n            diff = abs(fast-slow)\n        return fast if isBadVersion(fast) else slow",
        "solution_js": "/**\n * Definition for isBadVersion()\n *\n * @param {integer} version number\n * @return {boolean} whether the version is bad\n * isBadVersion = function(version) {\n * ...\n * };\n */\n\n/**\n * @param {function} isBadVersion()\n * @return {function}\n */\nvar solution = function(isBadVersion) {\n    /**\n     * @param {integer} n Total versions\n     * @return {integer} The first bad version\n     */\n    return function(n) {\n        let ceiling = n\n        let floor = 1\n        let firstBadVersion = -1\n\n        while (floor <= ceiling) {\n            const middle = Math.floor((ceiling + floor) / 2)\n\n            if (isBadVersion(middle)) {\n\n                firstBadVersion = middle\n                ceiling = middle - 1\n            } else {\n                floor = middle + 1\n            }\n        }\n\n        return firstBadVersion\n    };\n};",
        "solution_java": "/* The isBadVersion API is defined in the parent class VersionControl.\n      boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n    public int firstBadVersion(int n) {\n        int s = 0; int e = n;\n        \n        while(s < e) {\n            int mid = s +(e-s)/2;\n            \n            if(isBadVersion(mid)){\n                e = mid ;\n            } else {\n                s = mid +1;\n            }\n        }\n        return e ;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int firstBadVersion(int n) {\n\t//Using Binary Search\n        int lo = 1, hi = n, mid;\n        while (lo < hi) {\n            mid = lo + (hi - lo) / 2;\n            if (isBadVersion(mid)) hi = mid;\n            else lo = mid+1;\n        }\n        return lo;\n    }\n};"
    },
    {
        "title": "Minimum Limit of Balls in a Bag",
        "algo_input": "You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.\n\nYou can perform the following operation at most maxOperations times:\n\n\n\tTake any bag of balls and divide it into two new bags with a positive number of balls.\n\n\t\n\t\tFor example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.\n\t\n\t\n\n\nYour penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.\n\nReturn the minimum possible penalty&nbsp;after performing the operations.\n\n&nbsp;\nExample 1:\n\nInput: nums = [9], maxOperations = 2\nOutput: 3\nExplanation: \n- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -&gt; [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -&gt; [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n\n\nExample 2:\n\nInput: nums = [2,4,8,2], maxOperations = 4\nOutput: 2\nExplanation:\n- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -&gt; [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -&gt; [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -&gt; [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -&gt; [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.\n\n\nExample 3:\n\nInput: nums = [7,17], maxOperations = 2\nOutput: 7\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= maxOperations, nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n        l, r = 1, max(nums)\n        while l < r:\n            mid = (l + r) // 2\n            if sum([(n - 1) // mid for n in nums]) > maxOperations: \n                l = mid + 1\n            else:\n                r = mid\n        return l",
        "solution_js": "var minimumSize = function(nums, maxOperations) {\n  let i = 1\n  let j = Math.max(...nums)\n\n  while (i <= j) {\n    let mid = Math.floor((j-i)/2 + i)\n    let count = 0\n    nums.forEach(n => count += Math.floor((n-1)/mid))\n\n    if (count <= maxOperations) {\n      j = mid - 1\n    } else {\n      i = mid + 1\n    }\n  }\n  return i\n};",
        "solution_java": "class Solution {\n    public int minimumSize(int[] nums, int maxOperations) {\n\t//initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at the price of time consumption.\n\t//The answer should be the minimized max value.\n        int min = 0;\n        int max = 1000000000;\n\t\t//Compared with min<max or min <= max, min + 1 < max will avoid infinite loops e.g. when min = 2, max = 3\n        while (min +1< max) {\n            int mid = (max - min)/2 + min;\n\t\t\t//count indicates the operation times with atmost mid balls in bag.\n            int count = 0;\n            for (int a: nums) {\n\t\t\t//this is the same as Math. ceil(a/mid) - 1=> math.ceil(a/mid) gives the number of divided bags, we subtract the number by 1 to get the subdivision operation times.\n                count+=(a-1)/mid;\n            }\n\t\t\t//if count < maxOperations, max WOULD be further minimized and set to mid; \n\t\t\t//if count = maxOperations, max still COULD be further minimized and set to mid. \n\t\t\t//so we combine < and = cases together in one if condition\n            if (count <= maxOperations) {\n\t\t\t//max = mid - 1 will not work in this case becasue mid could be the correct answer. \n\t\t\t//To not miss the correct answer we set a relatively \"loose\" boundary for max and min.\n                max = mid;\n            } else{\n                min = mid;\n            }\n        }\n\t\t//Now we find the minimized max value\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPossible(vector<int>&nums,int mid_penalty,int maxOperations)\n    {\n        int operations=0;\n\n        for(int i=0;i<nums.size();i++)\n        {\n            operations+=(nums[i]/mid_penalty); //Operations Nedded to divide that element.\n            if(nums[i]%mid_penalty==0) //if it is completely divisible means less 1 less is needed for that nums.\n                operations--;\n        }\n\n        return operations<=maxOperations?1:0; //If operations are less than maxOperations it is one of our ans.\n    }\n    int minimumSize(vector<int>& nums, int maxOperations) {\n        int low_penalty=1,high_penalty=*max_element(nums.begin(),nums.end());\n        int ans=high_penalty;\n        while(low_penalty<=high_penalty)\n        {\n            int mid_penalty=low_penalty+(high_penalty-low_penalty)/2;\n            if(mid_penalty==0) //To avoid divison by zero.\n                break;\n            if(isPossible(nums,mid_penalty,maxOperations))\n            {\n                ans=mid_penalty;\n                high_penalty=mid_penalty-1;\n            }\n            else\n                low_penalty=mid_penalty+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Count Servers that Communicate",
        "algo_input": "You are given a map of a server center, represented as a m * n integer matrix&nbsp;grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers&nbsp;that communicate with any other server.\n\n&nbsp;\nExample 1:\n\n\n\nInput: grid = [[1,0],[0,1]]\nOutput: 0\nExplanation:&nbsp;No servers can communicate with others.\n\nExample 2:\n\n\n\nInput: grid = [[1,0],[1,1]]\nOutput: 3\nExplanation:&nbsp;All three servers can communicate with at least one other server.\n\n\nExample 3:\n\n\n\nInput: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput: 4\nExplanation:&nbsp;The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m &lt;= 250\n\t1 &lt;= n &lt;= 250\n\tgrid[i][j] == 0 or 1\n\n",
        "solution_py": "class Solution:\n    def countServers(self, grid: List[List[int]]) -> int:\n        def helper(row,col,count):\n            for c in range(len(grid[0])):\n                if c == col:\n                    continue\n                if grid[row][c] == 1:\n                    count += 1\n                    return count\n            for r in range(len(grid)):\n                if r == row:\n                    continue\n                if grid[r][col] == 1:\n                    count += 1\n                    return count\n            return count\n        count = 0\n        for row in range(len(grid)):\n            for col in range(len(grid[0])):\n                if grid[row][col] == 1:\n                    count = helper(row,col,count)\n        return count",
        "solution_js": "var countServers = function(grid) {\n    const m = grid.length;\n    const n = grid[0].length;\n    \n    const lastRows = [];\n    const lastCols = [];\n    \n    const set = new Set();\n    \n    for (let i = 0; i < m; i++) {\n        for (let j = 0; j < n; j++) {\n            if (grid[i][j] === 1) {                \n                const currIdx = (i * n) + j;\n               \n                const rowNeiIdx = lastRows[i];\n                \n                if (rowNeiIdx != null) {\n                    set.add(currIdx).add(rowNeiIdx);\n                }\n                \n                const colNeiIdx = lastCols[j];\n                \n                if (colNeiIdx != null) {\n                    set.add(currIdx).add(colNeiIdx);\n                }\n                \n                lastRows[i] = currIdx;\n                lastCols[j] = currIdx;\n            }\n        }\n    }\n    \n    return set.size; \n};",
        "solution_java": "class Solution {\n    int []parent;\n    int []rank;\n    public int countServers(int[][] grid) {\n        parent=new int[grid.length*grid[0].length];\n        rank=new int[grid.length*grid[0].length];\n        for(int i=0;i<parent.length;i++){\n            parent[i]=i;\n            rank[i]=0;\n        }\n        for(int i=0;i<grid.length;i++){\n            for(int j=0;j<grid[0].length;j++){\n                if(grid[i][j]==1){\n                    check(i,j,grid);\n                }\n            }\n        }\n        int count=0;\n        for(int i=0;i<parent.length;i++){\n            if(parent[i]!=i||rank[i]>0){\n              count++;\n            }\n        }\n        return count;\n    }\n    public void check(int sr,int sc,int [][]grid){\n       int mbox=sr*grid[0].length+sc;\n        for(int i=sr;i<grid.length;i++){\n            if(grid[i][sc]==1){\n                int cbox=i*grid[0].length+sc;\n                int xl=find(mbox);\n                int yl=find(cbox);\n                if(xl!=yl){\n                    union(xl,yl);\n                }\n            }\n        }\n        for(int j=sc;j<grid[0].length;j++){\n            if(grid[sr][j]==1){\n                int cbox=sr*grid[0].length+j;\n                int xl=find(mbox);\n                int yl=find(cbox);\n                if(xl!=yl){\n                    union(xl,yl);\n                }\n            }\n        }\n    }\n    int find(int x){\n        if(parent[x]==x){\n            return x;\n        }else{\n            parent[x]=find(parent[x]);\n            return parent[x];\n        }\n    }\n    void union(int x,int y){\n        if(rank[x]>rank[y]){\n            parent[y]=x;\n        }else if(rank[y]>rank[x]){\n            parent[x]=y;\n        }else{\n            parent[x]=y;\n            rank[y]++;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countServers(vector<vector<int>>& grid) {\n        int n=grid.size(),m=grid[0].size();\n        vector<vector<bool>>visited(n,vector<bool>(m,false));\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<m;j++)\n            {\n                if(grid[i][j] && !visited[i][j])\n                {\n                    bool flag=false;\n                    for(int x=0;x<n;x++)\n                    {\n                        if(x!=i && grid[x][j] && !visited[x][j])\n                            visited[x][j]=true,flag=true;\n                        if(!flag && x!=i && visited[x][j])\n                            flag=true;\n                    }\n                    for(int x=0;x<m;x++)\n                    {\n                        if(x!=j && grid[i][x] && !visited[i][x])\n                            visited[i][x]=true,flag=true;\n                        if(!flag && x!=j && visited[i][x])\n                            flag=true;\n                    }\n                    if(flag)\n                        visited[i][j]=true;\n                }\n            }\n        }\n        int ans=0;\n        for(int i=0;i<n;i++)\n            for(int j=0;j<m;j++)\n                if(visited[i][j])\n                    ans++;\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Design Add and Search Words Data Structure",
        "algo_input": "Design a data structure that supports adding new words and finding if a string matches any previously added string.\n\nImplement the WordDictionary class:\n\n\n\tWordDictionary()&nbsp;Initializes the object.\n\tvoid addWord(word) Adds word to the data structure, it can be matched later.\n\tbool search(word)&nbsp;Returns true if there is any string in the data structure that matches word&nbsp;or false otherwise. word may contain dots '.' where dots can be matched with any letter.\n\n\n&nbsp;\nExample:\n\nInput\n[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]\nOutput\n[null,null,null,null,false,true,true,true]\n\nExplanation\nWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 25\n\tword in addWord consists of lowercase English letters.\n\tword in search consist of '.' or lowercase English letters.\n\tThere will be at most 3 dots in word for search queries.\n\tAt most 104 calls will be made to addWord and search.\n\n",
        "solution_py": "class TrieNode:\n    \n    def __init__(self, val):\n        self.val = val\n        self.children = {}\n        self.isEnd = False\n\n\nclass WordDictionary:\n\n    def __init__(self):\n        self.root = TrieNode(\"*\")\n        \n    def addWord(self, word: str) -> None:\n        \n        curr = self.root\n        \n        for c in word:\n            \n            if c not in curr.children:\n                curr.children[c] = TrieNode(c)\n                \n            curr = curr.children[c]\n        \n        curr.isEnd = True\n        \n    def search(self, word: str) -> bool:\n        \n        def dfs(root, word):\n            curr = root\n\n            for i in range(len(word)):\n\n                if word[i] == \".\":\n                    for l in curr.children.values():\n                        if dfs(l, word[i+1:]) == True:\n                            return True\n                        \n                    return False\n\n                if word[i] not in curr.children:\n                    return False\n\n                curr = curr.children[word[i]]\n\n            return curr.isEnd\n        \n        return dfs(self.root, word)",
        "solution_js": "var WordDictionary = function() {\n    this.aryWordList = [];\n};\n\n/** \n * @param {string} word\n * @return {void}\n */\nWordDictionary.prototype.addWord = function(word) {\n    this.aryWordList.push(word);\n};\n\n/** \n * @param {string} word\n * @return {boolean}\n */\nWordDictionary.prototype.search = function(word) {\n    \nconst isWordsMatch = (first, second) =>\n  {\n    if (first.length !== second.length) return false;        \n      \n    if (first.length == 0 && second.length == 0) return true; // Exit case for recursion\n\n    if( first[0] === second[0] || first[0] === \".\" || second[0] === \".\")\n        return isWordsMatch(first.substring(1),\n                    second.substring(1));\n\n    return false;\n}\n    \n    const isWordFound = () => {\n        let isFound = false;\n        for(var indexI=0; indexI<this.aryWordList.length; indexI++) {\n            \n            if(isWordsMatch(this.aryWordList[indexI], word)) { \n                isFound = true;\n                break;           \n            }\n            \n        }\n        \n        return isFound;\n    }\n    \n    return word.indexOf(\".\") === -1 ? this.aryWordList.includes(word) : isWordFound();\n};\n\n/** \n * Your WordDictionary object will be instantiated and called as such:\n * var obj = new WordDictionary()\n * obj.addWord(word)\n * var param_2 = obj.search(word)\n */",
        "solution_java": "class WordDictionary {\n    private class Node{\n        boolean last;\n        Node[] sub;\n        Node(){\n            last = false;\n            sub = new Node[26];\n        }\n    }\n    Node root;\n    public WordDictionary() {\n        root = new Node();\n        \n    }\n    \n    public void addWord(String word) {\n        Node temp = root;\n        for(char c : word.toCharArray()){\n            int index = c-'a';\n            if(temp.sub[index] == null)\n                temp.sub[index] = new Node();\n            temp = temp.sub[index];\n        }\n        temp.last = true;\n    }\n    \n    public boolean search(String word) {\n        Node temp = root;\n        return dfs(temp, word, 0);\n    }\n    private boolean dfs(Node node, String word, int i){\n        if(i == word.length())\n            return node.last;  \n        \n        int index = word.charAt(i)-'a';\n        if(word.charAt(i) == '.'){\n            for(int j = 0; j < 26; j++){\n                if(node.sub[j] != null)\n                    if(dfs(node.sub[j], word, i+1))\n                        return true;\n            }\n            return false;\n        }\n        else if(node.sub[index] == null)\n            return false;\n        return dfs(node.sub[index], word, i+1);\n    }\n}",
        "solution_c": "class WordDictionary {\npublic:\n    struct tr {\n        bool isword;\n        vector<tr*> next;\n        tr() {\n            next.resize(26, NULL);\n            isword = false;\n        }\n    };\n\n    tr *root;\n    WordDictionary() {\n        root = new tr();\n    }\n\n    void addWord(string word) {\n        tr *cur = root;\n\n        for(auto c: word) {\n            if(cur->next[c-'a'] == NULL) {\n                cur->next[c-'a'] = new tr();\n            }\n            cur = cur->next[c-'a'];\n        }\n\n        cur->isword = true;\n    }\n\n    bool dfs(string& word, int i, tr* cur) {\n        if(!cur ){\n            return false;\n        }\n\n        if(i == word.size()) {\n            return cur->isword;\n        }\n\n        for (; i < word.size(); i++) {\n            char c = word[i];\n            if (c == '.') {\n                for (auto it: cur->next) {\n                    if(dfs(word, i+1, it)) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n            else {\n                if(cur->next[c-'a'] == NULL) {\n                    return false;\n                }\n                cur = cur->next[c-'a'];\n            }\n        }\n\n        return cur->isword;\n    }\n\n    bool search(string word) {\n        return dfs(word, 0, root);\n    }\n};\n\n/**\n * Your WordDictionary object will be instantiated and called as such:\n * WordDictionary* obj = new WordDictionary();\n * obj->addWord(word);\n * bool param_2 = obj->search(word);\n */"
    },
    {
        "title": "Lowest Common Ancestor of a Binary Search Tree",
        "algo_input": "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”\n\n&nbsp;\nExample 1:\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput: 6\nExplanation: The LCA of nodes 2 and 8 is 6.\n\n\nExample 2:\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput: 2\nExplanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n\n\nExample 3:\n\nInput: root = [2,1], p = 2, q = 1\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 105].\n\t-109 &lt;= Node.val &lt;= 109\n\tAll Node.val are unique.\n\tp != q\n\tp and q will exist in the BST.\n\n",
        "solution_py": "class Solution:\n    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n          \n        if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)):\n            return root\n        elif (root.val > p.val):\n            return self.lowestCommonAncestor(root.left, p, q)\n        else:\n            return self.lowestCommonAncestor(root.right, p , q)",
        "solution_js": "var lowestCommonAncestor = function(root, p, q) {\n    while(root){\n        if(p.val>root.val && q.val>root.val){\n            root=root.right\n        }else if(p.val<root.val && q.val<root.val){\n            root=root.left\n        }else{\n            return root\n        }\n    }\n}",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\n\nclass Solution {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        if(root == null || root == p || root == q)return root;\n\n        TreeNode left = lowestCommonAncestor(root.left, p , q);\n        TreeNode right = lowestCommonAncestor(root.right, p ,q);\n\n        if(left == null)return right;\n        if(right == null)return left;\n        else{\n            return root;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if(p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left,p,q);\n        else if(p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right,p,q);\n        return root;\n    }\n};"
    },
    {
        "title": "Painting a Grid With Three Different Colors",
        "algo_input": "You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.\n\nReturn the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: m = 1, n = 1\nOutput: 3\nExplanation: The three possible colorings are shown in the image above.\n\n\nExample 2:\n\nInput: m = 1, n = 2\nOutput: 6\nExplanation: The six possible colorings are shown in the image above.\n\n\nExample 3:\n\nInput: m = 5, n = 5\nOutput: 580986\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m &lt;= 5\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def colorTheGrid(self, m: int, n: int) -> int:\n        from functools import reduce\n        MOD = 10**9 + 7\n        sum_mod = lambda x,y: (x+y)%MOD\n        \n        def normalize(pat_var):\n            mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n            mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n            return tuple([ mapping[e] for e in pat_var])\n        \n        def get_pats(m, i, pat, pats):\n            if i == m-1:\n                pats.append(tuple(pat))\n                return\n            i_nx = i+1\n            for p_it_nx in (1,2,3):\n                if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n                    pat.append(p_it_nx)\n                    get_pats(m, i_nx, pat, pats)\n                    pat.pop()\n            return pats\n        \n        def get_trans(pat, i, pat_pre, trans):\n            if i == len(pat)-1:\n                pat_nl = normalize(pat_pre)\n                trans[pat_nl] = trans.get(pat_nl, 0) + 1\n                return\n            for p_it_pre in (1,2,3):\n                i_nx = i+1\n                if (p_it_pre != pat[i_nx]\n                    and (not pat_pre or p_it_pre != pat_pre[-1])):\n                    pat_pre.append(p_it_pre)\n                    get_trans(pat, i_nx, pat_pre, trans)\n                    pat_pre.pop()\n            return trans\n\n        pats = get_pats(m, -1, [], [])\n        # {pattern_i: {pattern_pre:count}}\n        pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats }  \n        \n        p_counts = { pat:1 for pat in pat_trans.keys() }\n        for i in range(n-1):\n            p_counts_new = {}\n            for pat, trans in pat_trans.items():\n                p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n            p_counts = p_counts_new\n        \n        res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n        perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n        return (res * perms) % MOD",
        "solution_js": "// transform any decimal number to its ternary representation\nlet ternary=(num,len)=>{\n    let A=[],times=0\n    while(times++<len)\n        A.push(num%3),num= (num-num%3)/3\n    return A\n}\n// deduce whether my array does not contain 2 consecutive elements\nlet adjdiff=Array=>Array.every((d,i)=>i==0||d!==Array[i-1])\n//main\nvar colorTheGrid = function(n, m) {\n    let mod=1e9+7,adj=[...Array(3**(n))].map(d=>new Set()),\n    //1.turn every potential state to a ternary(base3) representation\n        base3=[...Array(3**n)].map((d,i)=>ternary(i,n)),\n\t\t//3 conditions such that state a can be previous to state b \n        ok=(a,b)=>adjdiff(base3[a])&& adjdiff(base3[b])&& base3[a].every( (d,i)=>d!==base3[b][i])\n    //2.determine what are the acceptable adjacent states of any given state\n    for(let m1=0;m1<3**n;m1++)\n        for(let m2=0;m2<3**n;m2++)\n            if(ok(m1,m2))\n                adj[m1].add(m2),adj[m2].add(m1)\n    //3.do 2-row dp, where dp[state]= the number of colorings where the last line is colored based on state\n    let dp=[...Array(3**n)].map((d,i)=>Number(adjdiff(base3[i])))\n    for(let i=1,dp2=[...Array(3**n)].map(d=>0);i<m;i++,dp=[...dp2],dp2.fill(0))\n        for(let m1=0;m1<3**n;m1++)\n            for(let prev of Array.from(adj[m1]))\n                dp2[m1]=(dp2[m1]+dp[prev])%mod\n    return dp.reduce((a,c)=> (a+c) %mod ,0)\n};",
        "solution_java": "class Solution \n{\n    static int mod=(int)(1e9+7);\n   public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])\n   {\n       if(n==0)\n       {\n           return 1;\n       }\n       if(dp[n][src]!=-1)\n       {\n           return dp[n][src];\n       }\n       int val=0;\n    for(Integer ap:arr.get(src))\n    {\n         val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n    }\n       return dp[n][src]=val;\n   }\n   public static void val(ArrayList<String> arr,int color,int m,String s)\n    {\n        if(m==0)\n        {\n            arr.add(s);\n            return;\n        }\n       for(int i=0;i<3;i++)\n       {\n           if(color!=i)\n           val(arr,i,m-1,s+i);\n       }\n    }\n    public static boolean Match(String s,String s1)\n    {\n        for(int i=0;i<s.length();i++)\n        {\n            if(s.charAt(i)==s1.charAt(i))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n    public int colorTheGrid(int m, int n)\n    {\n        ArrayList<String> arr=new ArrayList<String>();\n        for(int i=0;i<3;i++)\n        {\n            String s=\"\";\n            val(arr,i,m-1,s+i);\n        }\n        ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>();\n        for(int i=0;i<arr.size();i++)\n        {\n            adj.add(new ArrayList<Integer>());\n        }\n    \n        for(int i=0;i<adj.size();i++)\n        {\n            for(int j=0;j<arr.size();j++)\n            {\n                if(Match(arr.get(i),arr.get(j)))\n                {\n                    adj.get(i).add(j);\n                }\n            }\n        }\n  int dp[][]=new int[n+1][adj.size()+1];\n        for(int i=0;i<=n;i++)\n        {\n            Arrays.fill(dp[i],-1);\n        }\n        int sum12=0;\n        for(int i=0;i<arr.size();i++)\n        {\n                 sum12=(sum12%mod+dfs(n-1,adj,i,dp)%mod)%mod;\n        }\n        return sum12;\n       \n    }\n}",
        "solution_c": "vector<string> moves;\nint MOD = 1e9 + 7;\nvoid fill(string s, int n, int p){\n    if(n==0){\n        moves.push_back(s);\n        return;\n    }\n    for(int i=1; i<4; i++){\n        if(p==i){\n            continue;\n        }\n        string m = to_string(i);\n        fill(s+m, n-1, i);\n    }\n    return;\n}\nclass Solution {\npublic:\n    vector<vector<int>>memo;\n    int solve(int n, int lastIdx, int m){\n        if (n == 0) return 1;\n        int ret = 0;\n        if (memo[n][lastIdx] != -1) return memo[n][lastIdx];\n        string last = moves[lastIdx];\n        for (int idx = 0; idx<moves.size(); idx++) {\n            string move = moves[idx];\n            bool same = false;\n            for (int i = 0; i < m; i++) if (move[i] == last[i]) same = true;   \n            if (!same) ret = (ret + solve(n - 1, idx, m)%MOD)%MOD;\n        }\n        return memo[n][lastIdx]= ret%MOD;\n    }\n    int colorTheGrid(int m, int n){\n        moves.clear();\n        fill(\"\", m, -1);\n        //cout<<moves.size()<<endl;\n        memo.resize(n + 1, vector<int>(moves.size(), -1));\n        int ret = 0;\n        for (int idx = 0; idx < moves.size(); idx++)\n            ret =  (ret + solve(n-1, idx, m)%MOD)%MOD;\n        return ret;\n    }\n};"
    },
    {
        "title": "Count Words Obtained After Adding a Letter",
        "algo_input": "You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.\n\nFor each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.\n\nThe conversion operation is described in the following two steps:\n\n\n\tAppend any lowercase letter that is not present in the string to its end.\n\n\t\n\t\tFor example, if the string is \"abc\", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be \"abcd\".\n\t\n\t\n\tRearrange the letters of the new string in any arbitrary order.\n\t\n\t\tFor example, \"abcd\" can be rearranged to \"acbd\", \"bacd\", \"cbda\", and so on. Note that it can also be rearranged to \"abcd\" itself.\n\t\n\t\n\n\nReturn the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.\n\nNote that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.\n\n&nbsp;\nExample 1:\n\nInput: startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\nOutput: 2\nExplanation:\n- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n  Note that \"act\" does exist in startWords, but we must append one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.\n\n\nExample 2:\n\nInput: startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\nOutput: 1\nExplanation:\n- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= startWords.length, targetWords.length &lt;= 5 * 104\n\t1 &lt;= startWords[i].length, targetWords[j].length &lt;= 26\n\tEach string of startWords and targetWords consists of lowercase English letters only.\n\tNo letter occurs more than once in any string of startWords or targetWords.\n\n",
        "solution_py": "# Brute Force\n# O(S * T); S := len(startWors); T := len(targetWords)\n# TLE\nclass Solution:\n    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n        cnt = 0\n        for target in targetWords:\n            for start in startWords:\n                if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1:\n                    cnt += 1\n                    break\n        return cnt\n\n# Sort + HashSet Lookup\n# O(S + T) Time\nclass Solution:\n    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n        # Sort each start word and add it to a hash set\n        startWords_sorted = set()\n        # O(S*26*log(26))\n        for word in startWords:\n            startWords_sorted.add(\"\".join(sorted(list(word))))\n        \n        # sort each target word and add it to a list\n        # O(T*26*log(26))\n        targetWords_sorted = []\n        for word in targetWords:\n            targetWords_sorted.append(sorted(list(word)))\n        \n        # for each sorted target word, we remove a single character and \n        # check if the resulting word is in the startWords_sorted\n        # if it is, we increment cnt and break the inner loop\n        # otherwise we keep removing until we either find a hit or reach the\n        # end of the string\n        # O(T*26) = O(T)\n        cnt = 0\n        for target in targetWords_sorted:\n            for i in range(len(target)):\n                w = target[:i] + target[i+1:]\n                w = \"\".join(w)\n                if w in startWords_sorted:\n                    cnt += 1\n                    break\n        \n        return cnt\n\n# Using Bit Mask\n# O(S + T) Time\n# Similar algorithm as the one above, implemented using a bit mask to avoid the sorts\nclass Solution:\n    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n        start_set = set()\n        # O(S * 26)\n        for word in startWords:\n            m = 0\n            for ch in word:\n                i = ord(ch) - ord('a')\n                m |= (1 << i)\n            start_set.add(m)\n        \n        # O(T * 2 * 26)\n        cnt = 0\n        for word in targetWords:\n            m = 0\n            for ch in word:\n                i = ord(ch) - ord('a')\n                m |= (1 << i)\n            \n            for ch in word:\n                i = ord(ch) - ord('a')\n                if m ^ (1 << i) in start_set:\n                    cnt += 1\n                    break\n        return cnt",
        "solution_js": "var wordCount = function(startWords, targetWords) {\n    const startMap = {};\n    for(let word of startWords) {\n        startMap[word.split('').sort().join('')] = true;\n    }\n\n    let ans = 0;\n    for(let word of targetWords) {\n        for(let i=0;i<word.length;i++) {\n            let temp = (word.substring(0,i) + word.substring(i+1,word.length)).split('').sort().join('');\n            if(startMap[temp]) {\n                ans++;\n                break;\n            }\n        }\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int wordCount(String[] startWords, String[] targetWords) {\n        int n = startWords.length;\n        int count = 0;\n        Set<String> set = new HashSet<>();\n        \n        //1. store lexicographically sorted letters of startword in set\n        for(String start: startWords){\n            char[] sAr = start.toCharArray();\n            Arrays.sort(sAr);\n            set.add(new String(sAr));\n        }\n        int m = targetWords.length;\n        boolean ans = false;\n        for(int i = 0; i < m; i++){\n            //2. sort lexicographically letters of targetword and store in new string s\n            char[] tAr = targetWords[i].toCharArray();\n            Arrays.sort(tAr);\n            int k = tAr.length;\n            String s = String.valueOf(tAr);\n            \n            ans = false;\n            for(int j = 0; j < k; j++){\n                //3. make a new string by omitting one letter from word and check if it is present in set than increase count value\n                String str = s.substring(0,j) + s.substring(j+1);\n                if(set.contains(str)){\n                    count++;\n                    break;\n                }\n            }\n        }\n        return count;    \n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n    int wordCount(vector<string>& startWords, vector<string>& targetWords) {\n        set<vector<int>> hash;\n        for (int i = 0; i < startWords.size(); i++) {\n            vector<int> counter(26, 0);\n            for (char &x : startWords[i]) {\n                counter[x - 'a']++;\n            }\n            hash.insert(counter); \n        }\n        \n        \n        int ans = 0;\n        \n        for (int i = 0; i < targetWords.size(); i++) {\n            vector<int> counter(26, 0);\n            for (char &x : targetWords[i]) {\n                counter[x - 'a']++;\n            }\n            \n            for (int j = 0; j < 26; j++) {\n                if (counter[j] == 1) {\n                    counter[j] = 0;\n                    \n                    if (hash.find(counter) != hash.end()) {\n                        ans++;\n                        break;\n                    }\n                    \n                    counter[j] = 1;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Delete Leaves With a Given Value",
        "algo_input": "Given a binary tree root and an integer target, delete all the leaf nodes with value target.\n\nNote that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [1,2,3,2,null,2,4], target = 2\nOutput: [1,null,3,null,4]\nExplanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\n\n\nExample 2:\n\n\n\nInput: root = [1,3,3,3,2], target = 3\nOutput: [1,3,null,null,2]\n\n\nExample 3:\n\n\n\nInput: root = [1,2,null,2,null,2], target = 2\nOutput: [1]\nExplanation: Leaf nodes in green with value (target = 2) are removed at each step.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 3000].\n\t1 &lt;= Node.val, target &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:\n        if not root:\n            return None\n        root.left = self.removeLeafNodes(root.left, target)\n        root.right = self.removeLeafNodes(root.right, target)\n        if not root.left and not root.right and root.val == target:\n            return None\n        return root",
        "solution_js": "var removeLeafNodes = function(root, target) {\n    const parent = new TreeNode(-1, root, null);\n\n    const traverse = (r = root, p = parent, child = -1) => {\n        if(!r) return null;\n        traverse(r.left, r, -1);\n        traverse(r.right, r, 1);\n        if(r.left == null && r.right == null && r.val == target) {\n            if(child == -1) p.left = null;\n            else p.right = null;\n        }\n    }\n    traverse();\n    return parent.left;\n};",
        "solution_java": "class Solution {\n    public TreeNode removeLeafNodes(TreeNode root, int target) {\n        if(root==null)\n            return root;\n        root.left = removeLeafNodes(root.left,target);\n        root.right = removeLeafNodes(root.right,target);\n        if(root.left == null && root.right == null && root.val == target)\n            root = null;\n        return root;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* removeLeafNodes(TreeNode* root, int target) {\n        if(root==NULL || root->left == NULL && root->right == NULL && root->val == target)\n            return NULL;\n\n        root->left = removeLeafNodes(root->left,target);\n        root->right = removeLeafNodes(root->right,target);\n\n        if(root->left == NULL && root->right == NULL && root->val == target)\n        {\n            return NULL;\n        }\n\n        return root;\n\n    }\n};"
    },
    {
        "title": "Maximum Value of K Coins From Piles",
        "algo_input": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.\n\nIn one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.\n\nGiven a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.\n\n&nbsp;\nExample 1:\n\nInput: piles = [[1,100,3],[7,8,9]], k = 2\nOutput: 101\nExplanation:\nThe above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.\n\n\nExample 2:\n\nInput: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput: 706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == piles.length\n\t1 &lt;= n &lt;= 1000\n\t1 &lt;= piles[i][j] &lt;= 105\n\t1 &lt;= k &lt;= sum(piles[i].length) &lt;= 2000\n\n",
        "solution_py": "class Solution:\n    def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n        n = len(piles)\n        prefixSum = []\n        for i in range(n):\n            temp = [0]\n            for j in range(len(piles[i])):\n                temp.append(temp[-1] + piles[i][j])\n            prefixSum.append(temp)\n            \n        dp = [[0] * (k + 1) for _ in range(n)]\n        for j in range(1, k + 1):\n            if j < len(prefixSum[0]):\n                dp[0][j] = prefixSum[0][j]\n        \n        for i in range(1, n):\n            for j in range(1, k + 1):\n                for l in range(len(prefixSum[i])):\n                    if l > j:\n                        break\n                    dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l])\n        return dp[n - 1][k]",
        "solution_js": "/**\n * @param {number[][]} piles\n * @param {number} k\n * @return {number}\n */\nvar maxValueOfCoins = function(piles, k) {\n    var n = piles.length;\n    var cache = {};\n    \n    var getMax = function(i, k) {\n        if (i >= n || k <= 0) return 0;\n        var key = i + ',' + k;\n        if (cache[key] !== undefined) return cache[key];\n        var ans = getMax(i + 1, k);\n        var cur = 0;\n        \n        for (var j = 0; j < piles[i].length && j < k; j++) {\n            cur+=piles[i][j];\n            ans = Math.max(ans, cur + getMax(i + 1, k - j - 1));\n        }\n        \n        return cache[key] = ans;\n    }\n    \n    return getMax(0, k);\n};",
        "solution_java": "class Solution {\n    public int maxValueOfCoins(List<List<Integer>> piles, int k) {\n        int n = piles.size();\n        int[][] ans = new int[n+1][2001];\n        Collections.sort(piles, (List<Integer> a, List<Integer> b) -> b.size() - a.size());\n        for(int i = 1; i <= k; i++) {\n            for(int j = 1; j <= n; j++) {\n                int sizeOfPile = piles.get(j-1).size();\n                List<Integer> pile = piles.get(j-1);\n                int sum = 0;\n                ans[j][i] = ans[j-1][i];\n                for(int l = 1; l <= Math.min(i, sizeOfPile); l++) {\n                    // Take K from this pile + remaining from previous piles\n                    sum += pile.get(l-1);\n                    int rem = i - l;\n                    ans[j][i] = Math.max(ans[j][i], sum + ans[j-1][rem]);\n                }\n            }\n        }\n\n        return ans[n][k];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n   int dp[1001][2001]; //Dp array For Memoization.\n   int solve(vector<vector<int>>&v,int index,int coin)\n   {\n       if(index>=v.size()||coin==0) //Base Condition\n           return 0;\n       if(dp[index][coin]!=-1) //Check wheather It is Already Calculated Or not.\n           return dp[index][coin];\n\n       /* Our 1st choice :- We not take any Coin from that pile*/\n       int ans=solve(v,index+1,coin); //Just Call function for next Pile.\n\n       /*Otherwise we can take Coins from that Pile.*/\n       int loop=v[index].size()-1;\n       int sum=0;\n\n       for(int j=0;j<=min(coin-1,loop);j++) //\n       {\n           sum=sum+v[index][j];\n           ans=max(ans,sum+solve(v,index+1,coin-(j+1)));\n\n           /*Aove we Pass coin-(j+1). Because till j'th index we have taken j+1 coin from that pile.*/\n       }\n\n       return dp[index][coin]=ans;\n   }\n   int maxValueOfCoins(vector<vector<int>>& piles, int k) {\n       memset(dp,-1,sizeof(dp));\n       return solve(piles,0,k);\n   }\n};"
    },
    {
        "title": "Couples Holding Hands",
        "algo_input": "There are n couples sitting in 2n seats arranged in a row and want to hold hands.\n\nThe people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).\n\nReturn the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.\n\n&nbsp;\nExample 1:\n\nInput: row = [0,2,1,3]\nOutput: 1\nExplanation: We only need to swap the second (row[1]) and third (row[2]) person.\n\n\nExample 2:\n\nInput: row = [3,2,0,1]\nOutput: 0\nExplanation: All couples are already seated side by side.\n\n\n&nbsp;\nConstraints:\n\n\n\t2n == row.length\n\t2 &lt;= n &lt;= 30\n\tn is even.\n\t0 &lt;= row[i] &lt; 2n\n\tAll the elements of row are unique.\n\n",
        "solution_py": "class Solution:\n    def minSwapsCouples(self, row: List[int]) -> int:\n        count = 0\n        for i in range(0, len(row)-2, 2):\n            idx = i+1\n            if(row[i]%2 == 0):\n                n = (row[i] + 2)//2\n                newNo = 2*n - 1\n            else:\n                n = (row[i] + 1) //2;\n                newNo = 2*n - 2\n            for j in range(i, len(row)):\n                if row[j] == newNo:\n                    idx = j\n                    break\n            if idx != i+1:\n                count += 1\n            row[idx], row[i+1] = row[i+1], row[idx]\n        return count\n\t\t```",
        "solution_js": "/**\n * @param {number[]} row\n * @return {number}\n */\nvar minSwapsCouples = function(row) {\n    let currentPositions = [];\n\n    for(let i=0;i<row.length;i++){\n        currentPositions[row[i]]=i;\n    }\n\n    let swapCount = 0;\n\n     for(let j=0;j<row.length;j+=2) // Looping through the couches\n         {\n\n    let leftPartner = row[j];\n    let correctRightPartner = getPartner(leftPartner);\n        if(row[j+1] !== correctRightPartner)\n        {\n            console.log(\"unhappy\");\n            //Swap Positions of positions - Bring the Correct Right Partner in the Couch\n            let tempValue = row[j+1];\n            row[j+1]=correctRightPartner;\n            let tempPosition = currentPositions[correctRightPartner];\n            row[tempPosition]=tempValue;\n\n            //Correct the Hash Table keeping the currentPositions of each Person.\n            currentPositions[correctRightPartner]=j+1;\n            currentPositions[tempValue]=tempPosition;\n\n            swapCount+=1;\n        }\n        else\n        {\n\n        console.log(\"happy\");\n        }\n    }\n\n    console.log(\"currentPositions\", currentPositions,\"Correct Row\", row);\n\n    return swapCount;\n\n};\nfunction getPartner(x){\n    if(x%2 ===0)\n    {\n        return x+1;\n    }\n    else\n        return x-1;\n}",
        "solution_java": "class Solution {\n    public int minSwapsCouples(int[] row) { // Union -Find pairs for 2\n        Map<Integer,Integer> parents=new HashMap<>();\n        int count=0;\n        for(int i=0;i<row.length;i+=2){\n            int parent=Math.min(row[i],row[i+1]);\n            int child=Math.max(row[i],row[i+1]);\n            parents.put(parent,child);\n        }\n        for(int i=0;i<row.length;i+=2){\n            if((parents.containsKey(i) && parents.get(i)==(i+1)) \n               || (parents.containsKey(i-1) && parents.get(i-1)==i))\n                continue;\n            count+=1;\n            int curChild=parents.get(i);\n            int correctChildsChild = parents.get(i+1);\n            parents.remove(i+1); // remove mapping of 1 in eg) //0,2 ; 1,3\n            parents.put(Math.min(curChild,correctChildsChild),Math.max(curChild,correctChildsChild));\n            // add mapping 2->7 , also place smaller number as parent for eg)//0,4 ; 1,3\n            parents.put(i,i+1);\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint minSwapsCouples(vector<int>& row) {\n\t\tint cnt=0,n=row.size();\n\t\t// first of all making row element equal  ex for [0,1],[2,3] --> [0,0] ,[2,2]\n\t\tfor(auto &x : row){\n\t\t\tif(x&1){\n\t\t\t\tx--;\n\t\t\t}\n\t\t}\n\n\t\tfor( int i=0; i<n; i+=2){\n\t\t\tint ele=row[i];\n\t\t\tint j=i+1;\n\t\t\t// for every num find location of equal one,\n\t\t\twhile(j<n and row[j]!=ele) j++;\n\t\t\tif(j!=i+1){\n\t\t\t\t\t\t// not in same couch then cnt++ , and swap\n\t\t\t\tswap(row[j], row[i+1]);\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\treturn cnt;\n\t}\n};"
    },
    {
        "title": "Path Sum",
        "algo_input": "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.\n\nA leaf is a node with no children.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput: true\nExplanation: The root-to-leaf path with the target sum is shown.\n\n\nExample 2:\n\nInput: root = [1,2,3], targetSum = 5\nOutput: false\nExplanation: There two root-to-leaf paths in the tree:\n(1 --&gt; 2): The sum is 3.\n(1 --&gt; 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.\n\n\nExample 3:\n\nInput: root = [], targetSum = 0\nOutput: false\nExplanation: Since the tree is empty, there are no root-to-leaf paths.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 5000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\t-1000 &lt;= targetSum &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def hasPathSum(self, root, targetSum):\n        \"\"\"\n        :type root: TreeNode\n        :type targetSum: int\n        :rtype: bool\n        \"\"\"\n        if not root: return False\n        targetSum -= root.val\n        if not root.left and not root.right:\n            return not targetSum\n        return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)",
        "solution_js": "var hasPathSum = function(root, targetSum) {\n\treturn DFS(root, 0 , targetSum)\n};\n\nconst DFS = (curr, currentSum, targetSum) =>{\n\n\tif(!curr) return false\n\n\tcurrentSum += curr.val;\n\n\tif(!curr.left && !curr.right) return currentSum === targetSum;\n\n\treturn DFS(curr.left, currentSum, targetSum) || DFS(curr.right, currentSum, targetSum)\n}",
        "solution_java": "class Solution {\n    public boolean hasPathSum(TreeNode root, int targetSum) {\n       if(root == null) return false;\n      \n      if(root.left == null && root.right == null) return root.val == targetSum;\n      \n      return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool ans=false;\n      int sum=0;\n    void recur(TreeNode* root, int target){\n        if(root==NULL)return;\n        \n            sum+=root->val;\n            recur(root->left,target);\n            recur(root->right,target);\n           if(root->left==NULL && root->right==NULL&&sum == target){ // !!Check only if it is a leaf node....\n             ans = true;\n             return;\n            }\n            sum-=root->val; //backtracking\n            return;\n        \n    }\n    bool hasPathSum(TreeNode* root, int targetSum) {\n        recur(root,targetSum);\n        return ans;\n    }\n};"
    },
    {
        "title": "Building Boxes",
        "algo_input": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\n\n\n\tYou can place the boxes anywhere on the floor.\n\tIf box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.\n\n\nGiven an integer n, return the minimum possible number of boxes touching the floor.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 3\nOutput: 3\nExplanation: The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\nExample 2:\n\n\n\nInput: n = 4\nOutput: 3\nExplanation: The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\nExample 3:\n\n\n\nInput: n = 10\nOutput: 6\nExplanation: The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minimumBoxes(self, n: int) -> int:\n        r = 0\n        while (n_upper := r*(r+1)*(r+2)//6) < n:\n            r += 1\n        m = r*(r+1)//2\n        for i in range(r, 0, -1):\n            if (n_upper - i) < n:\n                break\n            n_upper -= i\n            m -= 1\n        return m",
        "solution_js": "var minimumBoxes = function(n) {\n    //Binary search for the height of the biggest triangle I can create with n cubes available.\n    let lo=1,hi=n,result\n    let totalCubes=x=>x*(x+1)*(x+2)/6 //the total cubes of a triangle with height x \n    while(lo+1<hi){\n        let mid=lo+hi>>1\n        if(totalCubes(mid)<=n)\n            lo=mid\n        else \n            hi=mid\n    }\n\tlet f=(x)=>Math.floor(Math.sqrt(2*x)+1/2)// the i-th element of the sequence 1,2,2,3,3,3,4,4,4,4,5,...\n    result=(lo)*(lo+1)/2// the base of the largest complete triangle 1+2+3+..+H\n    n-=totalCubes(lo) //remove the cubes of the complete triangle\n    return result+f(n)  // the base of the largest+ the extra floor cubes\n};",
        "solution_java": "class Solution {\n\n    static final double ONE_THIRD = 1.0d / 3.0d;\n\n    public int minimumBoxes(int n) {\n        int k = findLargestTetrahedralNotGreaterThan(n);\n        int used = tetrahedral(k);\n        int floor = triangular(k);\n        int unused = (n - used);\n        if (unused == 0) {\n            return floor;\n        }\n        int r = findSmallestTriangularNotLessThan(unused);\n        return (floor + r);\n    }\n\n    private final int findLargestTetrahedralNotGreaterThan(int te) {\n        int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD));\n        while (tetrahedral(a) > te) {\n            a--;\n        }\n        return a;\n    }\n\n    private final int findSmallestTriangularNotLessThan(int t) {\n        int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2)));\n        while (triangular(a) < t) {\n            a++;\n        }\n        return a;\n    }\n\n    private final int tetrahedral(int a) {\n        return (int) ratio(product(a, a + 1, a + 2), 6);\n    }\n\n    private final int triangular(int a) {\n        return (int) ratio(product(a, a + 1), 2);\n    }\n\n    private final long product(long... vals) {\n        long product = 1L;\n        for (long val : vals) {\n            product *= val;\n        }\n        return product;\n    }\n\n    private final long ratio(long a, long b) {\n        return (a / b);\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumBoxes(int n) {\n        \n        // Find the biggest perfect pyramid\n        uint32_t h = cbrt((long)6*n);\n        uint32_t pyramid_box_num = h*(h+1)/2*(h+2)/3;   // /6 is split to /2 and /3 to avoid long to save space\n        if ( pyramid_box_num > n ){\n            h--;\n            pyramid_box_num = h*(h+1)/2*(h+2)/3;            // /6 is split to /2 and /3 to avoid long to save space\n        }\n        \n        // Calculate how many floor-touching boxes in the pyramid\n        int pyramid_base_num = (h)*(h+1)/2;\n        \n        // Get the number of boxes to be added to the perfect pyramid\n        n -= pyramid_box_num;\n        \n        // Find how many floor-touching boxes are added\n        int z = sqrt(2*n);\n        int max_box_added = z*(z+1)/2;\n        if ( max_box_added < n)\n            z++;\n        \n        return pyramid_base_num+z;\n    }\n};"
    },
    {
        "title": "Deepest Leaves Sum",
        "algo_input": "Given the root of a binary tree, return the sum of values of its deepest leaves.\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\n\n\nExample 2:\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 19\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode(object):\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution(object):\n    \n    \"\"\"\n    THOUGHT PROCESS:\n        1) find the height of the tree, this way we would know how deep we need to go.\n        2) we need a counter to check how deep we are and this is not available in deepestLeavesSum so we create a new function deepestLeave.\n        3) now we go in depth, if we are at bottom, we return the value, we recursively visit both left and right nodes.\n        \n    \"\"\"\n    \n    def height(self, root):\n        if root is None:\n            return 0\n        else:\n            x, y = 1, 1\n            if root.left:\n                x = self.height(root.left)+1\n            if root.right:\n                y = self.height(root.right)+1\n            \n            return max(x, y)\n            \n    \n    def deepestLeave(self, root, depth):\n        \n        if root is None:\n            return 0\n        \n        if root.left is None and root.right is None:\n            if depth == 1:\n                return root.val\n        \n        return self.deepestLeave(root.left, depth-1) + self.deepestLeave(root.right, depth-1)\n    \n    def deepestLeavesSum(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: int\n        \"\"\"\n        return self.deepestLeave(root, self.height(root))\n        \n        \n        \n        \n        ",
        "solution_js": "var deepestLeavesSum = function(root) {\n    let queue = [];\n    queue.push([root, 0]);\n    let sum = 0;\n    let curLevel = 0\n    let i = 0;\n    while(queue.length-i > 0) {\n        let [node, level] = queue[i];\n        queue[i] = null;\n        i++;\n        if(level > curLevel) {\n            sum = 0;\n            curLevel = level;\n        }\n        sum += node.val;\n        if(node.left != null) queue.push([node.left, level+1]);\n        if(node.right != null) queue.push([node.right, level+1]);\n    }\n    return sum;\n    //time: o(n)\n    //space: o(n)\n};",
        "solution_java": "class Solution {\n    public int height(TreeNode root)\n    {\n        if(root == null)\n            return 0;\n        return Math.max(height(root.left), height(root.right)) + 1;\n    }\n    public int deepestLeavesSum(TreeNode root) {\n        if(root == null) return 0;\n        if(root.left == null && root.right == null) return root.val;\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root);\n        q.add(null);\n        int hght = height(root);\n        int sum = 0;\n        while(q.size()>0 && q.peek()!=null)\n        {\n            TreeNode temp = q.remove();\n            if(temp.left!=null) q.add(temp.left);\n            if(temp.right!=null) q.add(temp.right);\n            if(q.peek() == null)\n            {\n                q.remove();\n                q.add(null);\n                hght--;\n            }\n            if(hght == 1)\n            {\n                while(q.size()>0 && q.peek()!=null)\n                {\n                    sum+=q.remove().val;\n                }\n            }\n\n        }\n        return sum;\n    }\n}",
        "solution_c": "\t\t\t\t\t\t**\t#Vote if u like ❤️**\n\t\t\t\t\t\t\t\n\tclass Solution {\n\tpublic:\n\t\tvoid fun(TreeNode *root , int l , map<int , vector<int>> &m)\n\t\t{\n\t\t\tif(root == NULL) return; //If root is NULL it will return \n\t\t\tm[l].push_back(root -> val); //With level as key inserting the value to the vector\n\t\t\tfun(root -> left, l + 1, m); // passing the left with level + 1 \n\t\t\tfun(root -> right, l + 1 , m); // passing right with level + 1\n\t\t}\n\t\tint deepestLeavesSum(TreeNode* root) {\n\t\t\tmap<int , vector<int>> m;  // Map with key as level and value of vector for storing the values\n\t\t\tfun(root , 0 , m); // A void fun with map and level as 0\n\t\t   auto itr = m.rbegin(); //Hence we need the leaves node the nodes are present in last level \n\t\t\tint sum = 0; // Sum Variable \n\t\t\tfor(int i = 0; i < itr-> second.size(); i++) {sum += itr -> second[i];}\n\t\t\treturn sum;\n\t\t}\n\t};\n\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t-Yash:)"
    },
    {
        "title": "Final Prices With a Special Discount in a Shop",
        "algo_input": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum&nbsp;index such that j &gt; i and prices[j] &lt;= prices[i], otherwise, you will not receive any discount at all.\n\nReturn an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.\n\n&nbsp;\nExample 1:\n\nInput: prices = [8,4,6,2,3]\nOutput: [4,2,4,2,3]\nExplanation:&nbsp;\nFor item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.&nbsp;\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.&nbsp;\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.&nbsp;\nFor items 3 and 4 you will not receive any discount at all.\n\n\nExample 2:\n\nInput: prices = [1,2,3,4,5]\nOutput: [1,2,3,4,5]\nExplanation: In this case, for all items, you will not receive any discount at all.\n\n\nExample 3:\n\nInput: prices = [10,1,1,6]\nOutput: [9,0,1,6]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 500\n\t1 &lt;= prices[i] &lt;= 10^3\n\n",
        "solution_py": "class Solution:\n    def finalPrices(self, prices: List[int]) -> List[int]:\n        ## RC ##\n        ## APPROACH : STACK ##\n        ## LOGIC ## \n        ## 1. Use Monotonic Increasing Stack Concept\n        ## 2. Main idea is to find the Next Smaller Element in O(N) using #1\n        stack = []\n        for i, num in enumerate(prices):\n            while(stack and prices[stack[-1]] >= num):\n                popIndex = stack.pop()\n                prices[popIndex] -= num\n            stack.append(i)\n        return prices",
        "solution_js": "var finalPrices = function(prices) {\n    let adjPrices = [];\n    while(prices.length) {\n        let currentPrice = prices[0];\n        \n        // Remove first price in original array\n        // Since we're looking for a price less than or equal to\n        prices.shift();\n        \n        let lowerPrice = prices.find((a) => a <= currentPrice);\n        adjPrices.push(lowerPrice ? currentPrice - lowerPrice : currentPrice);\n    }\n    \n    return adjPrices;\n};",
        "solution_java": "class Solution {\n    public int[] finalPrices(int[] prices) {\n        for(int i = 0; i < prices.length; i++){\n            for(int j = i + 1; j < prices.length; j++){\n                if(j > i && prices[j] <= prices[i]){\n                    prices[i] -= prices[j];\n                    break;\n                }\n            }\n        }\n        return prices;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> finalPrices(vector<int>& prices) {\n        vector<int>sk;\n        for(int i=0;i<prices.size();i++){\n        int discount=prices[i];\n            for(int j=i+1;j<prices.size();j++){\n                if(prices[i]>=prices[j]){\n                    discount=prices[i]-prices[j];\n                    break;\n                }\n\n            }\n            sk.push_back(discount);\n        }\n        return sk;\n    }\n};"
    },
    {
        "title": "Median of Two Sorted Arrays",
        "algo_input": "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\n\nThe overall run time complexity should be O(log (m+n)).\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,3], nums2 = [2]\nOutput: 2.00000\nExplanation: merged array = [1,2,3] and median is 2.\n\n\nExample 2:\n\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 2.50000\nExplanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n\n\n&nbsp;\nConstraints:\n\n\n\tnums1.length == m\n\tnums2.length == n\n\t0 &lt;= m &lt;= 1000\n\t0 &lt;= n &lt;= 1000\n\t1 &lt;= m + n &lt;= 2000\n\t-106 &lt;= nums1[i], nums2[i] &lt;= 106\n\n",
        "solution_py": "class Solution(object):\n    def findMedianSortedArrays(self, nums1, nums2):\n        lis = nums1 + nums2\n        lis.sort()\n        hi = len(lis)\n        print(5/2)\n        if hi%2 == 0:\n            if (lis[hi/2] + lis[hi/2-1])%2 == 0:\n                return (lis[hi/2] + lis[hi/2-1] )/2\n            return (lis[hi/2] + lis[hi/2-1])/2 + 0.5\n        else:\n            return lis[hi//2]",
        "solution_js": "var findMedianSortedArrays = function(nums1, nums2) {\n  let nums3 = nums1.concat(nums2).sort((a,b) => a - b)\n  if(nums3.length % 2 !== 0) return nums3[(nums3.length-1)/2]\n  return (nums3[nums3.length/2] + nums3[nums3.length/2 - 1])/2\n};",
        "solution_java": "class Solution {\n    public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n        if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0;\n        int i = 0;\n        int j = 0;\n        int k = 0;\n        int nums[] = new int[nums1.length + nums2.length];\n        if(nums1.length !=0 && nums2.length != 0){\n          while(i < nums1.length && j < nums2.length){\n            if(nums1[i] < nums2[j]){\n                nums[k] = nums1[i];\n                i++;\n                k++;\n            }else{\n                nums[k] = nums2[j];\n                j++;\n                k++;\n            }\n          }\n            while(i < nums1.length){\n                nums[k] = nums1[i];\n                i++;\n                k++;\n            }\n             while(j < nums2.length){\n                nums[k] = nums2[j];\n                j++;\n                k++;\n            }\n        }\n        if(nums1.length==0){\n            for(int h: nums2){\n                nums[k] = h;\n                k++;\n            }\n        }\n\n        if(nums2.length==0){\n            for(int d : nums1){\n                nums[k] = d;\n                k++;\n            }\n        }\n\n        int mid = (nums.length / 2);\n\n        if (nums.length % 2 == 0) {\n            return ((double) nums[mid] + (double) nums[mid - 1]) / 2.0;\n        } else {\n            return nums[mid];\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    \n    //Merging two arrays :- \n    vector<int> mergeSortedArrays(vector<int>&arr1,vector<int>&arr2){\n        int n = arr1.size();\n        int m = arr2.size();\n        vector<int> ans(m+n);\n        int i = 0;\n        int j = 0;\n        int mainIndex = 0;\n        \n        while( i < n && j < m ){\n            if(arr1[i] <= arr2[j])ans[mainIndex++] = arr1[i++];\n            else ans[mainIndex++] = arr2[j++];\n        }\n        \n        while( i < n){\n            ans[mainIndex++] = arr1[i++];\n        }\n        \n        while( j < m){\n            ans[mainIndex++] = arr2[j++];\n        }\n        return ans;\n    }\n    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n        vector<int> ans = mergeSortedArrays(nums1,nums2);\n        float median = 0;\n        int n = ans.size()-1;\n        \n        if(n%2 != 0)\n         median=(ans[n/2]+ans[(n/2)+1])/2.0; \n        else\n            median=ans[n/2]; \n        return median;\n        \n    }\n};"
    },
    {
        "title": "Search Suggestions System",
        "algo_input": "You are given an array of strings products and a string searchWord.\n\nDesign a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.\n\nReturn a list of lists of the suggested products after each character of searchWord is typed.\n\n&nbsp;\nExample 1:\n\nInput: products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput: [\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\nExplanation: products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]\n\n\nExample 2:\n\nInput: products = [\"havana\"], searchWord = \"havana\"\nOutput: [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n\n\nExample 3:\n\nInput: products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\nOutput: [[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= products.length &lt;= 1000\n\t1 &lt;= products[i].length &lt;= 3000\n\t1 &lt;= sum(products[i].length) &lt;= 2 * 104\n\tAll the strings of products are unique.\n\tproducts[i] consists of lowercase English letters.\n\t1 &lt;= searchWord.length &lt;= 1000\n\tsearchWord consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n        sorted_products = sorted(products)\n        res = []\n        prefix = ''\n        for letter in searchWord:\n            prefix += letter\n            words = []\n            for product in sorted_products:\n                if len(words) == 3:\n                    break\n                if product.startswith(prefix):\n                    words.append(product)\n            res.append(words)        \n        return res",
        "solution_js": "function TrieNode(key) {\n  this.key = key\n  this.parent = null\n  this.children  = {}\n  this.end = false\n  \n  this.getWord = function() {\n    let output = []\n    let node = this\n    \n    while(node !== null) {\n      output.unshift(node.key)\n      node = node.parent\n    }\n    \n    return output.join('')\n  }\n} \n\nfunction Trie() {\n  this.root = new TrieNode(null)\n  \n  this.insert = function(word) {\n    let node = this.root\n    \n    for (let i = 0; i < word.length; i++) {\n      if (!node.children[word[i]]) {\n        node.children[word[i]] = new TrieNode(word[i])\n        node.children[word[i]].parent = node\n      }\n      \n      node = node.children[word[i]]\n      \n      if (i === word.length - 1) {\n        node.end = true\n      }\n    }\n  }\n  \n  this.findAllWords = function (node, arr) {\n    if (node.end) {\n      arr.unshift(node.getWord());\n    }\n\n    for (let child in node.children) {\n      this.findAllWords(node.children[child], arr);\n    }\n  }\n  \n  this.find  = function(prefix) {\n    let node = this.root\n    let output = []\n\n    for(let i = 0; i < prefix.length; i++) {\n      if (node.children[prefix[i]]) {\n        node = node.children[prefix[i]]\n      } else {\n        return output\n      }\n    }\n\n    this.findAllWords(node, output)\n    \n    output.sort()\n\n    return output.slice(0, 3)\n  }\n  \n  this.search = function(word) {\n    let node = this.root\n    let output = []\n    \n    for (let i = 0; i < word.length; i++) {\n      output.push(this.find(word.substring(0, i + 1)))\n    }\n    \n    return output\n  }\n}\n\n/**\n * @param {string[]} products\n * @param {string} searchWord\n * @return {string[][]}\n */\nvar suggestedProducts = function(products, searchWord) {\n  let trie = new Trie()\n  \n  for (let product of products) {\n    trie.insert(product)\n  }\n  \n  return trie.search(searchWord)\n};",
        "solution_java": "class Solution\n{\n    public List<List<String>> suggestedProducts(String[] products, String searchWord)\n    {\n        PriorityQueue<String> pq= new PriorityQueue<String>();\n        List<List<String>> res= new LinkedList<List<String>>();\n        List<String> segment= new LinkedList<String>();\n        for(int i=0;i<products.length;i++)\n            pq.offer(products[i]);\n\n        for(int j=0;j<searchWord.length();j++)\n        {\n            segment= new LinkedList<String>();\n            pq= reduce(pq,searchWord.substring(0,j+1));\n            PriorityQueue<String> pri= new PriorityQueue<>(pq);\n            int p=0;\n            while(p<pq.size()&&p<3)\n            {\n                segment.add(pri.poll());\n                p++;\n            }\n            res.add(segment);\n        }\n        return res;\n    }\n    public PriorityQueue<String> reduce(PriorityQueue<String> pr, String filter)\n    {\n        PriorityQueue<String> p= new PriorityQueue<>();\n        String s=\"\";\n        while(!pr.isEmpty())\n        {\n            s=pr.poll();\n            if(s.startsWith(filter))\n                p.add(s);\n        }\n        return p;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n        map<int, vector<string>> m;\n        vector<vector<string>> res;\n        for (int i = 0; i < products.size(); i++)\n        {\n            int j = 0;\n            while (products[i][j] == searchWord[j] && j < searchWord.size())\n            {\n                if (m.count(j) == 0)\n                {\n                    vector<string> v;\n                    v.push_back(products[i]);\n                    m.insert(make_pair(j, v));\n                }\n                else\n                {\n                    m[j].push_back(products[i]);\n                }\n                j++;\n            }\n        }\n        for (int i = 0; i < searchWord.size(); i++)\n        {\n            if (i < m.size())\n            {\n                sort(m[i].begin(), m[i].end());\n                int a;\n                if (3 <= m[i].size())\n                {\n                    a = 3;\n                }\n                else\n                {\n                    a = m[i].size();\n                }\n                m[i].resize(a);\n                res.push_back(m[i]);\n            }\n            else\n            {\n                res.push_back({});\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Check if the Sentence Is Pangram",
        "algo_input": "A pangram is a sentence where every letter of the English alphabet appears at least once.\n\nGiven a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: sentence = \"thequickbrownfoxjumpsoverthelazydog\"\nOutput: true\nExplanation: sentence contains at least one of every letter of the English alphabet.\n\n\nExample 2:\n\nInput: sentence = \"leetcode\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentence.length &lt;= 1000\n\tsentence consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def checkIfPangram(self, sentence: str) -> bool:\n        return len(set(sentence))==26",
        "solution_js": "var checkIfPangram = function(sentence) {\n    return new Set(sentence.split(\"\")).size == 26;\n};",
        "solution_java": "class Solution {\n    public boolean checkIfPangram(String sentence) {\n        int seen = 0;\n        for(char c : sentence.toCharArray()) {\n            int ci = c - 'a';\n            seen = seen | (1 << ci);\n        }\n        return seen == ((1 << 26) - 1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkIfPangram(string sentence) {\n        vector<int> v(26,0);\n        for(auto x:sentence)\n        {\n            v[x-'a'] = 1;\n        }\n        return accumulate(begin(v),end(v),0) == 26;\n    }\n};"
    },
    {
        "title": "Alphabet Board Path",
        "algo_input": "On an alphabet board, we start at position (0, 0), corresponding to character&nbsp;board[0][0].\n\nHere, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"], as shown in the diagram below.\n\n\n\nWe may make the following moves:\n\n\n\t'U' moves our position up one row, if the position exists on the board;\n\t'D' moves our position down one row, if the position exists on the board;\n\t'L' moves our position left one column, if the position exists on the board;\n\t'R' moves our position right one column, if the position exists on the board;\n\t'!'&nbsp;adds the character board[r][c] at our current position (r, c)&nbsp;to the&nbsp;answer.\n\n\n(Here, the only positions that exist on the board are positions with letters on them.)\n\nReturn a sequence of moves that makes our answer equal to target&nbsp;in the minimum number of moves.&nbsp; You may return any path that does so.\n\n&nbsp;\nExample 1:\nInput: target = \"leet\"\nOutput: \"DDR!UURRR!!DDD!\"\nExample 2:\nInput: target = \"code\"\nOutput: \"RR!DDRR!UUL!R!\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target.length &lt;= 100\n\ttarget consists only of English lowercase letters.\n",
        "solution_py": "class Solution:\n    def alphabetBoardPath(self, target: str) -> str:\n        def shortestPath(r,c,tr,tc):\n            path = \"\"\n            pr = r\n            while r > tr:\n                path += 'U'\n                r -= 1\n            while r < tr:\n                path += 'D'\n                r += 1\n            if tr == 5 and pr != tr: path = path[:len(path) - 1]\n            while c > tc:\n                path += 'L'\n                c -= 1\n            while c < tc:\n                path += 'R'\n                c += 1\n            if tr == 5 and pr != tr: path = path + 'D'\n            return path\n\n        table = ['abcde','fghij','klmno','pqrst','uvwxy','z']\n        r,c = 0,0\n        ans = \"\"\n        for character in target:\n            t_row = None\n            for i,word in enumerate(table):\n                if character in word:\n                    t_row = i\n                    break\n            t_col = table[i].index(character)\n            ans += shortestPath(r,c,t_row,t_col) + '!'\n            r,c = t_row,t_col\n        return ans",
        "solution_js": "var alphabetBoardPath = function(target) {\n    var result = \"\";\n    var list = \"abcdefghijklmnopqrstuvwxyz\";\n    var curr = 0;\n    for(i=0;i<target.length;i++){ \n          let next = list.indexOf(target[i]);\n          if(next!==curr){   \n              if(curr===25) curr-=5, result+=\"U\";\n              if(next%5!==curr%5){  \n                 diff = next%5-curr%5;\n                 if(diff>0) curr+=diff, result+=\"R\".repeat(diff);\n                 else curr+=diff, result+=\"L\".repeat(-diff);  \n             }\n             diff = (next-curr)/5;\n             if(diff>0) curr+=diff*5, result+=\"D\".repeat(diff);\n             else curr+=diff*5, result+=\"U\".repeat(-diff);     \n          }\n    result+='!';\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public String alphabetBoardPath(String target) {\n        int x = 0, y = 0;\n        StringBuilder sb = new StringBuilder();\n        for(int i = 0; i < target.length(); i++){\n            char ch = target.charAt(i);\n            int x1 = (ch - 'a') / 5;\n            int y1 = (ch - 'a') % 5;\n            while(x1 < x)   {x--; sb.append('U');}\n            while(y1 > y)   {y++; sb.append('R');}\n            while(y1 < y)   {y--; sb.append('L');}\n            while(x1 > x)   {x++; sb.append('D');}\n            sb.append('!');\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string alphabetBoardPath(string target) {\n        string ans = \"\";\n        int prevRow = 0;\n        int prevCol = 0;\n        int curRow = 0;\n        int curCol = 0;\n        for(int i = 0; i < target.length(); i++){\n            prevCol = curCol;\n            prevRow = curRow;\n            curRow = (target[i] - 'a')/5;\n            curCol = (target[i] - 'a')%5;\n            if(curRow == 5 and abs(curCol - prevCol) > 0){\n                curRow--;\n            }\n            if(curRow - prevRow > 0){\n                ans += string((curRow - prevRow), 'D');\n            }else{\n                ans += string((prevRow - curRow), 'U');\n            }\n            if(curCol - prevCol > 0){\n                ans += string((curCol - prevCol), 'R');\n            }else{\n                ans += string((prevCol - curCol), 'L');\n            }\n            if(((target[i] - 'a')/5) == 5 and abs(curCol - prevCol) > 0){\n                ans += 'D';\n                curRow++;\n            }\n            ans += '!';\n        }\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Maximum Number of Ways to Partition an Array",
        "algo_input": "You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:\n\n\n\t1 &lt;= pivot &lt; n\n\tnums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]\n\n\nYou are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.\n\nReturn the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,-1,2], k = 3\nOutput: 1\nExplanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\n\n\nExample 2:\n\nInput: nums = [0,0,0], k = 1\nOutput: 2\nExplanation: The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\n\n\nExample 3:\n\nInput: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput: 4\nExplanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t2 &lt;= n &lt;= 105\n\t-105 &lt;= k, nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def waysToPartition(self, nums: List[int], k: int) -> int:\n        prefix_sums = list(accumulate(nums))\n        total_sum = prefix_sums[-1]\n        best = 0\n        if total_sum % 2 == 0:\n            best = prefix_sums[:-1].count(total_sum // 2) # If no change\n\n        after_counts = Counter(total_sum - 2 * prefix_sum\n                               for prefix_sum in prefix_sums[:-1])\n        before_counts = Counter()\n\n        best = max(best, after_counts[k - nums[0]]) # If we change first num\n\n        for prefix, x in zip(prefix_sums, nums[1:]):\n            gap = total_sum - 2 * prefix\n            after_counts[gap] -= 1\n            before_counts[gap] += 1\n\n            best = max(best, after_counts[k - x] + before_counts[x - k])\n\n        return best",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar waysToPartition = function(nums, k) {\n    let totalSum=nums.reduce((acc, curr) => acc+curr)\n    let left=0;\n    let rightDiff={}\n    let leftDiff={}\n    \n    for(let i=0; i<nums.length-1; i++) {\n        left+=nums[i]\n        const right=totalSum-left\n        if(rightDiff[left-right]) rightDiff[left-right]++\n        else rightDiff[left-right]=1\n    }\n\n    let maxPartition=rightDiff[0] ? rightDiff[0] : 0\n    left=0\n    for(let i=0; i<nums.length; i++) {\n        left+=nums[i]\n        let diff=k-nums[i]\n        const right=totalSum-left\n        let leftVal=leftDiff[`${diff}`] ? leftDiff[`${diff}`] : 0\n        let rightVal=rightDiff[`${-diff}`] ? rightDiff[`${-diff}`] : 0\n        \n        maxPartition=Math.max(maxPartition, leftVal+rightVal)\n        if(leftDiff[left-right]) leftDiff[left-right]++\n        else leftDiff[left-right]=1\n        \n        rightDiff[left-right]--\n\n    }\n    \n    return maxPartition\n\n};\n```",
        "solution_java": "class Solution {\n    //time - O(n), space - O(n)\n    public int waysToPartition(int[] nums, int k) {\n        int n = nums.length;\n\n        int[] pref = new int[n];\n        pref[0] = nums[0];\n        Map<Integer, Integer> count = new HashMap<>(); //contribution of prefixes without changing\n        count.put(pref[0], 1);\n\n        for (int i = 1; i < n - 1; i++){\n            pref[i] += pref[i - 1] + nums[i];\n            count.put(pref[i], count.getOrDefault(pref[i], 0) + 1);\n        }\n        pref[n - 1] += pref[n - 2] + nums[n - 1]; //last step doesn't add into 'count' map, because we're trying to find at least two parts.\n\n        int sum = pref[n - 1];\n        int max = 0;\n        if (sum % 2 == 0)\n            max = count.getOrDefault(sum / 2, 0); //max without changing\n\n        Map<Integer, Integer> countPrev = new HashMap<>(); //contribution of prefixes before current step\n        for (int i = 0; i < n; i++){\n            int diff = k - nums[i];\n            int changedSum = sum + diff;\n            if (changedSum % 2 == 0)\n                max = Math.max(max, count.getOrDefault(changedSum / 2 - diff, 0) + countPrev.getOrDefault(changedSum / 2, 0));\n            count.put(pref[i], count.getOrDefault(pref[i], 0) - 1);\n            countPrev.put(pref[i], countPrev.getOrDefault(pref[i], 0) + 1);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int waysToPartition(vector<int>& nums, int k) {\n        unordered_map<long long int,int> left;\n        unordered_map<long long int,int> right;\n\n        long long int sum=accumulate(nums.begin(),nums.end(),0L);\n        long long int leftSum=0;\n        int n=nums.size();\n\n        for(int i=0;i<n-1;i++){\n            leftSum+=nums[i];\n            long long int rightSum=sum-leftSum;\n            long long int difference=leftSum-rightSum;\n            right[difference]++; //storing difference count in right, since no difference exist in left\n        }\n\n        int res=right[0]; // Point Zero difference are the partition points\n        leftSum=0;\n        for(int i=0;i<n;i++){\n            long long int D=k-nums[i];\n            res=max(res,right[-D]+left[D]); // We can run a few test cases and see that if we replace arr[i] by k, the difference D, the left side including i,each element decreases by D while the right Side each element increases by D, so we find -D on right Side... WHY?? if right side is increasing by D, we need to find -D since this will result in -D+D=0, which are our partition points, since point 0 signifies a partition where leftSum==rightSum, similarly, left side decreases by D, so we find +D on left since this will result in zero as well.\n\n            leftSum+=nums[i];\n            long long int rightSum=sum-leftSum;\n            left[leftSum-rightSum]++; //Now since we are moving our i forward, we are gonna change the next i point, so we are placing leftSum-RightSum on left side\n            right[leftSum-rightSum]--; // From right we are gonna decrease it and transfer to left side\n            if(right[leftSum-rightSum]==0){\n                right.erase(leftSum-rightSum);\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Path Sum III",
        "algo_input": "Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values&nbsp;along the path equals&nbsp;targetSum.\n\nThe path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).\n\n&nbsp;\nExample 1:\n\nInput: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput: 3\nExplanation: The paths that sum to 8 are shown.\n\n\nExample 2:\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 1000].\n\t-109 &lt;= Node.val &lt;= 109\n\t-1000 &lt;= targetSum &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:\n        def util(node: TreeNode, sum_array) -> int:\n            t = [e - node.val for e in sum_array]\n            zeroes = t.count(0)\n            if node.left is None and node.right is None:\n                return zeroes\n            ansl, ansr = 0, 0\n            if node.left:\n                ansl = util(node.left, t + [targetSum])\n            if node.right:\n                ansr = util(node.right, t + [targetSum])\n            return ansl + ansr + zeroes\n\n        return util(root, [targetSum]) if root is not None else 0",
        "solution_js": "var pathSum = function(root, targetSum) {\nlet count = 0;\n\nlet hasSum = (node, target) => { //helper function, calculates number of paths having sum equal to target starting from given node\n    if(node===null){// base case\n        return;\n    }\n    if(node.val===target){// if at any point path sum meets the requirement\n        count++;\n    }\n    //recursive call\n    hasSum(node.left, target-node.val);\n    hasSum(node.right, target-node.val);\n}\n\nlet dfs = (node) => {//dfs on every node and find sum equal to target starting from every node\n    if(node===null)\n        return;\n    dfs(node.left);\n    dfs(node.right);\n    hasSum(node,targetSum);// find sum of path starting on this point\n}\n\ndfs(root);\n\nreturn count;\n};",
        "solution_java": "class Solution {\n    public int pathSum(TreeNode root, int targetSum) {\n        HashMap<Long, Integer> hm = new HashMap<>();\n        //hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum\n\n        int res = solve(hm, root, targetSum, 0);\n\n        return res;\n    }\n\n    public int solve(HashMap<Long, Integer> hm, TreeNode node, long tgt, long c_sum) {\n\n        if(node == null)\n            return 0;\n\n        c_sum += node.val;\n\n        int res = 0;\n\n        if(c_sum == tgt) //--> either this condition or the above commented condition.\n            res++;\n\n        if(hm.containsKey(c_sum-tgt)){\n            res += hm.get(c_sum-tgt);\n        }\n\n        hm.put(c_sum, hm.getOrDefault(c_sum,0)+1);\n\n        int left = solve(hm, node.left, tgt, c_sum);\n        int right = solve(hm, node.right, tgt, c_sum);\n\n        res += (left+right);\n\n        hm.put(c_sum, hm.getOrDefault(c_sum,0)-1); //remove the calculated cumulative sum\n\n        return res;\n\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = 0,t;\n    \n    void dfs(unordered_map<long long,int> &curr,TreeNode* node,long long sm){\n        \n        if(!node){\n            return;\n        }\n                \n        sm += (long long) node->val;\n        ans += curr[sm-t];\n        curr[sm]++;\n                \n        dfs(curr,node->left,sm);\n        dfs(curr,node->right,sm);\n        \n        curr[sm]--;\n    }\n    int pathSum(TreeNode* root, int targetSum) {\n        if(!root){\n            return 0;\n        }\n        \n        t = targetSum;\n        unordered_map<long long,int> curr;\n        curr[0] = 1;\n        long long sm = 0;\n        \n        dfs(curr,root,sm);\n\n        return ans;\n    }\n};"
    },
    {
        "title": "The k-th Lexicographical String of All Happy Strings of Length n",
        "algo_input": "A happy string is a string that:\n\n\n\tconsists only of letters of the set ['a', 'b', 'c'].\n\ts[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).\n\n\nFor example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\n\nGiven two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\n\nReturn the kth string of this list or return an empty string if there are less than k happy strings of length n.\n\n&nbsp;\nExample 1:\n\nInput: n = 1, k = 3\nOutput: \"c\"\nExplanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\n\n\nExample 2:\n\nInput: n = 1, k = 4\nOutput: \"\"\nExplanation: There are only 3 happy strings of length 1.\n\n\nExample 3:\n\nInput: n = 3, k = 9\nOutput: \"cab\"\nExplanation: There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9th string = \"cab\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 10\n\t1 &lt;= k &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def getHappyString(self, n: int, k: int) -> str:\n        ans = []\n        letters = ['a','b','c']\n        def happystr(n,prev,temp):\n            if n==0:\n                ans.append(\"\".join(temp))\n                return \n            for l in letters: \n                if l!=prev: \n                    happystr(n-1,l,temp+[l])\n        happystr(n,\"\",[])\n        if len(ans)<k:\n            return \"\"\n        return ans[k-1]\n            \n            ",
        "solution_js": "var getHappyString = function(n, k) {\n    const arr = ['a','b','c'], finalArr = ['a','b','c'];\n    let chr = '', str = '';\n    if(finalArr[finalArr.length-1].length === n && finalArr[0].length === n ) {\n        return finalArr[k-1] && finalArr[k-1].length === n ? finalArr[k-1] : '';\n    }\n    for(; finalArr.length < k || finalArr[0].length <= n;) {\n        str = finalArr.shift();\n        for(let index2 = 0; index2 < 3; index2++){\n            chr = str[str.length-1];\n            if(chr !== arr[index2]) {\n                finalArr.push(str+arr[index2]);\n            }\n        }\n        if(finalArr[finalArr.length-1].length === n && finalArr[0].length === n ) break;\n    }\n    return finalArr[k-1] ? finalArr[k-1] : '';\n};",
        "solution_java": "class Solution {\n\n public String getHappyString(int n, int k) {\n        List<String> innerList = new ArrayList<>();\n        getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList);\n        if (innerList.size() < k)\n            return \"\";\n        return innerList.get(k - 1);\n    }\n\n    public void getHappyStringUtil(int n, int k, char[] letter, StringBuilder tempString, List<String> innerList) {\n        // Base case\n        if (tempString.length() == n) {\n            innerList.add(tempString.toString());\n            return;\n        }\n\n        // Recursive call\n        for (int i = 0; i < 3; i++) {\n            if (tempString.length() > 0 && tempString.charAt(tempString.length() - 1) == letter[i])\n                continue;\n            tempString.append(letter[i]);\n            getHappyStringUtil(n, k, letter, tempString, innerList);\n            tempString.deleteCharAt(tempString.length() - 1);\n        }\n\n    }\n}",
        "solution_c": "class Solution {\n    private:\n    void happy(string s, vector<char> &v, int n, vector<string> &ans){\n        if(s.size() == n){\n            ans.push_back(s);\n            return;\n        }\n        for(int i=0; i<3; i++){\n            if(s.back() != v[i]){\n                s.push_back(v[i]);\n                happy(s,v,n,ans);\n                s.pop_back();\n            }\n        }\n    }\npublic:\n    string getHappyString(int n, int k) {\n        vector<char> v = {'a', 'b', 'c'};\n        vector<string> ans;\n        string s = \"\";\n        happy(s,v,n,ans);\n        if(ans.size() < k){\n            return \"\";\n        }\n        else{\n            return ans[k-1];\n        }\n    }\n};"
    },
    {
        "title": "Vowel Spellchecker",
        "algo_input": "Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.\n\nFor a given query word, the spell checker handles two categories of spelling mistakes:\n\n\n\tCapitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.\n\n\t\n\t\tExample: wordlist = [\"yellow\"], query = \"YellOw\": correct = \"yellow\"\n\t\tExample: wordlist = [\"Yellow\"], query = \"yellow\": correct = \"Yellow\"\n\t\tExample: wordlist = [\"yellow\"], query = \"yellow\": correct = \"yellow\"\n\t\n\t\n\tVowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.\n\t\n\t\tExample: wordlist = [\"YellOw\"], query = \"yollow\": correct = \"YellOw\"\n\t\tExample: wordlist = [\"YellOw\"], query = \"yeellow\": correct = \"\" (no match)\n\t\tExample: wordlist = [\"YellOw\"], query = \"yllw\": correct = \"\" (no match)\n\t\n\t\n\n\nIn addition, the spell checker operates under the following precedence rules:\n\n\n\tWhen the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\n\tWhen the query matches a word up to capitlization, you should return the first such match in the wordlist.\n\tWhen the query matches a word up to vowel errors, you should return the first such match in the wordlist.\n\tIf the query has no matches in the wordlist, you should return the empty string.\n\n\nGiven some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].\n\n&nbsp;\nExample 1:\nInput: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\nExample 2:\nInput: wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput: [\"yellow\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= wordlist.length, queries.length &lt;= 5000\n\t1 &lt;= wordlist[i].length, queries[i].length &lt;= 7\n\twordlist[i] and queries[i] consist only of only English letters.\n\n",
        "solution_py": "class Solution:\n    def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n        n = len(wordlist)\n        d = {}\n        sd = {}\n        vd = {}\n        cd = {}\n        for i in range(n):\n            d[wordlist[i]] = i\n            s = wordlist[i].lower()\n            if s not in sd:sd[s] = i \n            m = len(wordlist[i])\n            tmp = []\n            emp = \"\"\n            for j in range(m):\n                if wordlist[i][j] in 'aeiouAEIOU': tmp.append(j)\n                else:emp+=wordlist[i][j].lower()\n            cd[i] = emp\n            vd[i] = tmp\n            \n        ans = []\n        for word in queries:\n            word_lower = word.lower()\n            if word in d: \n                ans.append(word)\n                continue            \n            elif word_lower in sd:\n                ans.append(wordlist[sd[word_lower]])\n                continue\n            else:\n                vow_word = []\n                con_word = \"\" \n                m = len(word)\n                for i in range(m):\n                    if word[i] in 'aeiouAEIOU' : vow_word.append(i)\n                    else: con_word += word[i].lower()\n                if vow_word == []:\n                    ans.append(\"\")\n                    continue\n                    \n                flag = False\n                for i in range(n):\n                    vow_tmp = vd[i]\n                    con_tmp = cd[i]\n                    if vow_tmp == vow_word and con_tmp == con_word:\n                        ans.append(wordlist[i])\n                        flag = True\n                        break\n                if flag == True:continue\n                ans.append(\"\")\n        return ans",
        "solution_js": "var spellchecker = function(wordlist, queries) {\n  const baseList = new Set(wordlist.reverse());\n  const loweredList = wordlist.reduce((map, word) => (map[normalize(word)] = word, map), {});\n  const replacedList = wordlist.reduce((map, word) => (map[repVowels(word)] = word, map), {});\n  return queries.map(word => (\n    baseList.has(word) && word    ||\n\tloweredList[normalize(word)]  ||\n\treplacedList[repVowels(word)] ||\n\t''\n  ));\n};\nvar normalize = function(word) { return word.toLowerCase() };\nvar repVowels = function(word) { return normalize(word).replace(/[eiou]/g, 'a') };",
        "solution_java": "class Solution {\n    public String[] spellchecker(String[] wordlist, String[] queries) {\n        String[] ans = new String[queries.length];\n        Map<String, String>[] map = new HashMap[3];\n        Arrays.setAll(map, o -> new HashMap<>());\n        String pattern = \"[aeiou]\";\n\n        for (String w : wordlist){\n            String lo = w.toLowerCase();\n            map[0].put(w, \"\");\n            map[1].putIfAbsent(lo, w);\n            map[2].putIfAbsent(lo.replaceAll(pattern, \".\"), map[1].getOrDefault(w, w));\n        }\n\n        int i = 0;\n        for (String q : queries){\n            String lo = q.toLowerCase();\n            String re = lo.replaceAll(pattern, \".\");\n            if (map[0].containsKey(q)){\n                ans[i] = q;\n            }else if (map[1].containsKey(lo)){\n                ans[i] = map[1].get(lo);\n            }else if (map[2].containsKey(re)){\n                ans[i] = map[2].get(re);\n            }else{\n                ans[i] = \"\";\n            }\n            i++;\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {\n        unordered_map<string, vector<int>> umap;\n\n        // step 1: add info in umap;\n        for(int curr = 0; curr < wordlist.size(); curr++){\n            // case 1: add same;\n            umap[wordlist[curr]].push_back({curr});\n            // notice that the lowercase may appear;\n\n            // case 2: add lowercase;\n            string tmp = wordlist[curr];\n            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\n            if(umap.find(tmp) == umap.end() && tmp != wordlist[curr]) umap[tmp].push_back({curr});\n\n            // case 3: add vowel errors;\n            // convert aeiou to _;\n            for(int c_index = 0; c_index < tmp.size(); c_index++){\n                char c = tmp[c_index];\n                if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_';\n            }\n\n            if(umap.find(tmp) == umap.end()) umap[tmp].push_back({curr});\n        }\n\n        // step 2: convert queries;\n        for(int curr = 0; curr < queries.size(); curr++){\n            string tmp = queries[curr];\n            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\n            // case 1: check same;\n            if(umap.find(queries[curr]) != umap.end()){\n                queries[curr] = (umap[queries[curr]].size() == 1) ? wordlist[umap[queries[curr]][0]] : wordlist[umap[queries[curr]][1]];\n                continue;\n            }\n\n            // case 2: check lowercase;\n            if(umap.find(tmp) != umap.end() && tmp != queries[curr]){\n                queries[curr] = wordlist[umap[tmp][0]];\n                continue;\n            }\n\n            // case 3: check vowel errors;\n            // convert aeiou to _;\n            for(int c_index = 0; c_index < tmp.size(); c_index++){\n                char c = tmp[c_index];\n                if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_';\n            }\n\n            if(umap.find(tmp) != umap.end()){\n                queries[curr] = wordlist[umap[tmp][0]];\n                continue;\n            }\n\n            // case 4: not found;\n            queries[curr] = \"\";\n        }\n\n        return queries;\n    }\n};\n\n// 1. When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\n// 2. When the query matches a word up to capitlization, you should return the first such match in the wordlist.\n// 3. When the query matches a word up to vowel errors, you should return the first such match in the wordlist.\n// 4. If the query has no matches in the wordlist, you should return the empty string."
    },
    {
        "title": "Bulb Switcher",
        "algo_input": "There are n bulbs that are initially off. You first turn on all the bulbs, then&nbsp;you turn off every second bulb.\n\nOn the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.\n\nReturn the number of bulbs that are on after n rounds.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 1\nExplanation: At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.\n\nExample 2:\n\nInput: n = 0\nOutput: 0\n\n\nExample 3:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def bulbSwitch(self, n: int) -> int:\n        return int(sqrt(n))",
        "solution_js": "var bulbSwitch = function(n) {\n    return Math.floor(Math.sqrt(n));\n};",
        "solution_java": "\tclass Solution {\n    public int bulbSwitch(int n) {\n        return (int)Math.sqrt(n);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int bulbSwitch(int n) {\n        return sqrt(n);\n    }\n};"
    },
    {
        "title": "Latest Time by Replacing Hidden Digits",
        "algo_input": "You are given a string time in the form of  hh:mm, where some of the digits in the string are hidden (represented by ?).\n\nThe valid times are those inclusively between 00:00 and 23:59.\n\nReturn the latest valid time you can get from time by replacing the hidden digits.\n\n&nbsp;\nExample 1:\n\nInput: time = \"2?:?0\"\nOutput: \"23:50\"\nExplanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\n\n\nExample 2:\n\nInput: time = \"0?:3?\"\nOutput: \"09:39\"\n\n\nExample 3:\n\nInput: time = \"1?:22\"\nOutput: \"19:22\"\n\n\n&nbsp;\nConstraints:\n\n\n\ttime is in the format hh:mm.\n\tIt is guaranteed that you can produce a valid time from the given string.\n\n",
        "solution_py": "class Solution:\ndef maximumTime(self, time: str) -> str:\n    memo = {\"0\":\"9\",\n            \"1\":\"9\",\n            \"?\":\"3\", \n            \"2\":\"3\"}\n    \n    answer = \"\"\n    for idx, val in enumerate(time):\n        if val == \"?\":\n            if idx == 0:\n                if time[idx+1] == \"?\":\n                    answer += \"2\"\n                    \n                else:\n                    if int(time[idx+1]) >= 4:\n                        answer += \"1\"\n                \n                    else: answer += \"2\"\n                \n            if idx == 1:\n                answer += memo[time[idx-1]]\n            \n            if idx == 3:\n                answer += \"5\"   \n                \n            if idx == 4:\n                answer += \"9\"\n        \n        else:\n            answer += val\n    \n    return answer",
        "solution_js": "var maximumTime = function(time) {\n    time = time.split('')\n    if (time[0] === \"?\") time[0] = time[1] > 3 ? \"1\" : \"2\"\n    if (time[1] === \"?\") time[1] = time[0] > 1 ? \"3\" : \"9\"\n    if (time[3] === \"?\") time[3] = \"5\"\n    if (time[4] === \"?\") time[4] = \"9\"\n    return time.join('')\n};",
        "solution_java": "class Solution {\n    public String maximumTime(String time) {\n        char[] times = time.toCharArray();\n        //for times[0]\n        //if both characters of hour is ?, then hour is 23 then times[0] should be '2'(\"??:3?)\".\n        //if 2nd character of hour is <= 3, then hour can be in 20s  then times[0] should be '2'.\n        //if 2nd character of hour is >3, then hour can only be in 10s  then times[0] should be '1'.\n        if(times[0]=='?')\n            times[0]= (times[1]<='3' || times[1]=='?') ? '2' : '1';\n        //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then times[1] should be '9'.\n        //if 1st character of hour is 2, then hour can be 23 then times[1] should be '3'.\n        if(times[1]=='?')\n            times[1]= times[0]=='2' ? '3' : '9';\n        //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so times[3] is always '5'.\n        if(times[3]=='?')\n            times[3]='5';\n        //if 2nd character of minute is ?, then times[4] is '9'.\n        if(times[4]=='?')\n            times[4]='9';\n        return new String(times);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string maximumTime(string time) {\n        //for time[0]\n        //if both characters of hour is ?, then hour is 23 then time[0] should be '2'(\"??:3?)\".\n        //if 2nd character of hour is <= 3, then hour can be in 20s  then time[0] should be '2'.\n        //if 2nd character of hour is >3, then hour can only be in 10s  then time[0] should be '1'.\n        if(time[0]=='?')\n            time[0]= (time[1]<='3' || time[1]=='?') ? '2' : '1';\n        //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then time[1] should be '9'.\n        //if 1st character of hour is 2, then hour can be 23 then time[1] should be '3'.\n        if(time[1]=='?')\n            time[1]= time[0]=='2' ? '3' : '9';\n        //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so time[3] is always '5'.\n        if(time[3]=='?')\n            time[3]='5';\n        //if 2nd character of minute is ?, then time[4] is '9'.\n        if(time[4]=='?')\n            time[4]='9';\n        return time;\n    }\n};"
    },
    {
        "title": "Fraction Addition and Subtraction",
        "algo_input": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.\n\nThe final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.\n\n&nbsp;\nExample 1:\n\nInput: expression = \"-1/2+1/2\"\nOutput: \"0/1\"\n\n\nExample 2:\n\nInput: expression = \"-1/2+1/2+1/3\"\nOutput: \"1/3\"\n\n\nExample 3:\n\nInput: expression = \"1/3-1/2\"\nOutput: \"-1/6\"\n\n\n&nbsp;\nConstraints:\n\n\n\tThe input string only contains '0' to '9', '/', '+' and '-'. So does the output.\n\tEach fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.\n\tThe input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.\n\tThe number of given fractions will be in the range [1, 10].\n\tThe numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.\n\n",
        "solution_py": "\"\"\"\napproach:\nfirst replace - with +- in the string so that implementation gets\na little easy\n\"\"\"\nclass Solution:\n    def fractionAddition(self, expression: str) -> str:\n        expression = expression.replace('-', '+-')\n        parts = [item for item in expression.split('+') if item != '']\n        numes, denoms, denom_set, lcm = [], [], set(), 1\n        def get_lcm(a, b):\n            if a == 1:\n                return b\n            if b == 1:\n                return a\n            if a < b:\n                if b % a == 0:\n                    return a * get_lcm(1, b/a)\n                else:\n                    return a * get_lcm(1, b)\n            else:\n                if a % b == 0:\n                    return b * get_lcm(a/b, 1)\n                else:\n                    return b * get_lcm(a, 1)\n\n        for part in parts:\n            num, den = part.split('/')\n            numes.append(int(num))\n            denoms.append(int(den))\n            lcm = get_lcm(lcm, int(den))\n\n        result = 0\n        for num, den in zip(numes, denoms):\n             result +=num * int(lcm/den)\n\n        def get_gcd(a, b):\n            if a == 0:\n                return b\n            if b == 0:\n                return a\n            if a == b:\n                return a\n            elif a < b:\n                return get_gcd(a, b-a)\n            else:\n                return get_gcd(a-b, b)\n\n        gcd = get_gcd(abs(result), lcm)\n        return str(int(result/gcd)) + '/' + str(int(lcm/gcd))",
        "solution_js": "var fractionAddition = function(expression) {\n\tconst fractions = expression.split(/[+-]/).filter(Boolean);\n\tconst operator = expression.split(/[0-9/]/).filter(Boolean);\n\texpression[0] !== '-' && operator.unshift('+');\n\n\tconst gcd = (a, b) => b === 0 ? a : gcd(b, a % b);\n\tconst lcm = fractions.reduce((result, fraction) => {\n\t\tconst denominator = fraction.split('/')[1];\n\t\treturn result * denominator / gcd(result, denominator);\n\t}, 1);\n\n\tconst molecularSum = fractions.reduce((total, fraction, index) => {\n\t\tconst [molecular, denominator] = fraction.split('/');\n\t\tconst multiple = lcm / denominator * (operator[index] === '+' ? 1 : -1);\n\t\treturn total + molecular * multiple;\n\t}, 0);\n\n\tconst resultGcd = gcd(Math.abs(molecularSum), lcm);\n\treturn `${molecularSum / resultGcd}/${lcm / resultGcd}`;\n};",
        "solution_java": "class Solution {\n    private int gcd(int x, int y){\n        return x!=0?gcd(y%x, x):Math.abs(y);\n    }\n\n    public String fractionAddition(String exp) {\n        Scanner sc = new Scanner(exp).useDelimiter(\"/|(?=[-+])\");\n\n        int A=0, B=1;\n        while(sc.hasNext()){\n            int a = sc.nextInt(), b=sc.nextInt();\n            A = A * b + B * a;\n            B *= b;\n\n            int gcdX = gcd(A, B);\n            A/=gcdX;\n            B/=gcdX;\n        }\n        return A+\"/\"+B;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string fractionAddition(string expression) {\n        \n        int res_num = 0; //keep track of numerator\n        int res_denom = 1; //keep track of denominator\n        char sign = '+'; //keep track of sign\n\t\t\n        for(int i = 0; i < expression.size(); i++){ //parse the expression string\n            int next_num = 0;\n            int next_denom = 0;\n            if(expression[i] == '+' || expression[i] == '-') //updating\n                sign = expression[i];\n            else{\n                int j = i+1;\n                while(j < expression.size() && expression[j] != '/') j++; build next numerator\n                next_num = stoi(expression.substr(i, j-i));\n                int k = j+1;\n                while(k < expression.size() && expression[k] >= '0' && expression[k] <= '9') k++; //build next denominator\n                next_denom = stoi(expression.substr(j+1, k-(j+1)));\n                if(res_denom != next_denom){ //update result numerator and denominator\n                    res_num *= next_denom;\n                    next_num *= res_denom;\n                    res_denom *= next_denom;\n                    }\n                if(sign == '+') res_num += next_num;\n                else res_num -= next_num;\n                i = k-1;\n            }\n        }\n        return lowestFraction(res_num, res_denom); //put the fraction into lowest terms and return as string\n    }\n    \nprivate:\n    int findGCD(int a, int b) { //find Greatest Common Denominator\n        if(b == 0) return a;\n        return findGCD(b, a % b);\n   }\n    \n   string lowestFraction(int num, int denom){ //use GCD to put fraction into lowest terms and return as string\n      int gcd;\n      gcd = findGCD(num, denom);\n      num /= gcd;\n      denom /= gcd;\n       if(denom < 0){\n           denom *= -1;\n           num *= -1;\n       }\n      return to_string(num) + '/' + to_string(denom);\n}\n    \n};"
    },
    {
        "title": "Third Maximum Number",
        "algo_input": "Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,2,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.\n\n\nExample 2:\n\nInput: nums = [1,2]\nOutput: 2\nExplanation:\nThe first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.\n\n\nExample 3:\n\nInput: nums = [2,2,3,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n\n&nbsp;\nFollow up: Can you find an O(n) solution?",
        "solution_py": "class Solution:\n    def thirdMax(self, nums: List[int]) -> int:\n        nums_set = set(nums)\n        sorted_set = sorted(nums_set)\n        return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1]\n    \n    \n            #use set() to remove dups\n            #if len of nums after dups have been removed is at least 2, a third max val must exist\n            #if not, just return the max\n        \n        \n        #you can do it in 1 line like this but then you have to call the same functions repeatedly\n        #return sorted(set(nums))[-3] if len(set(nums)) > 2  else sorted(set(nums))[-1]\n    \n \n    ",
        "solution_js": "var thirdMax = function(nums) {\n    nums.sort((a,b) => b-a);\n\t//remove duplicate elements\n    for(let i=0; i<nums.length;i++){\n        if(nums[i] === nums[i+1]){\n            nums.splice(i+1, 1);\n            i--\n        }\n    }\n    \n    return nums[2] !=undefined?nums[2]: nums[0]\n};",
        "solution_java": "class Solution {\n    public int thirdMax(int[] nums) {\n        Integer first = null, second = null, third = null;\n        for(Integer num: nums){\n            if(num.equals(first) || num.equals(second) || num.equals(third)) continue;\n            if(first == null || num > first){\n                third = second;\n                second = first;\n                first = num;\n                continue;\n            } \n            if(second == null || num > second){\n                third = second;\n                second = num;\n                continue;\n            } \n            if(third == null || num > third){\n                third = num;\n            }\n        }\n        return (third != null) ? third : first;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n int thirdMax(vector<int>& nums) {\n           set<int>s;\n        for(int i=0;i<nums.size();i++){\n            s.insert(nums[i]);\n        }\n        if(s.size()>=3){   // when set size >=3 means 3rd Maximum exist(because set does not contain duplicate element)\n            int Third_index_from_last=s.size()-3;\n            auto third_maximum=next(s.begin(),Third_index_from_last);\n            return *third_maximum;\n        }\n            return *--s.end(); // return maximum if 3rd maximum not exist\n    }\n};"
    },
    {
        "title": "Get the Maximum Score",
        "algo_input": "You are given two sorted arrays of distinct integers nums1 and nums2.\n\nA valid path is defined as follows:\n\n\n\tChoose array nums1 or nums2 to traverse (from index-0).\n\tTraverse the current array from left to right.\n\tIf you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).\n\n\nThe score is defined as the sum of uniques values in a valid path.\n\nReturn the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput: 30\nExplanation: Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],  (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]    (starting from nums2)\nThe maximum is obtained with the path in green [2,4,6,8,10].\n\n\nExample 2:\n\nInput: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput: 109\nExplanation: Maximum sum is obtained with the path [1,3,5,100].\n\n\nExample 3:\n\nInput: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput: 40\nExplanation: There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 105\n\t1 &lt;= nums1[i], nums2[i] &lt;= 107\n\tnums1 and nums2 are strictly increasing.\n\n",
        "solution_py": "from itertools import accumulate\nclass Solution:\n    def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n        acc1 = list(accumulate(nums1, initial = 0))\n        acc2 = list(accumulate(nums2, initial = 0))\n        i, j = len(nums1)-1, len(nums2)-1\n        previ, prevj = len(nums1), len(nums2)\n        prev_maxscore = 0\n        while i >= 0 and j >= 0:\n            while i >= 0 and j >= 0 and nums1[i] < nums2[j]:\n                j -= 1\n            if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n                prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n                previ, prevj = i, j\n                i -= 1\n                j -= 1\n            while i >= 0 and j >= 0 and nums2[j] < nums1[i]:\n                i -= 1\n            if  i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n                prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n                previ, prevj = i, j\n                i -= 1\n                j -= 1\n        prev_maxscore += max(acc1[previ]-acc1[0], acc2[prevj]-acc2[0])\n        return prev_maxscore % (10**9 + 7)",
        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxSum = function(nums1, nums2) {\n    let MODULO_AMOUNT = 10 ** 9 + 7;\n    let result = 0;\n    let ptr1 = 0;\n    let ptr2 = 0;\n    let n1 = nums1.length;\n    let n2 = nums2.length;\n    let section_sum1 = 0;\n    let section_sum2 = 0;\n    while(ptr1 < n1 || ptr2 < n2){\n        if(ptr1 < n1 && ptr2 < n2 && nums1[ptr1] == nums2[ptr2]){\n            result += Math.max(section_sum1, section_sum2) + nums1[ptr1];\n            result %= MODULO_AMOUNT;\n            section_sum1 = 0;\n            section_sum2 = 0;\n            ptr1 += 1;\n            ptr2 += 1;\n            continue;\n        }\n\n        if(ptr1 == n1 || (ptr2 != n2 && nums1[ptr1] > nums2[ptr2])){\n            section_sum2 += nums2[ptr2];\n            ptr2 += 1;\n        }else{\n            section_sum1 += nums1[ptr1];\n            ptr1 += 1;\n        }\n    }\n    result += Math.max(section_sum1, section_sum2);\n    return result % MODULO_AMOUNT;\n};",
        "solution_java": "class Solution {\n    public int maxSum(int[] nums1, int[] nums2) {\n        long currSum = 0, sum1 = 0, sum2 = 0;\n        int i = 0;\n        int j = 0;\n        while(i < nums1.length && j < nums2.length){\n            if(nums1[i] == nums2[j]) {\n                currSum += Math.max(sum1, sum2) + nums2[j];\n                sum1 = 0;\n                sum2 = 0;\n                i++;\n                j++;\n            }\n            else if(nums1[i] < nums2[j]){\n                sum1 += nums1[i++];\n            } else {\n                sum2 += nums2[j++];\n            }\n        }\n       \n        while(i < nums1.length){\n            sum1 += nums1[i++];\n        }\n        while(j < nums2.length){\n            sum2 += nums2[j++];\n        }\n        return (int)((currSum + Math.max(sum1, sum2)) % 1000000007);\n    }\n}",
        "solution_c": "#define ll long long\nclass Solution {\npublic:\n    ll dp1[100005];\n    ll dp2[100005];\n    \n    ll mod=1e9+7;\n    \n    ll func(vector<int> &nums1 , vector<int> &nums2 , unordered_map< int , int> &mp1,\n unordered_map< int , int> &mp2 , int i1 , int i2 , int n1 , int n2 , bool f1)\n    {\n        if(i1>=n1 || i2>=n2)\n        {\n            return 0;\n        }\n        \n        ll sum1=0;\n        \n        ll sum2=0;\n        \n        ll ans=0;\n        \n        if(f1==true)\n        {\n            if(dp1[i1]!=-1)\n            {\n                return dp1[i1];\n            }\n        }\n        else\n        {\n            if(dp2[i2]!=-1)\n            {\n                return dp2[i2];\n            }\n        }\n        \n        if(f1==true)\n        {\n            sum1=(sum1 + nums1[i1]);\n            auto it=mp2.find(nums1[i1]);\n            \n            sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , i1+1 , i2 , n1 , n2 , true));\n            \n            if(it!=mp2.end())\n            {\n                int idx=mp2[nums1[i1]];\n                sum2=(sum2 + nums2[idx]);\n                \n                sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , idx+1 , n1 , n2 , false ));\n                \n            }\n            ans=max(sum1 , sum2);\n            \n            dp1[i1]=ans;\n        }\n        else\n        {\n            sum2=(sum2 + nums2[i2]);\n            auto it=mp1.find(nums2[i2]);\n            \n            sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , i2+1 , n1 , n2 , false));\n            \n            if(it!=mp1.end())\n            {\n                int idx=mp1[nums2[i2]];\n                sum1= (sum1 + nums1[idx]);\n                sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , idx+1 , i2 , n1 , n2 , true));\n            }\n            ans=max(sum1 , sum2);\n            dp2[i2]=ans;\n        }\n        \n        \n        return ans;\n        \n        \n    }\n    \n    int maxSum(vector<int>& nums1, vector<int>& nums2) {\n         \n        // at every equal value we can switch \n        \n        // the elements from array1 to array2\n        \n        unordered_map< int , int> mp1 , mp2;\n        \n        int n1=nums1.size() , n2=nums2.size();\n        \n        for(int i=0;i<nums1.size();i++)\n        {\n            mp1[nums1[i]]=i;\n        }\n        \n        for(int i=0;i<nums2.size();i++)\n        {\n            mp2[nums2[i]]=i;\n        }\n        \n        // start from both array as nums1 & nums2 , nums2 & nums1\n        \n        memset(dp1 , -1 , sizeof(dp1));\n        memset(dp2 , -1 , sizeof(dp2));\n        \n        bool f1=true;\n        \n        ll ans1=func(nums1 , nums2 , mp1 , mp2 , 0 , 0 ,n1 , n2 , f1);\n        memset(dp1 , -1 , sizeof(dp1));\n        memset(dp2 , -1 , sizeof(dp2));\n        ll ans2=func(nums2 , nums1 , mp2 , mp1 , 0 , 0 , n2 , n1 , f1);\n        \n        ans1=ans1%mod;\n        ans2=ans2%mod;\n        \n        return max(ans1 , ans2);\n        \n    }"
    },
    {
        "title": "Stream of Characters",
        "algo_input": "Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words.\n\nFor example, if words = [\"abc\", \"xyz\"]&nbsp;and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words.\n\nImplement the StreamChecker class:\n\n\n\tStreamChecker(String[] words) Initializes the object with the strings array words.\n\tboolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]\nOutput\n[null, false, false, false, true, false, true, false, false, false, false, false, true]\n\nExplanation\nStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 2000\n\t1 &lt;= words[i].length &lt;= 200\n\twords[i] consists of lowercase English letters.\n\tletter is a lowercase English letter.\n\tAt most 4 * 104 calls will be made to query.\n\n",
        "solution_py": "class TrieNode:\n    \n    def __init__(self):\n        self.children = {}\n        self.endOfWord = False\n\nclass StreamChecker:\n\n    def __init__(self, words: List[str]):\n        self.root = TrieNode()\n        self.qCur = self.root\n        self.stream = collections.deque()\n        cur = self.root\n        for word in words:\n            for i in range(len(word) - 1, -1, -1):\n                ch = word[i]\n                if ch not in cur.children:\n                    cur.children[ch] = TrieNode()\n                cur = cur.children[ch]\n            cur.endOfWord = True\n            cur = self.root\n\n    def query(self, letter: str) -> bool:\n        self.stream.appendleft(letter)\n        cur = self.root\n        for ch in self.stream:\n            if ch not in cur.children:\n                return False\n            else:\n                cur = cur.children[ch]\n                if cur.endOfWord:\n                    return True\n        return False",
        "solution_js": "var StreamChecker = function(words) {\n    function Trie() {\n        this.suffixLink = null; //this is where it will fallback to when a letter can't be matched\n        this.id = -1; //this id will be 0 or greater if it matches a word\n        this.next = new Map(); //map of <char, Trie*>\n    }\n    this.root = new Trie();\n    this.uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system\n\n    //standard trie traversal but keeping track of new words via id system\n    for (const word of words) {\n        let ptr = this.root;\n        for (const c of word) {\n            if (!ptr.next.has(c)) {\n                ptr.next.set(c, new Trie());\n            }\n            ptr = ptr.next.get(c);\n        }\n        if (ptr.id === -1) {\n            ptr.id = this.uniqueIds++;\n        }\n    }\n\n    //BFS traversal to build the automaton\n    const q = [];\n    for (const [c, node] of this.root.next) {\n        //all first level children should point back to the root when a match to a character fails\n        node.suffixLink = this.root;\n        q.push(node);\n    }\n\n    while (q.length) {\n        const curr = q.shift();\n        for (const [c, node] of curr.next) {\n\n            let ptr = curr.suffixLink;\n            while (ptr !== this.root && !ptr.next.has(c)) {\n                ptr = ptr.suffixLink;\n            }\n            //find the next suffixLink if it matches the current character or fallback to the root\n            node.suffixLink = ptr.next.get(c) ?? this.root;\n\n            //if the current suffixLink happens to also be a word we should store its id to make it quick to find\n            if (node.suffixLink.id !== -1) {\n                node.id = node.suffixLink.id;\n            }\n            q.push(node);\n        }\n    }\n    //the query ptr will now track every new streamed character and use it to match\n    this.queryPtr = this.root;\n};\n\nStreamChecker.prototype.query = function(letter) {\n    //the query ptr will now track every new streamed character and can be used to quickly find words\n    while (this.queryPtr !== this.root && !this.queryPtr.next.has(letter)) {\n        this.queryPtr = this.queryPtr.suffixLink;\n    }\n    this.queryPtr = this.queryPtr.next.get(letter) ?? this.root;\n    //if any word is found it will have an id that isn't -1\n    return this.queryPtr.id !== -1;\n};",
        "solution_java": "class StreamChecker {\n    \n    class TrieNode {\n        boolean isWord;\n        TrieNode[] next = new TrieNode[26];\n    }\n    \n    TrieNode root = new TrieNode();\n    StringBuilder sb = new StringBuilder();\n    \n    public StreamChecker(String[] words) {\n        createTrie(words);\n    }\n    \n    public boolean query(char letter){\n        sb.append(letter);\n        TrieNode node = root;\n        for(int i=sb.length()-1; i>=0 && node!=null; i--){\n            char ch = sb.charAt(i);\n            node = node.next[ch - 'a'];\n            if(node != null && node.isWord){\n                return true;\n            }\n        }\n        return false;\n    }\n    \n   private void createTrie(String words[]){\n       for(String s : words){\n           TrieNode node = root;\n           int len = s.length();\n           for(int i = len-1; i>=0; i--){\n               char ch = s.charAt(i);\n               if(node.next[ch-'a'] == null){\n                   node.next[ch - 'a'] = new TrieNode();\n               }\n               node = node.next[ch - 'a'];\n           }\n           node.isWord = true;\n       }\n   }\n}",
        "solution_c": "class StreamChecker {\n    struct Trie {\n        Trie* suffixLink; //this is where it will fallback to when a letter can't be matched\n        int id = -1; //this id will be 0 or greater if it matches a word\n        map<char, Trie*> next;\n    };\npublic:\n    Trie* root;\n    Trie* queryPtr;\n    int uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system\n    \n    StreamChecker(vector<string>& words) {\n        root = new Trie();\n        \n\t\t//standard trie traversal but keeping track of new words via id system\n        for (string& word: words) {\n            Trie* p = root;\n            for (char c: word) {\n                if (p->next.find(c) == p->next.end()) {\n                    p->next.insert({ c, new Trie() });\n                }\n                p = p->next.at(c);\n            }\n            if (p->id == -1) {\n                p->id = uniqueIds++;\n            }\n        }\n        \n        queue<Trie*> q;\n        for (pair<char, Trie*> itr: root->next) {\n            q.push(itr.second);\n            itr.second->suffixLink = root;\n        }\n        \n\t\t//BFS traversal to build the automaton\n        while (q.size()) {\n            Trie* curr = q.front();\n            q.pop();\n            for (pair<char, Trie*> e: curr->next) {\n                char c = e.first;\n                Trie* node = e.second;\n\t\t\t\t\n                Trie* ptr = curr->suffixLink;\n                while (ptr != root && ptr->next.find(c) == ptr->next.end()) {\n                    ptr = ptr->suffixLink;\n                }\n\t\t\t\t//find the next suffixLink if it matches the current character or fallback to the root\n                node->suffixLink = ptr->next.find(c) != ptr->next.end() ? ptr->next.at(c) : root;\n\t\t\t\t\n\t\t\t\t//if the current suffixLink happens to also be a word we should store its id to make it quick to find\n                if (node->suffixLink->id != -1) {\n                    node->id = node->suffixLink->id;\n                }\n                q.push(node);\n            }\n        }\n\t\t//the query ptr will now track every new streamed character and can be used to quickly find words\n        queryPtr = root;\n    }\n    \n    bool query(char letter) {\n\t\t//if the next letter can't be found and we're not at the root, we'll trace back until we find the longest suffix that matches\n        while (queryPtr != root && queryPtr->next.find(letter) == queryPtr->next.end()) {\n            queryPtr = queryPtr->suffixLink;\n        }\n        queryPtr = queryPtr->next.find(letter) != queryPtr->next.end() ? queryPtr->next.at(letter) : root;\n\t\t//if any word is found it will have an id that isn't -1\n        return queryPtr->id != -1;\n    }\n};"
    },
    {
        "title": "Number of Students Unable to Eat Lunch",
        "algo_input": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.\n\nThe number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:\n\n\n\tIf the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.\n\tOtherwise, they will leave it and go to the queue's end.\n\n\nThis continues until none of the queue students want to take the top sandwich and are thus unable to eat.\n\nYou are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.\n\n&nbsp;\nExample 1:\n\nInput: students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput: 0 \nExplanation:\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.\n\n\nExample 2:\n\nInput: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= students.length, sandwiches.length &lt;= 100\n\tstudents.length == sandwiches.length\n\tsandwiches[i] is 0 or 1.\n\tstudents[i] is 0 or 1.\n\n",
        "solution_py": "class Solution(object):\n    def countStudents(self, students, sandwiches):\n        \"\"\"\n        :type students: List[int]\n        :type sandwiches: List[int]\n        :rtype: int\n        \"\"\"\n        while sandwiches:\n            if sandwiches[0] in students:\n                students.remove(sandwiches[0])\n                sandwiches.pop(0)\n            else:\n                break\n        return len(sandwiches)\n            ",
        "solution_js": "var countStudents = function(students, sandwiches) {\nwhile (students.length>0 && students.indexOf(sandwiches[0])!=-1) {\n    if (students[0] == sandwiches[0]) {\n        students.shift();\n        sandwiches.shift();\n    }\n    else students.push(students.shift());\n}\nreturn students.length\n};",
        "solution_java": "class Solution {\n    public int countStudents(int[] students, int[] sandwiches) {\n        int ones = 0; //count of students who prefer type1\n        int zeros = 0; //count of students who prefer type0\n\n        for(int stud : students){\n            if(stud == 0) zeros++;\n            else ones++;\n        }\n\n        // for each sandwich in sandwiches\n        for(int sandwich : sandwiches){\n            if(sandwich == 0){ // if sandwich is of type0\n                if(zeros == 0){ // if no student want a type0 sandwich\n                    return ones;\n                }\n                zeros--;\n            }\n            else{ // if sandwich is of type1\n                if(ones == 0){ // if no student want a type1 sandwich\n                    return zeros;\n                }\n                ones--;\n            }\n        }\n        return 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countStudents(vector<int>& students, vector<int>& sandwiches) {\n        int size = students.size();\n        queue<int> student_choice;\n        for(int i = 0 ; i < size ; ++i){\n            student_choice.push(students[i]);\n        }\n        int rotations = 0 , i = 0;\n        while(student_choice.size() && rotations < student_choice.size()){\n            if(student_choice.front() == sandwiches[i]){\n                student_choice.pop();\n                i++;\n                rotations = 0;\n            } else {\n                int choice = student_choice.front();\n                student_choice.pop();\n                student_choice.push(choice);\n                rotations++;\n            }\n        }\n        return student_choice.size();\n    }\n};"
    },
    {
        "title": "Print Words Vertically",
        "algo_input": "Given a string s.&nbsp;Return&nbsp;all the words vertically in the same order in which they appear in s.\nWords are returned as a list of strings, complete with&nbsp;spaces when is necessary. (Trailing spaces are not allowed).\nEach word would be put on only one column and that in one column there will be only one word.\n\n&nbsp;\nExample 1:\n\nInput: s = \"HOW ARE YOU\"\nOutput: [\"HAY\",\"ORO\",\"WEU\"]\nExplanation: Each word is printed vertically. \n \"HAY\"\n&nbsp;\"ORO\"\n&nbsp;\"WEU\"\n\n\nExample 2:\n\nInput: s = \"TO BE OR NOT TO BE\"\nOutput: [\"TBONTB\",\"OEROOE\",\"   T\"]\nExplanation: Trailing spaces is not allowed. \n\"TBONTB\"\n\"OEROOE\"\n\"   T\"\n\n\nExample 3:\n\nInput: s = \"CONTEST IS COMING\"\nOutput: [\"CIC\",\"OSO\",\"N M\",\"T I\",\"E N\",\"S G\",\"T\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 200\n\ts&nbsp;contains only upper case English letters.\n\tIt's guaranteed that there is only one&nbsp;space between 2 words.\n",
        "solution_py": "class Solution:\n    def getMaxLen(self, words):\n        max_len = 0\n        for word in words:\n            max_len = max(max_len, len(word))\n        return max_len\n    \n    def printVertically(self, s: str) -> List[str]:\n        words = s.split()\n        max_len = self.getMaxLen(words)\n        \n        res = list()\n        for i in range(max_len):\n            s = \"\"\n            for word in words:\n                if i < len(word):\n                    s += word[i]\n                else:\n                    s += \" \"\n            s = s.rstrip()\n            res.append(s)\n        return res\n            \n            \n        \n\t\t",
        "solution_js": "/**\n * @param {string} s\n * @return {string[]}\n */\n\n var printVertically = function(s)\n{\n    let arr = s.split(' '),\n        max = arr.reduce((last, curr) => Math.max(last, curr.length), 0),\n        ans = [];\n\n    arr = arr.map(el => el + ' '.repeat(max - el.length));\n\n    for (let i = 0; i < max; i++)\n    {\n        let word = '';\n\n        for (let j = 0; j < arr.length; j++)\n            word += arr[j][i];\n\n        ans.push(word.replace(new RegExp('\\\\s+$'), ''));\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public List<String> printVertically(String s) {\n        s = s.replace(\" \",\",\");\n        String str=\"\";\n        List<String> a=new ArrayList<>();\n\n        int max=0;\n        for(int i =0;i<s.length();i++){\n           char ch=s.charAt(i);\n            if(ch==','){\n                a.add(str);\n                max=Math.max(max,str.length());\n                str=\"\";\n                continue;\n            }\n            else if(i==s.length()-1){\n                str+=ch;\n                a.add(str);\n                max=Math.max(max,str.length());\n                str=\"\";\n                continue;\n            }\n            str+=ch;\n\n        }\n\n        String [] arr=new String[max];\n        for(int i =0;i<max;i++){\n            arr[i]=\"\";\n\n        }\n\n        for(int i =0;i<a.size();i++){\n            String x=a.get(i);\n\n            for(int j=0;j<max;j++){\n\n                if(j<x.length()){\n                    arr[j]+=x.charAt(j);\n                }\n                else{\n                    arr[j]+=\" \";\n                }\n            }\n\n        }\n\n        a=new ArrayList<>();\n        for(int i=0;i<arr.length;i++){\n\n            String x=arr[i];\n            x=trim(x);\n\n            a.add(x);\n        }\n\n        return a;\n    }\n\n    public String trim(String str) {\n        int len = str.length();\n        int st = 0;\n\n        char[] val = str.toCharArray();\n\n        while ((st < len) && (val[len - 1] <= ' ')) {\n            len--;\n        }\n        return str.substring(st, len);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> printVertically(string s) {\n\n        int row = 0, col = 0;\n\n        stringstream sso(s);\n        string buffer;\n\n        while (sso >> buffer)\n        {\n            row++;\n            col = max((int)buffer.size(),col);\n        }\n\n        vector<vector<char>> matrix(row, vector<char>(col,' '));\n\n        sso = stringstream(s);\n\n        int i = 0;\n        while (sso >> buffer)\n        {\n            for (int j = 0; j < buffer.size(); j++)\n                matrix[i][j] = buffer[j];\n            i++;\n        }\n\n        vector<string> res;\n        for (int j = 0; j < col; j++)\n        {\n            string item;\n            for (int i = 0; i < row; i++)\n                item.push_back(matrix[i][j]);\n\n            for (int i = item.size()-1; i >= 0; i--)\n            {\n                if (item[i] != ' ')\n                {\n                    item.erase(item.begin()+i+1,item.end());\n                    break;\n                }\n            }\n            res.push_back(item);\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Max Dot Product of Two Subsequences",
        "algo_input": "Given two arrays nums1&nbsp;and nums2.\n\nReturn the maximum dot product&nbsp;between&nbsp;non-empty subsequences of nums1 and nums2 with the same length.\n\nA subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,&nbsp;[2,3,5]&nbsp;is a subsequence of&nbsp;[1,2,3,4,5]&nbsp;while [1,5,3]&nbsp;is not).\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput: 18\nExplanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.\n\nExample 2:\n\nInput: nums1 = [3,-2], nums2 = [2,-6,7]\nOutput: 21\nExplanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.\n\nExample 3:\n\nInput: nums1 = [-1,-1], nums2 = [1,1]\nOutput: -1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 500\n\t-1000 &lt;= nums1[i], nums2[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def maxDotProduct(self, A, B):\n        dp = [float('-inf')] * (len(B)+1)\n        for i in range(len(A)):\n            prev = float('-inf')\n            for j in range(len(B)):\n                product = A[i] * B[j]\n                prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product)\n        return dp[-1]",
        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxDotProduct = function(nums1, nums2) {\n    var m = nums1.length;\n    var n = nums2.length;\n    if (!m || !n) return 0;\n    var dp = [[nums1[0] * nums2[0]]];\n    for (var i = 1; i < m; i++) {\n        dp[i] = [];\n        dp[i][0] = Math.max(nums1[i] * nums2[0], dp[i-1][0]);\n    }\n    for (var i = 1; i < n; i++) dp[0][i] = Math.max(nums1[0] * nums2[i], dp[0][i-1]);\n    for (var i = 1; i < m; i++) {\n        for (var j = 1; j < n; j++) {\n            var val = nums1[i] * nums2[j];\n            dp[i][j] = Math.max(val, val + dp[i-1][j-1], dp[i][j-1], dp[i-1][j]);\n        }\n    }\n    return dp[m - 1][n - 1];\n};",
        "solution_java": "class Solution {\n    public int maxDotProduct(int[] nums1, int[] nums2) {\n        int N = nums1.length, M = nums2.length;\n        int[][] dp = new int[N][M];\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < M; j++) {\n                dp[i][j] = nums1[i] * nums2[j];\n                if (i > 0 && j > 0 && dp[i - 1][j - 1] > 0) {\n                    dp[i][j] += dp[i - 1][j - 1];\n                }\n                if (i > 0 && dp[i - 1][j] > dp[i][j]) {\n                    dp[i][j] = dp[i - 1][j];\n                }\n                if (j > 0 && dp[i][j - 1] > dp[i][j]) {\n                    dp[i][j] = dp[i][j - 1];\n                }\n            }\n        }\n        return dp[N - 1][M - 1];\n    }\n}",
        "solution_c": "class Solution\n{\n    public:\n\n        const int NEG_INF = -10e8;\n        int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {\n\n        int n = nums1.size();\n        int m = nums2.size();\n\n        // NOTE : we can't initialize with INT_MIN because adding any val with it will give overflow\n        // that is why we prefer 10^7 or 10^8\n\n        vector<vector<int>> dp(n+1, vector<int>(m+1, NEG_INF));\n\n        for (int i=1; i<=n; i++) {\n            for (int j=1; j<=m; j++) {\n\n                int temp_p = nums1[i-1]*nums2[j-1];\n\n        // Although it is a variation of LCS but here we need to check for all answers we already know in dp\n        // Why only temp_p ? -> suppose in dp[i-1][j-1] is -10^7 + temp_p is 2 == gives nearly -10^7(which is wrong ans)\n        // For Remaining comparisons we already know why !\n\n                dp[i][j] = max({ dp[i-1][j-1] + temp_p,\n                                      temp_p,\n                                      dp[i-1][j],\n                                      dp[i][j-1]\n                              });\n            }\n        }\n\n        return dp[n][m];\n    }\n};"
    },
    {
        "title": "Longest Substring Of All Vowels in Order",
        "algo_input": "A string is considered beautiful if it satisfies the following conditions:\n\n\n\tEach of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.\n\tThe letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).\n\n\nFor example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", and \"aaaeeeooo\" are not beautiful.\n\nGiven a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.\n\nA substring is a contiguous sequence of characters in a string.\n\n&nbsp;\nExample 1:\n\nInput: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput: 13\nExplanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\n\nExample 2:\n\nInput: word = \"aeeeiiiioooauuuaeiou\"\nOutput: 5\nExplanation: The longest beautiful substring in word is \"aeiou\" of length 5.\n\n\nExample 3:\n\nInput: word = \"a\"\nOutput: 0\nExplanation: There is no beautiful substring, so return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 5 * 105\n\tword consists of characters 'a', 'e', 'i', 'o', and 'u'.\n\n",
        "solution_py": "class Solution:\n    def longestBeautifulSubstring(self, word: str) -> int:\n        g = ''\n        count = m = 0\n        for x in word:\n            if g and x < g[-1]:\n                count = 0\n                g = ''\n            if not g or x > g[-1]:\n                g += x\n            count += 1\n            if g == 'aeiou':\n                m = max(m, count)\n        return m",
        "solution_js": "/**\n * @param {string} word\n * @return {number}\n */\nvar longestBeautifulSubstring = function(word) {\n   \n    let obj = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }\n    let seq = 0\n    let maxstrcount = 0, strcount = \"\"\n    for (let i = 0; i <= word.length; i++) {\n        if (seq <= obj[word[i]]) {\n            strcount += word[i]\n            seq = obj[word[i]]\n        } else {\n            let set = new Set()\n            for (let i = 0; i < strcount.length; i++) {\n                set.add(strcount[i])\n            }\n            if (set.size == 5) {\n                maxstrcount = Math.max(strcount.length, maxstrcount)\n            }\n            if (i < word.length - 1)\n                i--\n            strcount = \"\"\n            seq = 0\n        }\n    }\n    return maxstrcount\n};",
        "solution_java": "class Solution {\n    public int longestBeautifulSubstring(String word) {\n      int max = 0;\n      for(int i = 1;i<word.length();i++){\n         int temp = 1;\n         Set<Character> verify = new HashSet<>();\n         verify.add(word.charAt(i-1));\n         while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){\n            temp++;\n            verify.add(word.charAt(i));\n            i++;\n         }\n         max = verify.size() == 5 ? Math.max(max,temp) : max ;\n      }\n\n      return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestBeautifulSubstring(string word) {\n        const auto n = word.size();\n\n        int cnt = 1;\n        int len = 1;\n        int max_len = 0;\n        for (int i = 1; i != n; ++i) {\n            if (word[i - 1] == word[i]) {\n                ++len;\n            } else if (word[i - 1] < word[i]) {\n                ++len;\n                ++cnt;\n            } else {\n                cnt = 1;\n                len = 1;\n            }\n\n            if (cnt == 5) {\n                max_len = max(max_len, len);\n            }\n        }\n        return max_len;\n    }\n};"
    },
    {
        "title": "Count the Number of Ideal Arrays",
        "algo_input": "You are given two integers n and maxValue, which are used to describe an ideal array.\n\nA 0-indexed integer array arr of length n is considered ideal if the following conditions hold:\n\n\n\tEvery arr[i] is a value from 1 to maxValue, for 0 &lt;= i &lt; n.\n\tEvery arr[i] is divisible by arr[i - 1], for 0 &lt; i &lt; n.\n\n\nReturn the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, maxValue = 5\nOutput: 10\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.\n\n\nExample 2:\n\nInput: n = 5, maxValue = 3\nOutput: 11\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n   - With no other distinct values (1 array): [1,1,1,1,1] \n   - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n   - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 104\n\t1 &lt;= maxValue &lt;= 104\n\n",
        "solution_py": "from math import sqrt\n\nclass Solution:\n    def primesUpTo(self, n):\n        primes = set(range(2, n + 1))\n        for i in range(2, n):\n            if i in primes:\n                it = i * 2\n                while it <= n:\n                    if it in primes:\n                        primes.remove(it)\n                    it += i\n\n        return primes\n\n    def getPrimeFactors(self, n, primes):\n        ret = {}\n        sq = int(math.sqrt(n))\n\n        for p in primes:\n            if n in primes:\n                ret[n] = 1\n                break\n\n            while n % p == 0:\n                ret[p] = ret.get(p, 0) + 1\n                n //= p\n\n            if n <= 1:\n                break\n\n        return ret\n        \n    def idealArrays(self, n: int, maxValue: int) -> int:\n        mod = 10**9 + 7\n        ret = 0\n        primes = self.primesUpTo(maxValue)\n        \n        for num in range(1, maxValue + 1):\n            # find number of arrays that can end with num\n            # for each prime factor, we can add it at any index i that we want\n            pf = self.getPrimeFactors(num, primes)\n            cur = 1\n            for d in pf:\n                ct = pf[d]\n                v = n\n                # there are (n + 1) choose k ways to add k prime factors\n                for add in range(1, ct):\n                    v *= (n + add)\n                    v //= (add + 1)\n                \n                cur = (cur * v) % mod\n                    \n            ret = (ret + cur) % mod\n                    \n        return ret",
        "solution_js": "/**\n * @param {number} n\n * @param {number} maxValue\n * @return {number}\n */\nvar idealArrays = function(n, maxValue) {\n  const mod = 1e9 + 7;\n  let cur = 0;\n  let arr = Array(2).fill().map(() => Array(maxValue).fill(1));\n  for (let l = 2; l <= n; l++) {\n    const prev = arr[cur];\n    const next = arr[1-cur];\n    for (let s = 1; s <= maxValue; s++) {\n      let res = 0;\n      for (let m = 1; m * s <= maxValue; m++) {\n        res = (res + prev[m * s - 1]) % mod;\n      }\n      next[s-1] = res;\n    }\n    cur = 1 - cur;\n  }\n  const res = arr[cur].reduce((a, b) => (a + b) % mod, 0);\n  return res;\n};",
        "solution_java": "class Solution {\n    int M =(int)1e9+7;\n    public int idealArrays(int n, int maxValue) {\n        long ans = 0;\n        int N = n+maxValue;\n        long[] inv = new long[N];\n        long[] fact = new long[N];\n        long[] factinv = new long[N];\n        inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1;\n        for (int i = 2; i < N; i++){ // mod inverse\n            inv[i]=M-M/i*inv[M%i]%M;\n            fact[i]=fact[i-1]*i%M;\n            factinv[i]=factinv[i-1]*inv[i]%M;\n        }\n        for (int i = 1; i <= maxValue; i++){\n            int tmp = i;\n            Map<Integer, Integer> map = new HashMap<>();\n            for (int j = 2; j*j<= tmp; j++){\n                while(tmp%j==0){  // prime factorization.\n                    tmp/=j;\n                    map.merge(j, 1, Integer::sum);\n                }\n            }\n            if (tmp>1){\n                map.merge(tmp, 1, Integer::sum);\n            }\n            long gain=1;\n            for (int val : map.values()){ // arranges all the primes.\n                gain *= comb(n+val-1, val, fact, factinv);\n                gain %= M;\n            }\n            ans += gain;\n            ans %= M;\n        }\n\n        return (int)ans;\n    }\n\n    private long comb(int a, int b, long[] fact, long[] factinv){\n        return fact[a]*factinv[b]%M*factinv[a-b]%M;\n    }\n}",
        "solution_c": "int comb[10001][14] = { 1 }, cnt[10001][14] = {}, mod = 1000000007;\nclass Solution {\npublic: \nint idealArrays(int n, int maxValue) {\n    if (comb[1][1] == 0) { // one-time computation.\n        for (int s = 1; s <= 10000; ++s) // nCr (comb)\n            for (int r = 0; r < 14; ++r)\n                comb[s][r] = r == 0 ? 1 : (comb[s - 1][r - 1] + comb[s - 1][r]) % mod;\n        for (int div = 1; div <= 10000; ++div) { // Sieve of Eratosthenes\n            ++cnt[div][0];\n            for (int i = 2 * div; i <= 10000; i += div)\n                for (int bars = 0; cnt[div][bars]; ++bars)\n                    cnt[i][bars + 1] += cnt[div][bars];\n        }\n    }\n    int res = 0;\n    for (int i = 1; i <= maxValue; ++i)\n        for (int bars = 0; bars < min(14, n) && cnt[i][bars]; ++bars)\n            res = (1LL * cnt[i][bars] * comb[n - 1][bars] + res) % mod;\n    return res;\n}\n};"
    },
    {
        "title": "Maximum Number of Coins You Can Get",
        "algo_input": "There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:\n\n\n\tIn each step, you will choose any 3 piles of coins (not necessarily consecutive).\n\tOf your choice, Alice will pick the pile with the maximum number of coins.\n\tYou will pick the next pile with the maximum number of coins.\n\tYour friend Bob will pick the last pile.\n\tRepeat until there are no more piles of coins.\n\n\nGiven an array of integers piles where piles[i] is the number of coins in the ith pile.\n\nReturn the maximum number of coins that you can have.\n\n&nbsp;\nExample 1:\n\nInput: piles = [2,4,1,2,7,8]\nOutput: 9\nExplanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.\n\n\nExample 2:\n\nInput: piles = [2,4,5]\nOutput: 4\n\n\nExample 3:\n\nInput: piles = [9,8,7,6,5,1,2,3,4]\nOutput: 18\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= piles.length &lt;= 105\n\tpiles.length % 3 == 0\n\t1 &lt;= piles[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def maxCoins(self, piles: List[int]) -> int:\n        piles.sort()\n        n = len(piles)\n        k = n // 3\n        i, j = 0, 2\n        ans = 0\n        while i < k:\n            ans += piles[n-j]\n            j += 2\n            i +=1\n        return ans",
        "solution_js": "var maxCoins = function(piles) {\n    let count = 0, i = 0, j = piles.length - 1;\n    piles.sort((a, b) => b - a);\n\n    while(i < j) {\n        count += piles[i + 1];\n        i += 2;\n        j--;\n    }\n\n    return count;\n};",
        "solution_java": "class Solution {\n    public int maxCoins(int[] piles) {\n        Arrays.sort(piles);\n        int s=0,n=piles.length;\n        for(int i=n/3;i<n;i+=2)\n            s+=piles[i];\n        return s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxCoins(vector<int>& piles) {\n        sort(piles.begin(),piles.end(),greater<int>());\n        int myPilesCount=0;\n        int myPilesSum=0;\n        int PilesSize=piles.size();\n        int i=1;\n        while(myPilesCount<(PilesSize/3))\n        {\n\n            myPilesSum+=piles[i];\n            myPilesCount++;\n            i+=2;\n        }\n        return myPilesSum;\n    }\n};"
    },
    {
        "title": "Truncate Sentence",
        "algo_input": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).\n\n\n\tFor example, \"Hello World\", \"HELLO\", and \"hello world hello world\" are all sentences.\n\n\nYou are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.\n\n&nbsp;\nExample 1:\n\nInput: s = \"Hello how are you Contestant\", k = 4\nOutput: \"Hello how are you\"\nExplanation:\nThe words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".\n\n\nExample 2:\n\nInput: s = \"What is the solution to this problem\", k = 4\nOutput: \"What is the solution\"\nExplanation:\nThe words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".\n\nExample 3:\n\nInput: s = \"chopper is not a tanuki\", k = 5\nOutput: \"chopper is not a tanuki\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\tk is in the range [1, the number of words in s].\n\ts consist of only lowercase and uppercase English letters and spaces.\n\tThe words in s are separated by a single space.\n\tThere are no leading or trailing spaces.\n\n",
        "solution_py": "class Solution:\n    def truncateSentence(self, s: str, k: int) -> str:\n        words = s.split(\" \")\n        return \" \".join(words[0:k])",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar truncateSentence = function(s, k) {\n   return s.split(\" \").slice(0,k).join(\" \")\n};",
        "solution_java": "class Solution {\n    public String truncateSentence(String s, int k) {\n        int n = s.length();\n        int count = 0;\n        int i = 0;\n        while(i<n){\n            if(s.charAt(i)==' '){\n                count++;\n                if(count==k) \n                    return s.substring(0,i);\n            }\n            i++;\n        }\n        return s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tstring truncateSentence(string s, int k) {\n\n\t\tint n = s.size();\n\n\t\tstring ans;\n\t\tint cnt = 0;\n\t\tfor(int i=0 ; i<n ; i++){\n\n\t\t\tif(s[i] == ' '){\n\t\t\t\tcnt++;\n\t\t\t}\n\n\t\t\tif(k == cnt){\n\t\t\t\treturn ans;\n\t\t\t}\n\n\t\t\tans += s[i];\n\n\t\t}\n\n\t\treturn ans; \n\t}\n};"
    },
    {
        "title": "Search a 2D Matrix II",
        "algo_input": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:\n\n\n\tIntegers in each row are sorted in ascending from left to right.\n\tIntegers in each column are sorted in ascending from top to bottom.\n\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\nOutput: true\n\n\nExample 2:\n\nInput: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= n, m &lt;= 300\n\t-109 &lt;= matrix[i][j] &lt;= 109\n\tAll the integers in each row are sorted in ascending order.\n\tAll the integers in each column are sorted in ascending order.\n\t-109 &lt;= target &lt;= 109\n\n",
        "solution_py": "class Solution(object):\n    def searchMatrix(self, matrix, target):\n        \"\"\"\n        :type matrix: List[List[int]]\n        :type target: int\n        :rtype: bool\n        \"\"\"\n        found=False\n        for X in matrix:\n             for M in X:\n                if M==target:\n                    found=True\n        return found",
        "solution_js": "function binarySearch(arr, target) {\n    let low = 0;\n    let high = arr.length - 1;\n\n    while (low <= high) {\n        let mid = parseInt((low + high) / 2);\n\n        if (arr[mid] == target) {\n            return mid;\n        }\n        else if (arr[mid] < target) {\n            low = mid + 1;\n        }\n        else if (arr[mid] > target) {\n            high = mid - 1;\n        }\n    }\n    return -1;\n}\n\nvar searchMatrix = function(matrix, target) {\n    for (let i = 0; i < matrix.length; i++) {\n        let check = binarySearch(matrix[i], target);\n\n        if (check != -1) { return true }\n    }\n    return false\n};",
        "solution_java": "class Solution {\n    public boolean searchMatrix(int[][] matrix, int target) {\n        int rows = matrix.length;\n        int cols = matrix[0].length;\n        int lo = 0, hi = rows;\n        while(lo + 1 < hi) {\n            int mid = lo + (hi - lo) / 2;\n            if (matrix[mid][0] <= target) {\n                lo = mid;\n            } else {\n                hi = mid;\n            }\n        }\n        int[] prospect;\n        for (int i = 0; i <= lo; i++) {\n            prospect = matrix[i];\n            int l = 0;\n            int h = cols;\n            while (l + 1 < h) {\n                int mid = l + (h - l) / 2;\n                if (prospect[mid] <= target) {\n                    l = mid;\n                } else {\n                    h = mid;\n                }\n            }\n            if (prospect[l] == target) {\n                return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        for(int i=0;i<matrix.size();++i)\n        {\n            int s=0,e=matrix[0].size()-1;\n            while(s<=e)\n            {\n                int mid=(s+e)/2;\n                if(matrix[i][mid]>target)\n                {\n                    e=mid-1;\n                }\n                else if(matrix[i][mid]<target)\n                {\n                    s=mid+1;\n                }\n                else\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Determine if Two Strings Are Close",
        "algo_input": "Two strings are considered close if you can attain one from the other using the following operations:\n\n\n\tOperation 1: Swap any two existing characters.\n\n\t\n\t\tFor example, abcde -&gt; aecdb\n\t\n\t\n\tOperation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.\n\t\n\t\tFor example, aacabb -&gt; bbcbaa (all a's turn into b's, and all b's turn into a's)\n\t\n\t\n\n\nYou can use the operations on either string as many times as necessary.\n\nGiven two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"abc\", word2 = \"bca\"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -&gt; \"acb\"\nApply Operation 1: \"acb\" -&gt; \"bca\"\n\n\nExample 2:\n\nInput: word1 = \"a\", word2 = \"aa\"\nOutput: false\nExplanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n\n\nExample 3:\n\nInput: word1 = \"cabbba\", word2 = \"abbccc\"\nOutput: true\nExplanation: You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -&gt; \"caabbb\"\nApply Operation 2: \"caabbb\" -&gt; \"baaccc\"\nApply Operation 2: \"baaccc\" -&gt; \"abbccc\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word1.length, word2.length &lt;= 105\n\tword1 and word2 contain&nbsp;only lowercase English letters.\n\n",
        "solution_py": "from collections import Counter\n\nclass Solution:\n    def closeStrings(self, word1: str, word2: str) -> bool:\n        return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())",
        "solution_js": "var closeStrings = function(word1, word2) {\n    if (word1.length != word2.length) return false;\n    let map1 = new Map(), map2 = new Map(),freq1=new Set(),freq2=new Set();\n    for (let i = 0; i < word1.length; i++) map1.set(word1[i],map1.get(word1[i])+1||1),map2.set(word2[i],map2.get(word2[i])+1||1);\n    if (map1.size != map2.size) return false;\n    for (const [key,value] of map1) {\n      if (!map2.has(key)) return false\n      freq1.add(value);\n      freq2.add(map2.get(key));\n    }\n    if (freq1.size != freq2.size) return false;\n    for (const freq of freq1) if (!freq2.has(freq)) return false\n    return true;    \n};",
        "solution_java": "class Solution {\n    private int N = 26;\n    public boolean closeStrings(String word1, String word2) {\n        // count the English letters\n        int[] arr1 = new int[N], arr2 = new int[N];\n        for (char ch : word1.toCharArray())\n            arr1[ch - 'a']++;\n        for (char ch : word2.toCharArray())\n            arr2[ch - 'a']++;\n\n        // if one has a letter which another one doesn't have, dont exist\n        for (int i = 0; i < N; i++) {\n            if (arr1[i] == arr2[i]) {\n                continue;\n            }\n            if (arr1[i] == 0 || arr2[i] == 0) {\n                return false;\n            }\n        }\n        Arrays.sort(arr1);\n        Arrays.sort(arr2);\n        for (int i = 0; i < N; i++) {\n            if (arr1[i] != arr2[i]) {\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool closeStrings(string word1, string word2) {\n        set<int> w1_letters, w2_letters, w1_freq, w2_freq;\n        unordered_map<char, int> w1_m, w2_m;\n        \n        for (auto a : word1) {\n            w1_letters.insert(a);\n            w1_m[a]++;\n        }\n        \n        for (auto a : word2) {\n            w2_letters.insert(a);\n            w2_m[a]++;\n        }\n        \n        for (auto [k, v] : w1_m) w1_freq.insert(v);\n        \n        for (auto [k, v] : w2_m) w2_freq.insert(v);\n\n        return w1_letters == w2_letters && w1_freq == w2_freq;\n    }\n};"
    },
    {
        "title": "Average of Levels in Binary Tree",
        "algo_input": "Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\n\n\nExample 2:\n\nInput: root = [3,9,20,15,7]\nOutput: [3.00000,14.50000,11.00000]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 &lt;= Node.val &lt;= 231 - 1\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n# O(n) || O(h) where h is the height of the tree\n    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n\n        queue = deque([root])\n        result = []\n\n        while queue:\n            runningSum = 0\n            newLevelSize = 0\n            for i in range(len(queue)):\n                currNode = queue.popleft()\n\n                runningSum += currNode.val\n                newLevelSize += 1\n\n                if currNode.left:\n                    queue.append(currNode.left)\n                if currNode.right:\n                    queue.append(currNode.right)\n\n            secretFormula = (runningSum/newLevelSize)\n\n            result.append(secretFormula)\n\n        return result",
        "solution_js": "var averageOfLevels = function(root) {\nlet avg = [root.val];\nlet level = [];\nlet queue = [root];\nwhile(queue.length>0){\n    let curr = queue.shift();\n    if(curr.left){\n        level.push(curr.left)\n    }\n    if(curr.right){\n        level.push(curr.right);\n    }\n    if(queue.length===0){\n        queue.push(...level);\n        avg.push(level.reduce((a,b) => a+b.val,0)/level.length);\n        level = [];\n    }\n}\navg.pop()\nreturn avg;\n};",
        "solution_java": "class Solution {\n    public List<Double> averageOfLevels(TreeNode root) {\n        Queue<TreeNode> q = new LinkedList<>(List.of(root));\n        List<Double> ans = new ArrayList<>();\n        while (q.size() > 0) {\n            double qlen = q.size(), row = 0;\n            for (int i = 0; i < qlen; i++) {\n                TreeNode curr = q.poll();\n                row += curr.val;\n                if (curr.left != null) q.offer(curr.left);\n                if (curr.right != null) q.offer(curr.right);\n            }\n            ans.add(row/qlen);\n        }\n        return ans;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    // Pre-Requisite for this solution: Level order traversal of a BT Line by Line\n    \n    vector<double> averageOfLevels(TreeNode* root) {\n        // vector to store the result\n        vector<double> avgVal;\n        avgVal.push_back(root->val);\n        \n        // Queue for level order traversal Line by Line\n        queue<TreeNode*> q;\n        q.push(root);\n        q.push(NULL);\n        \n        // To store values for levels\n        double levelSum = 0;\n        double levelCount = 0;\n        \n        // Standard Level order traversal Line by Line code\n        while(q.empty() == false){\n            TreeNode* curr = q.front(); q.pop();\n            \n            if(curr == NULL){\n                if(q.empty()==true){\n                    break;\n                }\n                else{   // Here we know that we are at the end of a line\n                    \n                    // So we push the result into the vector\n                    avgVal.push_back(levelSum/levelCount);\n                    \n                    // Reset the counters and push End of Level into the queue.\n                    levelSum = 0;\n                    levelCount = 0;\n                    q.push(NULL);\n                    continue;\n                }\n            }\n            \n            // Note that when we are traversing one level\n            // we are getting sum and count of the next level\n            // Hence, we are moving one level ahead\n            if(curr->left){\n                q.push(curr->left);\n                levelSum += curr->left->val;\n                levelCount++;\n            }\n            if(curr->right){\n                q.push(curr->right);\n                levelSum += curr->right->val;\n                levelCount++;\n            }\n        }\n        return avgVal;\n    }\n};"
    },
    {
        "title": "Regular Expression Matching",
        "algo_input": "Given an input string s&nbsp;and a pattern p, implement regular expression matching with support for '.' and '*' where:\n\n\n\t'.' Matches any single character.​​​​\n\t'*' Matches zero or more of the preceding element.\n\n\nThe matching should cover the entire input string (not partial).\n\n&nbsp;\nExample 1:\n\nInput: s = \"aa\", p = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\n\n\nExample 2:\n\nInput: s = \"aa\", p = \"a*\"\nOutput: true\nExplanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n\n\nExample 3:\n\nInput: s = \"ab\", p = \".*\"\nOutput: true\nExplanation: \".*\" means \"zero or more (*) of any character (.)\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length&nbsp;&lt;= 20\n\t1 &lt;= p.length&nbsp;&lt;= 30\n\ts contains only lowercase English letters.\n\tp contains only lowercase English letters, '.', and&nbsp;'*'.\n\tIt is guaranteed for each appearance of the character '*', there will be a previous valid character to match.\n\n",
        "solution_py": "class Solution:\n   def isMatch(self, s, p):\n       n = len(s)\n       m = len(p)\n       dp = [[False for _ in range (m+1)] for _ in range (n+1)]\n       dp[0][0] = True\n       for c in range(1,m+1):\n           if p[c-1] == '*' and c > 1:\n               dp[0][c] = dp[0][c-2]\n       for r in range(1,n+1):\n           for c in range(1,m+1):\n               if p[c-1] == s[r-1] or p[c-1] == '.':\n                   dp[r][c] = dp[r-1][c-1]\n               elif c > 1 and p[c-1] == '*':\n                   if  p[c-2] =='.' or s[r-1]==p[c-2]:\n                       dp[r][c] =dp[r][c-2] or dp[r-1][c]\n                   else:\n                       dp[r][c] = dp[r][c-2]\n       return dp[n][m]",
        "solution_js": "/**\n * @param {string} s\n * @param {string} p\n * @return {boolean}\n */\n\nvar isMatch = function(s, p) {\n    const pattern = new RegExp('^'+p+'$'); // ^ means start of string, $ means end of the string, these are to prevent certain pattern that match a part of the string to be returned as true.\n    return pattern.test(s);\n};",
        "solution_java": "class Solution {\n    public boolean isMatch(String s, String p) {\n        if (p == null || p.length() == 0) return (s == null || s.length() == 0);\n\n        boolean dp[][] = new boolean[s.length()+1][p.length()+1];\n        dp[0][0] = true;\n        for (int j=2; j<=p.length(); j++) {\n            dp[0][j] = p.charAt(j-1) == '*' && dp[0][j-2];\n        }\n\n        for (int j=1; j<=p.length(); j++) {\n            for (int i=1; i<=s.length(); i++) {\n                if (p.charAt(j-1) == s.charAt(i-1) || p.charAt(j-1) == '.')\n                    dp[i][j] = dp[i-1][j-1];\n                else if(p.charAt(j-1) == '*')\n                    dp[i][j] = dp[i][j-2] || ((s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == '.') && dp[i-1][j]);\n            }\n        }\n        return dp[s.length()][p.length()];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isMatch(string s, string p) {\n        return helper(s,p,0,0);\n    }\n    \n    bool helper(string s, string p, int i, int j)\n    {\n        if(j==p.length())\n            return i==s.length();\n        bool first_match=(i<s.length() && (s[i]==p[j] || p[j]=='.' ));\n        \n        if(j+1<p.length() && p[j+1]=='*')\n        {\n            return (helper(s,p,i,j+2)|| (first_match && helper(s,p,i+1,j) ));\n        }\n        else\n        {\n            return (first_match && helper(s,p,i+1,j+1));\n        }\n    }\n};"
    },
    {
        "title": "K Highest Ranked Items Within a Price Range",
        "algo_input": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:\n\n\n\t0 represents a wall that you cannot pass through.\n\t1 represents an empty cell that you can freely move to and from.\n\tAll other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.\n\n\nIt takes 1 step to travel between adjacent grid cells.\n\nYou are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k.\n\nYou are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different:\n\n\n\tDistance, defined as the length of the shortest path from the start (shorter distance has a higher rank).\n\tPrice (lower price has a higher rank, but it must be in the price range).\n\tThe row number (smaller row number has a higher rank).\n\tThe column number (smaller column number has a higher rank).\n\n\nReturn the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\nOutput: [[0,1],[1,1],[2,1]]\nExplanation: You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).\n\n\nExample 2:\n\nInput: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\nOutput: [[2,1],[1,2]]\nExplanation: You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).\n\n\nExample 3:\n\nInput: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\nOutput: [[2,1],[2,0]]\nExplanation: You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.\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\t0 &lt;= grid[i][j] &lt;= 105\n\tpricing.length == 2\n\t2 &lt;= low &lt;= high &lt;= 105\n\tstart.length == 2\n\t0 &lt;= row &lt;= m - 1\n\t0 &lt;= col &lt;= n - 1\n\tgrid[row][col] &gt; 0\n\t1 &lt;= k &lt;= m * n\n\n",
        "solution_py": "class Solution:\n    def highestRankedKItems(self, G, pricing, start, k):\n        m, n = len(G), len(G[0])\n        row, col = start\n        node = (0, G[row][col], row, col)\n        visited = set()\n        visited.add((row, col))\n        d = deque([node])\n        ans = []\n\n        while d:\n            dist, cost, row, col = d.popleft()\n            if pricing[0] <= cost <= pricing[1]:\n                ans += [(dist, cost, row, col)]\n\n            for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):\n                if 0 <= x <= m-1 and 0 <= y <= n-1 and (x, y) not in visited and G[x][y] != 0:\n                    d.append((dist + 1, G[x][y], x, y))\n                    visited.add((x, y))\n\n        ans = sorted(ans)\n\n        return [[x, y] for _, _, x, y in ans[:k]]",
        "solution_js": "var highestRankedKItems = function(grid, pricing, start, k) {\n    const m = grid.length;\n    const n = grid[0].length;\n    const dirs = [-1, 0, 1, 0, -1];\n\n    const visited = [];\n\n    for (let i = 0; i < m; ++i) {\n        visited[i] = new Array(n).fill(false);\n    }\n\n    const [low, high] = pricing;\n\n    const queue = [];\n\n    queue.push([...start, 0]);\n\n    const items = [];\n\n    while (queue.length > 0) {\n        const [row, col, dist] = queue.shift();\n\n        if (visited[row][col]) continue;\n\n        visited[row][col] = true;\n\n        const price = grid[row][col];\n\n        if (withinRange(price, low, high)) {\n            items.push({ dist, price, row, col });\n        }\n\n        for (let i = 0; i < dirs.length - 1; ++i) {\n            const neiRow = row + dirs[i];\n            const neiCol = col + dirs[i + 1];\n\n            if (withinBound(neiRow, neiCol) && !visited[neiRow][neiCol] && grid[neiRow][neiCol] != 0) {\n                queue.push([neiRow, neiCol, dist + 1]);\n            }\n        }\n    }\n\n    items.sort(compareFunc);\n\n    const res = [];\n\n    for (let i = 0; i < Math.min(k, items.length); ++i) {\n        const { dist, price, row, col } = items[i];\n\n        res.push([row, col]);\n    }\n\n    return res;\n\n    function withinRange(price, low, high) {\n        return low <= price && price <= high;\n    }\n\n    function withinBound(row, col) {\n        return row >= 0 && col >= 0 && row < m && col < n;\n    }\n\n    function compareFunc(a, b) {\n        return a.dist - b.dist || a.price - b.price || a.row - b.row || a.col - b.col;\n    }\n};",
        "solution_java": "class Solution {\n    static class Quad\n    {\n        int x,y,price,dist;\n        Quad(int x,int y,int price,int dist)\n        {\n            this.x=x;\n            this.y=y;\n            this.price=price;\n            this.dist=dist;\n        }\n    }\n    public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n        List<List<Integer>> ans=new LinkedList<>();\n        PriorityQueue<Quad> pq=new PriorityQueue<>((a,b)->{\n            if(a.dist!=b.dist)\n                return a.dist-b.dist;\n            if(a.price!=b.price)\n                return a.price-b.price;\n            if(a.x!=b.x)\n                return a.x-b.x;\n            return a.y-b.y;\n        });\n        bfs(grid,start[0],start[1],pricing[0],pricing[1],pq);\n        while(!pq.isEmpty()&&k-->0)\n        {\n            Quad quad=pq.poll();\n            List<Integer> temp=new LinkedList<>();\n            temp.add(quad.x);\n            temp.add(quad.y);\n            ans.add(temp);\n        }\n        return ans;\n    }\n    void bfs(int[][] grid,int i,int j,int low,int high,PriorityQueue<Quad> pq)\n    {\n        Queue<int[]> queue=new LinkedList<>();\n        int m=grid.length,n=grid[0].length;\n        if(grid[i][j]>=low&&grid[i][j]<=high)\n            pq.add(new Quad(i,j,grid[i][j],0));\n        grid[i][j]=0;\n        queue.add(new int[]{i,j});\n        int dist=0;\n        int dirs[][]={{1,0},{-1,0},{0,1},{0,-1}};\n        while(!queue.isEmpty())\n        {\n            ++dist;\n            int size=queue.size();\n            while(size-->0)\n            {\n                int[] p=queue.poll();\n                for(int[] dir:dirs)\n                {\n                    int newX=dir[0]+p[0];\n                    int newY=dir[1]+p[1];\n                    if(newX>=0&&newY>=0&&newX<m&&newY<n&&grid[newX][newY]!=0)\n                    {\n                        if(grid[newX][newY]>=low&&grid[newX][newY]<=high)\n                            pq.add(new Quad(newX,newY,grid[newX][newY],dist));\n                        queue.add(new int[]{newX,newY});\n                        grid[newX][newY]=0;\n                    }\n                }\n            }\n            \n        }\n    }\n   \n\n}",
        "solution_c": "class Solution {\npublic:\n    struct cell\n    {\n        int dist;\n        int cost;\n        int row;\n        int col;\n    };\n    struct compare\n    {\n        bool operator()(const cell &a, const cell &b)\n        {\n            if(a.dist != b.dist)\n                return a.dist < b.dist;\n            else if(a.cost != b.cost)\n                return a.cost < b.cost;\n            else if(a.row != b.row)\n                return a.row < b.row;\n            else\n                return a.col < b.col;\n        }\n    };\n\n    vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid, vector<int>& pricing, vector<int>& start, int k) {\n        int m=grid.size();\n        int n=grid[0].size();\n\n        queue<pair<int,int>>q;\n        q.push({start[0],start[1]});\n\n        vector<vector<bool>> vis(m,vector<bool>(n,false));\n        vis[start[0]][start[1]]=true;\n\n        int dx[4]={-1,0,1,0};\n        int dy[4]={0,-1,0,1};\n        int dist=0;\n\n        priority_queue<cell,vector<cell>,compare> pq;\n         while(!q.empty())\n         {\n             int size=q.size();\n             while(size--)\n             {\n                 pair<int,int> p=q.front(); q.pop();\n                 if(grid[p.first][p.second]!=1 && grid[p.first][p.second]>=pricing[0] && grid[p.first][p.second]<=pricing[1])\n                 {\n                     pq.push({dist,grid[p.first][p.second],p.first,p.second});\n\n                     if(pq.size()>k)\n                         pq.pop();\n                }\n                for(int k=0;k<4;k++)\n                {\n                    int x=p.first+dx[k];\n                    int y=p.second+dy[k];\n\n                    if(x>=0 && x<m && y>=0 && y<n && vis[x][y]==false && grid[x][y]!=0)\n                    {\n                        vis[x][y]=true;\n                        q.push({x,y});\n                    }\n                }\n            }\n        dist++;\n        }\n\n        vector<vector<int>> ans;\n        while(!pq.empty())\n        {\n        ans.push_back({pq.top().row,pq.top().col});\n        pq.pop();\n        }\n\n    reverse(ans.begin(),ans.end());\n    return ans;\n    }\n};"
    },
    {
        "title": "Longest String Chain",
        "algo_input": "You are given an array of words where each word consists of lowercase English letters.\n\nwordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.\n\n\n\tFor example, \"abc\" is a predecessor of \"abac\", while \"cba\" is not a predecessor of \"bcad\".\n\n\nA word chain is a sequence of words [word1, word2, ..., wordk] with k &gt;= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.\n\nReturn the length of the longest possible word chain with words chosen from the given list of words.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput: 4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].\n\n\nExample 2:\n\nInput: words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput: 5\nExplanation: All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].\n\n\nExample 3:\n\nInput: words = [\"abcd\",\"dbqca\"]\nOutput: 1\nExplanation: The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length &lt;= 16\n\twords[i] only consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestStrChain(self, words: List[str]) -> int:\n        \n        words.sort(key=len)\n        dic = {}\n        \n        for i in words:\n            dic[ i ] = 1\n            \n            for j in range(len(i)):\n                \n                # creating words by deleting a letter\n                successor = i[:j] + i[j+1:]\n                if successor in dic:\n                    dic[ i ] = max (dic[i], 1 + dic[successor])\n        \n        res = max(dic.values())\n        return res",
        "solution_js": "/**\n * @param {string[]} words\n * @return {number}\n */\nvar longestStrChain = function(words) \n{\n        let tiers = new Array(16);\n        for(let i=0; i<tiers.length; i++)\n                tiers[i] = [];\n        for(let word of words)\n                tiers[word.length-1].push({word,len:1});\n\n        const isPredecessor = function(word1,word2)     // Assumes word2.length = word1.length+1\n        {\n                let w1p = 0, misses = 0;\n                for(let w2p = 0; w2p < word2.length; w2p++)\n                {\n                        if(word2[w2p] !== word1[w1p])\n                        {\n                                if(misses === 1)\n                                        return false;\n                                misses = 1;\n                        }\n                        else\n                        {\n                                w1p++;\n                                if(w1p === word1.length)\n                                        return true;\n                        }\n                }\n                return true;\n        };\n        \n        \n        for(let i=tiers.length-1; i>0; i--)\n        {\n                for(let w2=0; w2<tiers[i].length; w2++)\n                {\n                        for(let w1 = 0; w1 < tiers[i-1].length; w1++)\n                        {\n                                if(tiers[i-1][w1].len >= tiers[i][w2].len+1)\n                                        continue;\n                                if(isPredecessor(tiers[i-1][w1].word, tiers[i][w2].word))\n                                        tiers[i-1][w1].len = tiers[i][w2].len+1;\n                        }\n                }\n        }\n        \n        let max = 0;\n        for(let i=0; i<tiers.length; i++)\n        {\n                for(let j=0; j<tiers[i].length; j++)\n                        max = Math.max(max,tiers[i][j].len);\n        }\n        \n        return max;\n};",
        "solution_java": "class Solution {\n    \n    Boolean compareForIncreaseByOne(String str1,String str2){\n            //str 1 will be long than str2\n        int first=0;\n        int second=0;\n        if(str1.length() != (str2.length() + 1)){\n            return false;\n        }\n        while(first < str1.length()){\n            if(second < str2.length() && str1.charAt(first) == str2.charAt(second)){\n                first++;\n                second++;\n            }else{\n                first++;\n            }\n        }\n        if(first == str1.length() && second == str2.length()){\n            return true;\n        }\n        return false;\n    }\n    \n    public int longestStrChain(String[] words) {\n        int N = words.length;\n        Arrays.sort(words,(a,b) -> a.length()-b.length());  //as Sequence/Subset are not ordered\n        int []dp =new int[N];\n        Arrays.fill(dp,1);\n        int maxi = 1;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<i;j++){\n                if(compareForIncreaseByOne(words[i],words[j]) && dp[j]+1 > dp[i]){\n                    dp[i] = dp[j] + 1;\n                    maxi = Math.max(maxi,dp[i]);\n                }\n            }\n        }//for neds\n        return maxi;\n    }\n}",
        "solution_c": "class Solution {\n    int dfs(unordered_map<string, int>& m, unordered_set<string>& setWords, \n            const string& w) {\n        if (m.count(w)) return m[w];\n        int maxLen = 1;\n        \n        for(int i=0;i<w.size();++i) {\n            auto preWord = w.substr(0, i) + w.substr(i+1);\n            if(setWords.count(preWord)) {\n                int newLen = 1 + dfs(m, setWords, preWord);\n                maxLen = max(newLen, maxLen);\n            }\n        }\n        m[w] = maxLen;\n        return maxLen;\n        \n    }\npublic:\n    int longestStrChain(vector<string>& words) {\n        \n        unordered_map<string, int> m;\n        unordered_set<string> setWords(words.begin(), words.end());\n        int res = 0;\n\t\t\n        for(auto& w:words) {\n            res = max(res, dfs(m, setWords, w));\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Possible Bipartition",
        "algo_input": "We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.\n\nGiven the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput: true\nExplanation: group1 [1,4] and group2 [2,3].\n\n\nExample 2:\n\nInput: n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput: false\n\n\nExample 3:\n\nInput: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2000\n\t0 &lt;= dislikes.length &lt;= 104\n\tdislikes[i].length == 2\n\t1 &lt;= dislikes[i][j] &lt;= n\n\tai &lt; bi\n\tAll the pairs of dislikes are unique.\n\n",
        "solution_py": "class Solution:\n    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n        def dfs(i, c):\n            if color[i] != 0:\n                if color[i] != c:\n                    return False\n                return True\n\n            color[i] = c\n            for u in e[i]:\n                if not dfs(u, 3 - c):\n                    return False\n            return True\n\n        e = [[] for _ in range(n)]\n        for u, v in dislikes:\n            u -= 1\n            v -= 1\n            e[u].append(v)\n            e[v].append(u)\n        color = [0] * n\n        for i in range(n):\n            if color[i] == 0:\n                if not dfs(i, 1):\n                    return False\n        return True",
        "solution_js": "var possibleBipartition = function(n, dislikes) {\n    const g = new Map();\n    dislikes.forEach(([a, b]) => {\n        const aDis = g.get(a) || [];\n        const bDis = g.get(b) || [];\n        g.set(a, aDis.concat(b));\n        g.set(b, bDis.concat(a));\n    });\n    \n    const vis = new Array(n+1).fill(false);\n    const col = new Array(n+1).fill(-1);\n    \n    const dfs = (n, c = 0) => {\n        if(vis[n]) return true;\n        \n        col[n] = c;\n        vis[n] = true;\n        \n        const nodes = g.get(n) || [];\n        for(let node of nodes) {\n            if(!vis[node]) {\n                if(!dfs(node, 1 - c)) return false;\n            }\n            \n            if(node != n && col[node] == c) return false;\n        }\n        \n        return true;\n    };\n    \n    let canBi = true;\n    for(let i = 1; i <= n; i++) {\n        canBi &= dfs(i);\n    }\n    return canBi;\n};",
        "solution_java": "class Solution {\n    int[] rank;\n    int[] parent;\n    int[] rival;\n    public boolean possibleBipartition(int n, int[][] dislikes) {\n        rank = new int[n+1];\n        rival = new int[n+1];\n        parent = new int[n+1];\n        for(int i = 1;i <= n;i++){\n            rank[i] = 1;\n            parent[i] = i;\n        }\n        for(int[] dis : dislikes){\n            int x = dis[0], y = dis[1];\n            if(find(x) == find(y))\n                return false;\n            if(rival[x] != 0)\n                union(rival[x], y);\n            else\n                rival[x] = y;\n            if(rival[y] != 0)\n                union(rival[y], x);\n            else\n                rival[y] = x;\n        }\n        return true;\n    }\n    public int find(int x){\n        if(parent[x] == x)\n            return x;\n        return parent[x] = find(parent[x]);\n    }\n    public void union(int x, int y){\n        int x_set = find(x);\n        int y_set = find(y);\n        if(x_set == y_set)\n            return;\n        if(rank[x_set] < rank[y_set])\n            parent[x_set] = y_set;\n        else if(rank[y_set] < rank[x_set])\n            parent[y_set] = x_set;\n        else{\n            parent[x_set] = y_set;\n            rank[y_set]++;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool dfs(vector<int>adj[], vector<int>& color, int node){\n        for(auto it: adj[node]){ //dfs over adjacent nodes\n            if(color[it]==-1){ //not visited yet\n                color[it]=1-color[node]; //set different color of adjacent nodes \n                if(!dfs(adj,color,it)) return false;\n            }\n            else if(color[it]!=1-color[node]) return false; //if adjacent nodes have same color\n        }\n        return true;\n    }\n    \n    \n    bool possibleBipartition(int n, vector<vector<int>>& dislikes) {\n        vector<int>adj[n+1];\n        for(int i=0;i<dislikes.size();i++){//undirected graph\n            adj[dislikes[i][0]].push_back(dislikes[i][1]);\n            adj[dislikes[i][1]].push_back(dislikes[i][0]);\n        }\n        vector<int>color(n+1,-1); //-1 i.e. not visited yet\n        for(int i=1;i<=n;i++){\n            if(color[i]==-1){\n                color[i]=0;\n                if(!dfs(adj,color,i)) return false;\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Odd Even Jump",
        "algo_input": "You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\n\nYou may jump forward from index i to index j (with i &lt; j) in the following way:\n\n\n\tDuring odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] &lt;= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n\tDuring even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] &gt;= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n\tIt may be the case that for some index i, there are no legal jumps.\n\n\nA starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).\n\nReturn the number of good starting indices.\n\n&nbsp;\nExample 1:\n\nInput: arr = [10,13,12,14,15]\nOutput: 2\nExplanation: \nFrom starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.\n\n\nExample 2:\n\nInput: arr = [2,3,1,1,4]\nOutput: 3\nExplanation: \nFrom starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.\n\n\nExample 3:\n\nInput: arr = [5,1,3,4,2]\nOutput: 3\nExplanation: We can reach the end from starting indices 1, 2, and 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 2 * 104\n\t0 &lt;= arr[i] &lt; 105\n\n",
        "solution_py": "class Solution:\n    def oddEvenJumps(self, arr: List[int]) -> int:\n        \n        l = len(arr)\n        res = [False]*l\n        res[-1] = True\n        \n        # for odd jump: for i, get next larger one \n        odd_next = [i for i in range(l)]\n        stack = [] # mono inc for ind\n        for n, i in sorted([(arr[i], i) for i in range(l)]):\n            while stack and stack[-1]<i:\n                odd_next[stack.pop()] = i\n            stack.append(i)\n                \n        # for even jump: for i, get next smaller one \n        even_next = [i for i in range(l)]\n        stack = [] # mono inc for ind\n        for n, i in sorted([(-arr[i], i) for i in range(l)]):\n            while stack and stack[-1]<i:\n                even_next[stack.pop()] = i\n            stack.append(i)\n            \n        # dp \n        @lru_cache(None)\n        def dp(i, odd):\n            if i == l-1:\n                return True\n            ind = odd_next[i] if odd else even_next[i]\n            \n            if ind == i:\n                return False\n            \n            return dp(ind, not odd)\n        \n        for i in range(l-1):\n            res[i] = dp(i, True)\n        return sum(res)",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar oddEvenJumps = function(arr) {\n    let result = 0;\n    const len = arr.length\n    const map = {} // { value: index }\n    const memo = new Array(2).fill(null).map(i => new Array(len).fill(false))\n    \n    // Build a BST to maintain logN search/Insert\n    function treeNode(value) {\n        this.val = value;\n        this.left = null;\n        this.right = null;\n    }\n    \n    const root = new TreeNode(arr[len - 1])\n    \n    function InsertToBST(val) {\n        function dfs(node){\n            if(node.val < val) {\n                if(!node.right) node.right = new TreeNode(val);\n                else dfs(node.right);\n            }\n            if(node.val > val) {\n                if(!node.left) node.left = new TreeNode(val);\n                else dfs(node.left);\n            }\n        }\n        \n        dfs(root);\n    }\n    \n    \n    \n    \n    memo[0][len - 1] = memo[1][len - 1] = true;\n    map[arr[len - 1]] = len - 1;\n    \n    //memo[0] odd jumps\n    //memo[1] even jumps\n    \n    function getNextBig(base) { // odd jump\n        if(map[base] !== undefined) {\n            return base\n        }\n        let result = Infinity\n        function dfs(node) {\n            if(!node) return;\n            \n            if(node.val > base && node.val < result) {\n                result = node.val;\n                dfs(node.left)\n            }\n            \n            if(node.val < base) {\n                dfs(node.right);\n            }\n        }\n        \n        dfs(root)\n        \n        return result === Infinity ? false : result;\n    }\n    \n    function getNextSmall(base) { //even jump\n        if(map[base] !== undefined) {\n            return base\n        }\n        let result = -Infinity\n        function dfs(node) {\n            if(!node) return;\n            \n            if(node.val < base && node.val > result) {\n                result = node.val;\n                dfs(node.right)\n            }\n            \n            if(node.val > base) {\n                dfs(node.left);\n            }\n        }\n        \n        dfs(root)\n        \n        return result === -Infinity ? false : result;\n    }\n    \n    for(let i = len - 2; i >= 0; i--) {\n        let nextBig = getNextBig(arr[i])\n        let nextSmall = getNextSmall(arr[i])\n        \n        memo[0][i] = nextBig ? memo[1][map[nextBig]] : nextBig;\n        memo[1][i] = nextSmall ? memo[0][map[nextSmall]] : nextSmall;\n        map[arr[i]] = i;\n        InsertToBST(arr[i])\n    }\n\n    return memo[0].filter(boo => boo).length\n    \n};",
        "solution_java": "class Solution {\n    public int oddEvenJumps(int[] arr) {\n\n        int len = arr.length;\n        int minjmp[] = new int[len];\n        int maxjmp[] = new int[len];\n\n        TreeMap<Integer, Integer> map = new TreeMap<>();\n        int evjmp, oddjmp;\n        for(int i = len-1; i>=0; i--)\n        {\n            Integer minpos = map.floorKey(arr[i]);\n            evjmp = (minpos != null)?map.get(minpos):len; //default len, to show not possible\n\n            if(evjmp != len && (evjmp == len-1 || maxjmp[evjmp] == len-1))\n                evjmp = len-1; //check the last pos reachability\n\n            Integer maxpos = map.ceilingKey(arr[i]);\n            oddjmp = (maxpos != null) ? map.get(maxpos):len;\n\n            if(oddjmp != len && (oddjmp == len-1 || minjmp[oddjmp] == len-1))\n                oddjmp = len-1;//check the last pos reachability\n\n            minjmp[i] = evjmp; //specify possible jump path, if not possible assign len\n            maxjmp[i] = oddjmp;//specify possible jump path, if not possible assign len\n\n            map.put(arr[i],i); //put the current index\n        }\n\n        int res = 0;\n\n        for(int i = 0; i< len-1; i++) {\n\n            if(maxjmp[i] == len-1)\n                res++;\n        }\n\n        return res+1; //since last position will always be the answer\n    }\n\n}",
        "solution_c": "class Solution {\nprivate:\n    void tryOddJump(const int idx,\n                    const int val,\n                    std::map<int, int>& visitedNode,\n                    vector<int>& oddJumpsDP,\n                    vector<int>& evenJumpsDP) {\n        // looking for equal or bigger element and it's going to be smallest posible\n        auto jumpPoint = visitedNode.lower_bound(val);\n        // If from jumpPoint exists even jump further, then odd jump will have some value\n        if(jumpPoint != visitedNode.end()) oddJumpsDP[idx] = evenJumpsDP[jumpPoint->second];\n    }\n    \n    void tryEvenJump(const int idx,\n                     const int val,\n                     std::map<int, int>& visitedNode,\n                     vector<int>& oddJumpsDP,\n                     vector<int>& evenJumpsDP) {\n        //looking for strictly bigger element because then I can be sure that previous will be equal or less that val for sure\n        auto jumpPoint = visitedNode.upper_bound(val);\n        // if it's first element, then there is no equal or less option, so no even jump possible\n        if(jumpPoint != visitedNode.begin()) \n            evenJumpsDP[idx] = oddJumpsDP[std::prev(jumpPoint)->second]; // (jumpPoint-1) check if further odd jump is possible from largest element that is <= val \n    }\npublic:\n    int oddEvenJumps(vector<int>& arr) {\n        const size_t n = arr.size();\n        vector<int> oddJumpsDP(n, 0);\n        vector<int> evenJumpsDP(n, 0);\n        oddJumpsDP[n-1] = 1;\n        evenJumpsDP[n-1] = 1;\n        std::map<int, int> visitedNode;\n        visitedNode[arr[n-1]] = n-1;\n        \n        /*\n        Idea is to move backward and keep track of posibility of odd and even jumps from each cell.\n        This way at any jump we could check if further jumps is possible.\n        Example 1:\n                          v\n            arr = [10,13,12,14,15]\n            odd = [ -, -, 0, 1, 1]\n            even= [ -, -, -, 0, 1]\n            \n            Let's say we curently have answers for 14 and 15 and trying to work on 12:\n                tryOddJump() -> will give us 14 as only possible odd jump(arr[i] <= arr[j] and arr[j] is the smallest possible value), \n\t\t\t\tbut there is no EVEN jump from 14 further, \n\t\t\t\tso we cache odd jump for 12 as 0 as well. \n\t\t\t\tThat's why I called thouse variables as oddJumpsDP/evenJumpsDP,\n\t\t\t\tthey are caches for subproblems that helps in later computations.\n\t\t\t\tWithout them we would need to check entire further path starting from each cell and it's not efficient.\n        */\n        int res = 1;\n        for(int i=n-2; i>=0; --i) {\n            tryOddJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);\n            tryEvenJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);\n            // we alwayse start from 1st jump that is odd jump, so we can add index to the result if odd jump from it is possible\n            if(oddJumpsDP[i] == 1) ++res;\n            visitedNode[arr[i]] = i;\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Minimum Insertions to Balance a Parentheses String",
        "algo_input": "Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:\n\n\n\tAny left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.\n\tLeft parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.\n\n\nIn other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.\n\n\n\tFor example, \"())\", \"())(())))\" and \"(())())))\" are balanced, \")()\", \"()))\" and \"(()))\" are not balanced.\n\n\nYou can insert the characters '(' and ')' at any position of the string to balance it if needed.\n\nReturn the minimum number of insertions needed to make s balanced.\n\n&nbsp;\nExample 1:\n\nInput: s = \"(()))\"\nOutput: 1\nExplanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.\n\n\nExample 2:\n\nInput: s = \"())\"\nOutput: 0\nExplanation: The string is already balanced.\n\n\nExample 3:\n\nInput: s = \"))())(\"\nOutput: 3\nExplanation: Add '(' to match the first '))', Add '))' to match the last '('.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of '(' and ')' only.\n\n",
        "solution_py": "class Solution:\n    def minInsertions(self, s: str) -> int:\n        leftbrackets = insertions = 0\n        i, n = 0, len(s)\n\n        while i < n:\n            if s[i] == '(':\n                leftbrackets += 1\n            elif s[i] == ')':\n                if i == n-1 or s[i+1] != ')': insertions += 1\n                else: i += 1\n                    \n                if not leftbrackets: insertions += 1\n                else: leftbrackets -= 1\n                    \n            i += 1\n        \n        return leftbrackets * 2 + insertions",
        "solution_js": "var minInsertions = function(s) {\n    let rightNeeded = 0;\n    let leftNeeded = 0;\n    for (const char of s) {\n        if (char === \"(\") {\n            if (rightNeeded % 2 === 0) {\n                rightNeeded += 2;  \n            } else {                \n                rightNeeded++;\n                leftNeeded++;\n            }\n        } else {\n            rightNeeded--;\n            if (rightNeeded === -1 ){\n                leftNeeded++;\n                rightNeeded = 1;\n            }\n        }\n    }\n    return leftNeeded + rightNeeded;\n};",
        "solution_java": "class Solution {\n    public int minInsertions(String s) {\n        int open=0;\n        int ans=0;\n\n        for(int i=0;i<s.length();i++){\n            if(s.charAt(i)=='('){\n                open++;\n            }\n            else{\n                if(i+1<s.length() && s.charAt(i+1)==')'){\n                    i++;\n                    if(open>0){\n                        open--;\n                    }\n                    else{\n                        ans++;\n                    }\n                }\n                else{\n                    if(open>0){\n                        open--;\n                        ans++;\n                    }\n                    else{\n                        ans+=2;\n                    }\n                }\n            }\n        }\n        ans+=2*open;\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minInsertions(string s) {\n        stack<int> st;\n        int n = s.size();\n        int insert = 0;\n        for(int i = 0; i < n; i++)\n        {\n            if(s[i] == '(')\n            {\n                if(st.empty())\n                {\n                    st.push(2);\n                }\n                else\n                {\n                    if(st.top() != 2)\n                    {\n                        st.pop();\n                        insert++;\n                    }\n                    st.push(2);\n                }\n            }\n            else\n            {\n                if(st.empty())\n                {\n                    insert++;\n                    st.push(1);\n                }\n                else\n                {\n                    int dummy = st.top();\n                    st.pop();\n                    dummy--;\n                    if(dummy)\n                        st.push(dummy);\n                }\n            }\n        }\n        while(!st.empty())\n        {\n            insert += st.top();\n            st.pop();\n        }\n        return insert;\n    }\n};"
    },
    {
        "title": "A Number After a Double Reversal",
        "algo_input": "Reversing an integer means to reverse all its digits.\n\n\n\tFor example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.\n\n\nGiven an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: num = 526\nOutput: true\nExplanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.\n\n\nExample 2:\n\nInput: num = 1800\nOutput: false\nExplanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.\n\n\nExample 3:\n\nInput: num = 0\nOutput: true\nExplanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 106\n\n",
        "solution_py": "class Solution(object):\n    def isSameAfterReversals(self, num):\n\t\t# All you have to do is check the Trailing zeros\n        return num == 0 or num % 10  # num % 10 means num % 10 != 0",
        "solution_js": "/**\n * @param {number} num\n * @return {boolean}\n */\nvar isSameAfterReversals = function(num) {\n    if(num == 0)    return true;\n    if(num % 10 == 0)   return false;\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isSameAfterReversals(int num) {\n        return (num%10!=0||num<10);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSameAfterReversals(int num) {\n        return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros\n    }\n};"
    },
    {
        "title": "Make The String Great",
        "algo_input": "Given a string s of lower and upper case English letters.\n\nA good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:\n\n\n\t0 &lt;= i &lt;= s.length - 2\n\ts[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.\n\n\nTo make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.\n\nReturn the string after making it good. The answer is guaranteed to be unique under the given constraints.\n\nNotice that an empty string is also good.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leEeetcode\"\nOutput: \"leetcode\"\nExplanation: In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\n\n\nExample 2:\n\nInput: s = \"abBAcC\"\nOutput: \"\"\nExplanation: We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --&gt; \"aAcC\" --&gt; \"cC\" --&gt; \"\"\n\"abBAcC\" --&gt; \"abBA\" --&gt; \"aA\" --&gt; \"\"\n\n\nExample 3:\n\nInput: s = \"s\"\nOutput: \"s\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts contains only lower and upper case English letters.\n\n",
        "solution_py": "class Solution:\n    def makeGood(self, s: str) -> str:\n        while True:\n            for i in range(len(s)-1):\n                if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()):\n                    s = s[:i]+s[i+2:]\n                    break\n            else:\n                break\n        return s",
        "solution_js": "var makeGood = function(s) {\n    const sArr = []\n    for(let i = 0; i < s.length; i++) {\n        sArr.push(s[i])\n    }\n    const popper = function() {\n        let counter = 0\n                for(let i = 0; i < sArr.length; i++) {\n            if(sArr[i] !== sArr[i + 1]) {\n                if(sArr[i].toUpperCase() === sArr[i + 1] || sArr[i].toLowerCase() === sArr[i + 1]) {\n                    sArr.splice(i,2)\n                    counter++\n                }\n            }\n        }\n        if(counter > 0) {\n            popper()\n        }\n    }\n    popper()\n  \n    return sArr.join('');\n};\n\nconvert string to array to allow access to splice method. iterate over array checking for eqality between i and i +1  in the array. if equal, do nothing. if not equal convert to lower/uppercase and again check for equality. if equal splice those two from the array. counter checks if anything has been removed, if it has it iterates over the array again",
        "solution_java": "class Solution {\npublic String makeGood(String s) {\n     char[] res = s.toCharArray();\n    int i = 0;\n    for( char n: s.toCharArray())\n    {\n        res[i] = n;\n        \n        if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32)\n        {\n            i-=2;\n        }\n        i++;\n    }\n    return new String(res, 0, i);\n}\n}",
        "solution_c": "class Solution {\npublic:\n    string makeGood(string s) {\n        \tstack<char>st;\n\tst.push(s[0]);\n\tstring ans=\"\";\n\n\tfor(int i=1;i<s.size();++i){\n\t\tif(!st.empty() and (st.top()==s[i]+32 or st.top()==s[i]-32)){\n\t\t\tcout<<\"top :\"<<st.top()<<endl;\n\t\t\tst.pop();\n\t\t}\n\n\t\telse {\n\n\t\t\tst.push(s[i]);\n\t\t}\n\t}\n\n\t\n\t\twhile(!st.empty()){\n\t\t// cout<<st.top()<<\"\";\n\t\tans+=st.top();\n\t\tst.pop();\n\n\t\t}\n\t\t\treverse(ans.begin(),ans.end());\n\t\n\t\treturn ans;\n\t\n\t\n    }\n};"
    },
    {
        "title": "Count Binary Substrings",
        "algo_input": "Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.\n\nSubstrings that occur multiple times are counted the number of times they occur.\n\n&nbsp;\nExample 1:\n\nInput: s = \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n\n\nExample 2:\n\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def countBinarySubstrings(self, s: str) -> int:\n        \n        # previous continuous occurrence, current continuous occurrence\n        pre_cont_occ, cur_cont_occ = 0, 1\n        \n        # counter for binary substrings with equal 0s and 1s\n        counter = 0\n        \n\t\t# scan each character pair in s\n        for idx in range(1, len(s)):\n            \n            if s[idx] == s[idx-1]:\n                \n                # update current continuous occurrence\n                cur_cont_occ += 1\n            \n            else:\n                # update counter of binary substrings between prevous character group and current character group\n                counter += min(pre_cont_occ, cur_cont_occ)\n\n                # update previous as current's continuous occurrence\n                pre_cont_occ = cur_cont_occ\n                \n                # reset current continuous occurrence to 1\n                cur_cont_occ = 1\n        \n        # update for last time\n        counter += min(pre_cont_occ, cur_cont_occ)\n        \n        return counter",
        "solution_js": "/**\n * find all bit switches '01' and '10'. \n * From each one expand sideways: i goes left, j goes right\n * Until:\n * if '01' -> i,j != 0,1\n * if '10' -> i,j != 1,0\n * and within input boundaries\n */\nvar countBinarySubstrings = function(s) {\n    let i = 0;\n    const n = s.length;\n    let count = 0;\n    while (i < n-1) {\n        if (s[i] != s[i+1]) {\n            if (s[i] === '0') {\n                count += countZeroOnes(s, i, true);\n            } else {\n                count += countZeroOnes(s, i, false);\n            }\n            \n        }\n        i++;\n    }\n    return count;\n    \n    // count the number of valid substrings substrings\n    function countZeroOnes(s, start, startsWithZero) {\n        let count = 0;\n        let i = start;\n        let j = start+1;\n        const n = s.length;\n        if (startsWithZero) {\n            while(i >= 0 && j < n && s[i] === '0' && s[j] === '1') {\n                count++;\n                i--;\n                j++;\n            }\n        } else {\n            while(i >= 0 && j < n && s[i] === '1' && s[j] === '0') {\n                count++;\n                i--;\n                j++;\n            }\n        }\n        return count;\n    }\n}",
        "solution_java": "class Solution\n{\n    public int countBinarySubstrings(String s)\n    {\n        int i , prevRunLength = 0 , curRunLength = 1 , count = 0 ;\n        for ( i = 1 ; i < s.length() ; i++ )\n        {\n            if( s.charAt(i) == s.charAt( i - 1 ) )\n            {\n                curRunLength++;\n            }\n            else\n            {\n                prevRunLength = curRunLength;\n                curRunLength = 1;\n            }\n            if(prevRunLength >= curRunLength)\n            {\n                count++ ;\n            }\n        }\n        return count ;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countBinarySubstrings(string s) {\n        int prev=0;\n        int curr=1;\n        int sum=0;\n\n        for(int i=1;i<s.length();i++){\n            if(s[i]==s[i-1]){\n                curr++;\n            }\n            else{\n                sum+= min(prev, curr);\n                prev=curr;\n                curr=1;\n            }\n        }\n\n        sum+= min(prev, curr);\n        return sum;\n    }\n};"
    },
    {
        "title": "Alert Using Same Key-Card Three or More Times in a One Hour Period",
        "algo_input": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.\n\nYou are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.\n\nAccess times are given in the 24-hour time format \"HH:MM\", such as \"23:51\" and \"09:49\".\n\nReturn a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.\n\nNotice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period.\n\n&nbsp;\nExample 1:\n\nInput: keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\nOutput: [\"daniel\"]\nExplanation: \"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").\n\n\nExample 2:\n\nInput: keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\nOutput: [\"bob\"]\nExplanation: \"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= keyName.length, keyTime.length &lt;= 105\n\tkeyName.length == keyTime.length\n\tkeyTime[i] is in the format \"HH:MM\".\n\t[keyName[i], keyTime[i]] is unique.\n\t1 &lt;= keyName[i].length &lt;= 10\n\tkeyName[i] contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    # 668 ms, 99.52%. Time: O(NlogN). Space: O(N)\n    def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n        \n        def is_within_1hr(t1, t2):\n            h1, m1 = t1.split(\":\")\n            h2, m2 = t2.split(\":\")\n            if int(h1) + 1 < int(h2): return False\n            if h1 == h2: return True\n            return m1 >= m2\n        \n        records = collections.defaultdict(list)\n        for name, time in zip(keyName, keyTime):\n            records[name].append(time)\n        \n        rv = []\n        for person, record in records.items():\n            record.sort()\n\t\t\t# Loop through 2 values at a time and check if they are within 1 hour.\n            if any(is_within_1hr(t1, t2) for t1, t2 in zip(record, record[2:])):\n                rv.append(person)\n        return sorted(rv)\n                  ",
        "solution_js": "/**\n * @param {string[]} keyName\n * @param {string[]} keyTime\n * @return {string[]}\n */\nvar alertNames = function(keyName, keyTime) {\n    // so we don't keep duplicates\n    const abusers = new Set();\n    // map: name->times[] (sorted)\n    const times = {};\n    for (let i=0; i<keyName.length; i++) {\n        const name = keyName[i];\n        const time = keyTime[i];\n        if (times[name] == null) times[name] = [];\n        times[name].push(time);\n        \n        if (times[name].length > 2) {\n            times[name].sort();\n            const len = times[name].length;\n            // we check all triples for a time difference below 1 hour.\n            // as times are sorted, we need to check all i and i+2\n            for (let i=0; i<len-2; i++) {\n                if (belowHour(times[name][i], times[name][i+2])) {    \n                    abusers.add(name);\n                }\n            }\n        }\n        \n    }\n    const ar = Array.from(abusers);\n    // sort them lexicographically\n    ar.sort();\n    return ar;\n        \n    /*\n    same hour: true\n    hour diff is above 1: false\n    hour diff is 1: m2 must be <= m1\n    */\n    function belowHour(t1, t2) {\n        const [h1, m1] = t1.split(':').map(num => parseInt(num));\n        const [h2, m2] = t2.split(':').map(num => parseInt(num));\n        if (h1 === h2) return true;\n        if (h2-h1 > 1) return false;\n        if (m2 <= m1) return true;\n    }\n};",
        "solution_java": "class Solution {\n    public List<String> alertNames(String[] keyName, String[] keyTime) {\n        Map<String, PriorityQueue<Integer>> map = new HashMap<>();\n\t\t// for every entry in keyName and keyTime, add that time to a priorityqueue for that name\n        for(int i=0;i<keyName.length;i++){\n            PriorityQueue<Integer> pq = map.getOrDefault(keyName[i], new PriorityQueue<Integer>());\n\t\t\t//convert the time to an integer (0- 2359 inclusive) for easy comparisons\n            pq.add(Integer.parseInt(keyTime[i].substring(0,2))*100+Integer.parseInt(keyTime[i].substring(3)));\n            map.put(keyName[i],pq);\n        }\n        \n\t\t// Generate the \"answer\" list\n        List<String> ans = new ArrayList<>();\n        for(String s: map.keySet()){\n\t\t\t// For each name in the map, determine if that name used the keycard within 1 hour\n            PriorityQueue<Integer> pq = map.get(s);\n            if(active(pq)){\n                ans.add(s);\n            }\n        }\n        \n\t\t// Sort the names alphabetically\n        Collections.sort(ans);\n        return ans;\n    }\n    \n\t// Greedy function to determine if there were 3 uses within an hour\n    private boolean active(PriorityQueue<Integer> pq){\n\t\t// If there are two or less entries, the user could not have entered 3 times, return false\n        if(pq.size()<3) return false;\n\t\t\n\t\t// Create rolling data\n\t\t// Using PriorityQueues, the lowest number is removed first by default\n        int a = pq.poll();\n        int b = pq.poll();\n        int c = pq.poll();\n        \n\t\t// Test if two entrances are within 1 hour (100 in integer)\n        if(c-a <=100) return true;\n        while(pq.size()>0){\n            a = b;\n            b = c;\n            c = pq.poll();\n            if(c-a <=100) return true;\n        }\n\t\t\n\t\t// If the full Queue has been checked, return false\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool timeDiff(vector<string> timestamp, int index){\n        int time1 = ((timestamp[index][0]-'0') * 10 + (timestamp[index][1]-'0')) * 60 + ((timestamp[index][3]-'0') * 10 + (timestamp[index][4]-'0'));\n        int time2 = ((timestamp[index+2][0]-'0') * 10 + (timestamp[index+2][1]-'0')) * 60 + ((timestamp[index+2][3]-'0') * 10 + (timestamp[index+2][4]-'0'));\n        \n        if(abs(time2-time1)<=60) return true;\n        return false;\n    }\n    \n    vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) {\n        unordered_map<string, vector<string>> ht;\n        \n        for(int i=0; i<keyName.size(); i++)\n            ht[keyName[i]].push_back(keyTime[i]);\n        \n        vector<string> result;\n        for(auto time : ht){\n            sort(time.second.begin(), time.second.end());\n            for(int i=0; i+2<time.second.size(); i++)\n                if(timeDiff(time.second, i)){\n                    result.push_back(time.first);\n                    break;\n                }\n        }\n        \n        sort(result.begin(), result.end());\n        return result;\n    }\n};\n\n/*\nAlgorithm Outline\n1. store in HT as vector\n2. Check for each, 1st & 3rd in range. True if Yes\n*/"
    },
    {
        "title": "Circular Permutation in Binary Representation",
        "algo_input": "Given 2 integers n and start. Your task is return any permutation p&nbsp;of (0,1,2.....,2^n -1) such that :\n\n\n\tp[0] = start\n\tp[i] and p[i+1]&nbsp;differ by only one bit in their binary representation.\n\tp[0] and p[2^n -1]&nbsp;must also differ by only one bit in their binary representation.\n\n\n&nbsp;\nExample 1:\n\nInput: n = 2, start = 3\nOutput: [3,2,0,1]\nExplanation: The binary representation of the permutation is (11,10,00,01). \nAll the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]\n\n\nExample 2:\n\nInput: n = 3, start = 2\nOutput: [2,6,7,5,4,0,1,3]\nExplanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 16\n\t0 &lt;= start&nbsp;&lt;&nbsp;2 ^ n\n",
        "solution_py": "class Solution:\n    def circularPermutation(self, n: int, start: int) -> List[int]:\n        gray_code = [x ^ (x >> 1) for x in range(2 ** n)]\n        start_i = gray_code.index(start)\n        return gray_code[start_i:] + gray_code[:start_i]",
        "solution_js": "var circularPermutation = function(n, start) {\n    const grayCodes = [];\n\n    let startIdx = -1;\n\n    for (let i = 0; i <= 2**n - 1; i++) {\n        grayCodes[i] = i ^ (i >> 1);\n\n        if (grayCodes[i] == start) startIdx = i;\n    }\n\n    const res = [];\n\n    for (let i = 0; i <= 2**n - 1; i++) {\n        res[i] = grayCodes[startIdx];\n\n        startIdx++;\n\n        if (startIdx == grayCodes.length) startIdx = 0;\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<Integer> circularPermutation(int n, int start) {\n        List<Integer> l = new ArrayList<Integer>();\n        int i=0;\n        int len = (int)Math.pow(2,n);\n        int[] arr = new int[len];\n        while(i<len){\n            arr[i]=(i)^(i/2);\n            i++;\n        }\n        \n        i=0;\n        while(arr[i]!=start)i++;\n        while(i<arr.length){\n            l.add(arr[i]);\n            i++;\n        }\n        i=0;\n        while(i<arr.length && arr[i]!=start){\n            l.add(arr[i]);\n            i++;\n        }\n        return l;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> get_val(int n)\n    {\n        if(n==1)return {\"0\",\"1\"};\n        vector<string> v = get_val(n-1);\n        vector<string> ans;\n        for(int i = 0;i<v.size();i++)\n        {\n            ans.push_back(\"0\" + v[i]);\n        }\n\n        for(int i = v.size()-1;i>=0;i--)\n        {\n            ans.push_back(\"1\" + v[i]);\n        }\n        return ans;\n    }\n\n    vector<int> solve(int n)\n    {\n        vector<string> v = get_val(n);\n        vector<int> ans;\n        for(int i = 0;i<v.size();i++)\n        {\n            string s = v[i];\n            int x = 0;\n            for(int j = 0;j<s.size();j++)\n            {\n                x = x*2 + s[j]-'0';\n            }\n            ans.push_back(x);\n        }\n        return ans;\n    }\n\n    vector<int> circularPermutation(int n, int start) {\n\n        vector<int> v = solve(n);\n        int ind;\n        for(int i = 0;i<v.size();i++)\n        {\n            if(v[i]==start)\n            {\n                ind = i;\n                break;\n            }\n        }\n\n        vector<int> ans;\n        for(int i = ind;i<v.size();i++)\n        {\n            ans.push_back(v[i]);\n        }\n        for(int i = 0;i<ind;i++)\n        {\n            ans.push_back(v[i]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Build Array Where You Can Find The Maximum Exactly K Comparisons",
        "algo_input": "You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:\n\nYou should build the array arr which has the following properties:\n\n\n\tarr has exactly n integers.\n\t1 &lt;= arr[i] &lt;= m where (0 &lt;= i &lt; n).\n\tAfter applying the mentioned algorithm to arr, the value search_cost is equal to k.\n\n\nReturn the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, m = 3, k = 1\nOutput: 6\nExplanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n\n\nExample 2:\n\nInput: n = 5, m = 2, k = 3\nOutput: 0\nExplanation: There are no possible arrays that satisify the mentioned conditions.\n\n\nExample 3:\n\nInput: n = 9, m = 1, k = 1\nOutput: 1\nExplanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 50\n\t1 &lt;= m &lt;= 100\n\t0 &lt;= k &lt;= n\n\n",
        "solution_py": "class Solution:\n    def numOfArrays(self, n: int, m: int, k: int) -> int:\n        @cache\n        def dp(a,b,c):\n            if a==n: return c==k\n            return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1))\n        return dp(0,0,0)%(10**9+7)",
        "solution_js": "var numOfArrays = function(n, m, k){ \n    let mod=1e9+7,\n        // dp[i][c][j] the number of arrays of length i that cost c and their max element is j  \n        dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0))),\n        // prefix[i][k][j] holds the prefix sum of dp[i][k][:j] \n        prefix=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0)))\n    //basecases\n    dp[0][0][0] = 1\n    prefix[0][0].fill(1)\n    for(var i = 1; i <= n; i++) //length of array\n        for(var x = 1; x <= k; x++) //curcost\n            for(var j = 1; j <= m; j++) //curmax\n                // the previous max can be anything <j with a cost of x-1, to which we append j \n                dp[i][x][j] += prefix[i-1][x-1][j-1],\n                // we can also append any number <=j to an array of length i-1 that already costs x,\n                //therefore not increasing the cost\n                dp[i][x][j] += dp[i - 1][x][j] *j ,\n                dp[i][x][j] %= mod,\n                prefix[i][x][j]=(prefix[i][x][j-1]+dp[i][x][j])%mod\n    return dp[n][k].reduce((a,c)=>(a+c)%mod)\n};",
        "solution_java": "class Solution {\n    public int numOfArrays(int n, int m, int k) {\n        int M = (int)1e9+7, ans = 0;\n        int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side\n        for (int i = 1; i <= m; i++){\n            dp[i][1]=1; // base case \n        }\n        for (int i = 2; i <= n; i++){\n            int[][] next = new int[m+1][k+1];\n            for (int j = 1; j <= m; j++){ // for the current max value\n                for (int p = 1; p <= m; p++){ // previous max value\n                    for (int w = 1; w <= k; w++){ // for all possible k\n                        if (j>p){ // if current max is larger, update next[j][w] from dp[p][w-1]\n                            next[j][w]+=dp[p][w-1];\n                            next[j][w]%=M;\n                        }else{ // otherwise, update next[p][w] from dp[p][w]\n                            next[p][w]+=dp[p][w];\n                            next[p][w]%=M;\n                        }\n                    }\n                }\n            }\n            dp=next;\n        }\n        for (int i = 1; i <= m; i++){ // loop through max that has k and sum them up.\n            ans += dp[i][k];\n            ans %= M;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numOfArrays(int n, int m, int k) {\n        if(m<k)return 0;\n        int dp[2][m+1][k+1],mod=1e9+7;\n        memset(dp,0,sizeof(dp));\n        for(int j=1;j<=m;++j)\n            dp[0][j][1]=j;\n        for(int i=1;i<n;++i)\n            for(int j=1;j<=m;++j)\n                for(int l=1;l<=min(i+1,min(j,k));++l)\n                    dp[i&1][j][l]=(dp[i&1][j-1][l]+(long)(dp[(i-1)&1][j][l]-dp[(i-1)&1][j-1][l])*j+dp[(i-1)&1][j-1][l-1])%mod;\n        return (dp[(n-1)&1][m][k]+mod)%mod;\n    }\n};"
    },
    {
        "title": "Maximum Total Importance of Roads",
        "algo_input": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.\n\nYou are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.\n\nYou need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.\n\nReturn the maximum total importance of all roads possible after assigning the values optimally.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput: 43\nExplanation: The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.\n\n\nExample 2:\n\nInput: n = 5, roads = [[0,3],[2,4],[1,3]]\nOutput: 20\nExplanation: The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 5 * 104\n\t1 &lt;= roads.length &lt;= 5 * 104\n\troads[i].length == 2\n\t0 &lt;= ai, bi &lt;= n - 1\n\tai != bi\n\tThere are no duplicate roads.\n\n",
        "solution_py": "class Solution:\n    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n        Arr = [0] * n  # i-th city has Arr[i] roads\n        for A,B in roads:\n            Arr[A] += 1 # Each road increase the road count\n            Arr[B] += 1\n        Arr.sort()  # Cities with most road should receive the most score\n        summ = 0\n        for i in range(len(Arr)):\n            summ += Arr[i] * (i+1)  # Multiply city roads with corresponding score\n        \n        return summ",
        "solution_js": "var maximumImportance = function(n, roads) {\n    const connectionCount = Array(n).fill(0)\n\n    // Count the connections from each city\n    // e.g. the 0th city's count will be stored at index zero in the array\n    for (let [cityTo, cityFrom] of roads) {\n        connectionCount[cityTo]++\n        connectionCount[cityFrom]++\n    }\n\n    let cityToConnectionCount = []\n    for (let city = 0; city < n; city++) {\n        cityToConnectionCount.push([city, connectionCount[city]])// Store the [city, numberOfConnections]\n    }\n\n    // Created new array(sortedCities) for readability\n    const sortedCities = cityToConnectionCount.sort((a,b) => b[1] - a[1])// sort by number of connections, the city with the greatest number of connections should be\n    // the city with the greatest importance\n\n    const values = Array(n).fill(0)\n    let importance = n\n    for (let i = 0; i < sortedCities.length; i++) {\n        const [city, connectionCount] = cityToConnectionCount[i]\n        values[city] = importance// City at the 0th position array is should be the city with the greatest importance\n        importance--\n    }\n\n    // Sum the importance of each city, toCity => fromCity\n    let res = 0\n    for (let [to, from] of roads) {\n        res += values[to] + values[from]\n    }\n\n    return res\n};```",
        "solution_java": "class Solution {\n    public long maximumImportance(int n, int[][] roads) {\n        long ans = 0, x = 1;\n        long degree[] = new long[n];\n        for(int road[] : roads){\n            degree[road[0]]++;\n            degree[road[1]]++;\n        }\n        Arrays.sort(degree);\n        for(long i : degree) ans += i * (x++) ;\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long maximumImportance(int n, vector<vector<int>>& roads) {\n        vector<int>ind(n,0);\n        \n        for(auto it:roads)\n        {\n            ind[it[0]]++;\n            ind[it[1]]++;\n        }\n        \n        priority_queue<long long> pq;\n        long long val = n,ans=0;\n        \n        for(int i=0;i<n;i++)\n            pq.push(ind[i]);\n        \n        while(!pq.empty())\n        {\n            ans += pq.top() * val;\n            val--;\n            pq.pop();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Kth Smallest Number in Multiplication Table",
        "algo_input": "Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).\n\nGiven three integers m, n, and k, return the kth smallest element in the m x n multiplication table.\n\n&nbsp;\nExample 1:\n\nInput: m = 3, n = 3, k = 5\nOutput: 3\nExplanation: The 5th smallest number is 3.\n\n\nExample 2:\n\nInput: m = 2, n = 3, k = 6\nOutput: 6\nExplanation: The 6th smallest number is 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 3 * 104\n\t1 &lt;= k &lt;= m * n\n\n",
        "solution_py": "class Solution:\n    def numSmaller(self, x, m, n):\n        res = 0\n        for i in range(1, m + 1):\n            res += min(x // i, n)\n        return res\n    \n    def findKthNumber(self, m: int, n: int, k: int) -> int:\n        beg = 1\n        end = m * n\n        while beg < end:\n            mid = (beg + end) // 2\n            curr = self.numSmaller(mid, m, n)\n            if curr < k:\n                beg = mid + 1\n            else:\n                end = mid\n        return beg",
        "solution_js": "/**\n * @param {number} m\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar findKthNumber = function(m, n, k) {\n  // lo always points to a value which is\n  // not going to be our answer\n  let lo = 0;\n  let hi = m * n;\n\n  // the loop stops when lo and hi point to two adjascent numbers\n  // because lo is always incorrect, hi will contain our final answer\n  while (lo + 1 < hi) {\n\n    // As a general practice don't do a (lo + hi) / 2 because that\n    // might cause integer overflow\n    const mid = lo + Math.floor((hi - lo) / 2);\n    const count = countLessThanEqual(mid, m, n);\n\n    // Find the minimum mid, such that count >= k\n    if (count >= k) {\n      hi = mid;\n    } else {\n      lo = mid;\n    }\n  }\n  return hi;\n};\n\nfunction countLessThanEqual(target, rows, cols) {\n  let count = 0;\n  // we move row by row in the multiplication table\n  // Each row contains at max (target / rowIndex) elements less than\n  // or equal to target. The number of cols would limit it though.\n  for (let i = 1; i <= rows; i++) {\n    count += Math.min(Math.floor(target / i), cols);\n  }\n  return count;\n}",
        "solution_java": "class Solution {\n    public int findKthNumber(int m, int n, int k) {\n        int lo = 1;\n        int hi = m * n;\n        \n        while(lo < hi){\n            int mid = lo + (hi - lo) / 2;\n            \n            if(count(mid, m, n) < k){\n                lo = mid + 1;\n            } else if(count(mid, m, n) >= k){\n                hi = mid;\n            }\n        }\n        return lo;\n    }\n    private int count(int mid, int m, int n){\n        int ans = 0;\n        for(int i = 1; i <= m; i++){\n            int res = Math.min(mid / i, n);\n            ans += res;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int findKthNumber(int m, int n, int k) {\n        int high=m*n ,low=1;\n\n        int mid=0, ans=1e9;\n        while(low<=high)\n        {\n            mid=low+(high-low)/2;\n            int temp=0;\n\n            // for each i find the max value ,less than or equal to n , such that\n            // i*j<=mid\n            // add j to answer\n           for(int i=1;i<=m;i++)\n            temp+=min(mid/i,n);\n\n            if(temp>=k)\n            {\n                ans=min(ans,mid);\n                high=mid-1;\n            }\n            else\n                low=mid+1;\n\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Best Time to Buy and Sell Stock with Cooldown",
        "algo_input": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\n\nFind the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:\n\n\n\tAfter you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).\n\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n\n&nbsp;\nExample 1:\n\nInput: prices = [1,2,3,0,2]\nOutput: 3\nExplanation: transactions = [buy, sell, cooldown, buy, sell]\n\n\nExample 2:\n\nInput: prices = [1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 5000\n\t0 &lt;= prices[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def maxProfit(self, prices: List[int]) -> int:\n        \n        \n        cache = {}\n        def dfs(i, buying):\n            \n            if i >= len(prices):\n                return 0\n            \n            if (i, buying) in cache:\n                return cache[(i, buying)]\n            \n            if buying:\n                # if have sell the share in previous step\n                # then currently we have two options\n                # either buy or not buy(cooldown)\n                \n                # we have bought so, increment the index and set buying flag to not buying\n                # and don't forget that we bought so, we have to reduce that share amount from profit\n                buy = dfs(i+1, not buying) - prices[i] \n                \n                cooldown = dfs(i+1, buying)\n                \n                profit = max( buy, cooldown )\n                cache[(i, buying)] = profit\n                \n            else:\n                # we have sell the share so, \n                # we cannot buy next share we have to skip the next price(cooldown for one day)\n                # set (not buying) flag to buying\n                # we also have to add that share price to profit\n                sell = dfs(i+2, not buying) + prices[i] \n                \n                cooldown = dfs(i+1, buying)\n                \n                profit = max( sell, cooldown )\n                cache[(i, buying)] = profit\n                \n            return cache[(i,  buying)]\n        \n        return dfs(0, True)",
        "solution_js": "/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n    let dp = {};\n    let recursiveProfit = (index,buy) =>{\n        if(index>=prices.length){\n            return 0;\n        }\n        if(dp[index+'_'+buy]) return dp[index+'_'+buy]\n        if(buy){\n            dp[index+'_'+buy] = Math.max(-prices[index]+recursiveProfit(index+1,0), 0+recursiveProfit(index+1,1))\n            return dp[index+'_'+buy];\n        }\n        else{\n            dp[index+'_'+buy]= Math.max(prices[index]+recursiveProfit(index+2,1),0+recursiveProfit(index+1,0))\n            return dp[index+'_'+buy];\n        }\n    }\n    return recursiveProfit(0,1);\n};",
        "solution_java": "class Solution {\n    public int maxProfit(int[] prices) {\n\n        int n = prices.length;\n\n        int[][] dp = new int[n+2][2];\n\n        for(int index = n-1; index>=0; index--){\n            for(int buy = 0; buy<=1; buy++){\n\n                int profit = 0;\n\n                if(buy == 0){ // buy stocks\n                    profit = Math.max(-prices[index] + dp[index+1][1], 0 + dp[index+1][0]);\n                }\n                if(buy == 1){ // we can sell stocks\n                    profit = Math.max(prices[index] + dp[index+2][0], 0 + dp[index+1][1]);\n                }\n                dp[index][buy] = profit;\n            }\n        }\n        return dp[0][0];\n    }\n}",
        "solution_c": "class Solution {\n public:\n  int maxProfit(vector<int>& prices) {\n    int n = prices.size();\n    int ans = 0;\n    vector<int> dp(n, 0);\n    for (int i = 1; i < n; ++i) {\n      int max_dp = 0;\n      for (int j = 0; j < i; ++j) {\n        dp[i] = max(dp[i], prices[i] - prices[j] + max_dp);\n        max_dp = max(max_dp, j > 0 ? dp[j - 1] : 0);\n      }\n      ans = max(ans, dp[i]);\n    }\n    return ans;\n  }\n};"
    },
    {
        "title": "Implement Stack using Queues",
        "algo_input": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).\n\nImplement the MyStack class:\n\n\n\tvoid push(int x) Pushes element x to the top of the stack.\n\tint pop() Removes the element on the top of the stack and returns it.\n\tint top() Returns the element on the top of the stack.\n\tboolean empty() Returns true if the stack is empty, false otherwise.\n\n\nNotes:\n\n\n\tYou must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.\n\tDepending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 2, 2, false]\n\nExplanation\nMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= x &lt;= 9\n\tAt most 100 calls will be made to push, pop, top, and empty.\n\tAll the calls to pop and top are valid.\n\n\n&nbsp;\nFollow-up: Can you implement the stack using only one queue?\n",
        "solution_py": "class MyStack:\n\n    def __init__(self):\n        self.q1 = deque()\n        self.q2 = deque()\n\n    def push(self, x: int) -> None:\n        self.q1.append(x)\n\n    def pop(self) -> int:\n        while len(self.q1) > 1:\n            self.q2.append(self.q1.popleft())\n        \n        popped_element = self.q1.popleft()\n        \n        # Swap q1 and q2\n        self.q1, self.q2 = self.q2, self.q1\n        \n        return popped_element\n\n    def top(self) -> int:\n        while len(self.q1) > 1:\n            self.q2.append(self.q1.popleft())\n        \n        top_element = self.q1[0]\n        \n        self.q2.append(self.q1.popleft())\n        \n        # Swap q1 and q2\n        self.q1, self.q2 = self.q2, self.q1\n        \n        return top_element\n\n    def empty(self) -> bool:\n        return len(self.q1) == 0",
        "solution_js": "var MyStack = function() {\n    this.stack = [];\n};\n\n/** \n * @param {number} x\n * @return {void}\n */\nMyStack.prototype.push = function(x) {\n    this.stack.push(x);\n};\n\n/**\n * @return {number}\n */\nMyStack.prototype.pop = function() {\n    return this.stack.splice([this.stack.length-1], 1)\n};\n\n/**\n * @return {number}\n */\nMyStack.prototype.top = function() {\n     return this.stack[this.stack.length-1]\n};\n\n/**\n * @return {boolean}\n */\nMyStack.prototype.empty = function() {\n    return this.stack.length === 0 ? true : false;\n};\n\n/** \n * Your MyStack object will be instantiated and called as such:\n * var obj = new MyStack()\n * obj.push(x)\n * var param_2 = obj.pop()\n * var param_3 = obj.top()\n * var param_4 = obj.empty()\n */",
        "solution_java": "class MyStack {\n\n    Queue<Integer> queue = null;\n\n    public MyStack() {\n        queue = new LinkedList<>();\n    }\n\n    public void push(int x) {\n\n        Queue<Integer> tempQueue = new LinkedList<>();\n        tempQueue.add(x);\n\n        while(!queue.isEmpty()){\n         tempQueue.add(queue.remove());\n        }\n\n        queue = tempQueue;\n\n    }\n\n    public int pop() {\n       return queue.remove();\n    }\n\n    public int top() {\n        return queue.peek();\n    }\n\n    public boolean empty() {\n        return queue.isEmpty();\n    }\n}",
        "solution_c": "class MyStack {\npublic:\n    queue<int> q1;\n    queue<int> q2;\n    MyStack() {\n\n    }\n\n    void push(int x) {\n        q1.push(x);\n    }\n\n    int pop() {\n\n        while(q1.size() !=1){\n         int temp = q1.front();\n            q1.pop();\n            q2.push(temp);\n        }\n        int temp = q1.front();\n        q1.pop();\n        while(!q2.empty()){\n            int tp = q2.front();\n            q2.pop();\n            q1.push(tp);\n        }\n        return temp;\n    }\n\n    int top() {\n        while(q1.size() !=1){\n         int temp = q1.front();\n            q1.pop();\n            q2.push(temp);\n        }\n        int temp = q1.front();\n        q1.pop();\n        q2.push(temp);\n        while(!q2.empty()){\n            int tp = q2.front();\n            q2.pop();\n            q1.push(tp);\n        }\n        return temp;\n    }\n\n    bool empty() {\n        if(q1.empty()){\n            return true;\n        }\n        return false;\n    }\n};\n\n/**\n * Your MyStack object will be instantiated and called as such:\n * MyStack* obj = new MyStack();\n * obj->push(x);\n * int param_2 = obj->pop();\n * int param_3 = obj->top();\n * bool param_4 = obj->empty();\n */"
    },
    {
        "title": "Find Bottom Left Tree Value",
        "algo_input": "Given the root of a binary tree, return the leftmost value in the last row of the tree.\n\n&nbsp;\nExample 1:\n\nInput: root = [2,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,2,3,4,null,5,6,null,null,7]\nOutput: 7\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 &lt;= Node.val &lt;= 231 - 1\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n        \n        res = root.val\n        stack = [(0, root)]\n        prev_d = 0\n        \n        while stack:\n            \n            curr_d, curr_v = stack.pop(0)\n            \n            if curr_v.left:\n                stack.append((curr_d+1, curr_v.left))\n                if prev_d != curr_d + 1:\n                    res = curr_v.left.val\n                    prev_d = curr_d+1\n            \n            if curr_v.right:\n                stack.append((curr_d+1, curr_v.right))\n                if prev_d != curr_d + 1:\n                    res = curr_v.right.val\n                    prev_d = curr_d+1\n        \n        return res\n\t\t\n\t\t# An Upvote will be encouraging",
        "solution_js": "var findBottomLeftValue = function(root) {\n    let arr=[];\n    let q=[root];\n    while(q.length!==0){\n        let current=q.shift();\n        arr.push(current.val)\n        if(current.right){\n            q.push(current.right)\n        }\n        if(current.left){\n            q.push(current.left);\n        }\n    }\n    return arr[arr.length-1]\n};",
        "solution_java": "class Solution {\n    int max = Integer.MIN_VALUE;\n    int res = -1;\n    public int findBottomLeftValue(TreeNode root) {\n        check(root,0);\n        return res;\n    }\n    void check(TreeNode root, int h){\n        if(root==null)\n            return;\n        if(h>max){\n            max=h;\n            res = root.val;\n        }\n        check(root.left,h+1);\n        check(root.right,h+1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findBottomLeftValue(TreeNode* root) {\n        queue<TreeNode*> q;\n        q.push(root);\n        int ans=root->val;\n        \n        while(!q.empty()){\n            int n=q.size();\n            for(int i=0;i<n;i++){\n                TreeNode* curr= q.front();\n                q.pop();\n                \n                if(i==0) ans=curr->val;\n                \n                if(curr->left) q.push(curr->left);\n                if(curr->right) q.push(curr->right);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Bitwise AND of Numbers Range",
        "algo_input": "Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.\n\n&nbsp;\nExample 1:\n\nInput: left = 5, right = 7\nOutput: 4\n\n\nExample 2:\n\nInput: left = 0, right = 0\nOutput: 0\n\n\nExample 3:\n\nInput: left = 1, right = 2147483647\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= left &lt;= right &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def rangeBitwiseAnd(self, left: int, right: int) -> int:\n        if not left: return 0\n        i = 0\n        cur = left\n        while cur + (cur & -cur) <= right:\n            cur += cur & -cur\n            left &= cur\n        return left",
        "solution_js": "var rangeBitwiseAnd = function(left, right) {\n    const a = left.toString(2);\n    const b = right.toString(2);\n\n    if (a.length !== b.length) {\n        return 0;\n    }\n\n    let match = 0;\n\n    for (let i = 0; i < a.length; i++) {\n        if (a[i] !== b[i]) {\n            break;\n        }\n\n        match++;\n    }\n\n    return parseInt(b.substring(0, match).padEnd(b.length, '0'), 2);\n};",
        "solution_java": "class Solution {\npublic int rangeBitwiseAnd(int left, int right) {\n    int count=0;\n    while(left!=right){\n        left>>=1;\n        right>>=1;\n        count++;\n    }\n    return right<<=count;\n}",
        "solution_c": "class Solution {\npublic:\n    int rangeBitwiseAnd(int left, int right) {\n        int t=0;\n        while(left!=right){\n            left= left>>1;\n            right= right>>1;\n            t++;\n        }\n        int ans= left;\n        while(t--){\n            ans= ans<<1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Depth of Binary Tree",
        "algo_input": "Given a binary tree, find its minimum depth.\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\n\nNote:&nbsp;A leaf is a node with no children.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 2\n\n\nExample 2:\n\nInput: root = [2,null,3,null,4,null,5,null,6]\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 105].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def minDepth(self, root):\n        # Base case...\n        # If the subtree is empty i.e. root is NULL, return depth as 0...\n        if root is None:  return 0\n        # Initialize the depth of two subtrees...\n        leftDepth = self.minDepth(root.left)\n        rightDepth = self.minDepth(root.right)\n        # If the both subtrees are empty...\n        if root.left is None and root.right is None:\n            return 1\n        # If the left subtree is empty, return the depth of right subtree after adding 1 to it...\n        if root.left is None:\n            return 1 + rightDepth\n        # If the right subtree is empty, return the depth of left subtree after adding 1 to it...\n        if root.right is None:\n            return 1 + leftDepth\n        # When the two child function return its depth...\n        # Pick the minimum out of these two subtrees and return this value after adding 1 to it...\n        return min(leftDepth, rightDepth) + 1;    # Adding 1 is the current node which is the parent of the two subtrees...",
        "solution_js": "var minDepth = function(root) {\n    if (!root){\n        return 0\n    }\n    if(root.left && root.right){\n        return Math.min(minDepth(root.left), minDepth(root.right)) + 1\n    }\n    if(root.right){\n        return minDepth(root.right) + 1\n    }\n    if(root.left){\n        return minDepth(root.left) + 1\n    }\n    return 1\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public int minDepth(TreeNode root) {\n        if(root == null)\n            return 0;\n        \n        int left = minDepth(root.left);\n        int right = minDepth(root.right);\n        if(root.left == null)\n            return right+1;\n        if(root.right == null)\n            return left+1;\n        return Math.min(left, right)+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void maxlevel(TreeNode* root,int level,int &ans){\n        if(!root)\n            return ;\n\n        if(!root->left && !root->right){\n            ans=min(level,ans);\n            return ;\n        }\n\n        maxlevel(root->left,level+1,ans);\n        maxlevel(root->right,level+1,ans);\n    }\n    int minDepth(TreeNode* root) {\n        if(!root)\n            return 0;\n\n        int ans=INT_MAX;\n        maxlevel(root,0,ans);\n        return ans+1;\n    }\n};"
    },
    {
        "title": "Lexicographical Numbers",
        "algo_input": "Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.\n\nYou must write an algorithm that runs in&nbsp;O(n)&nbsp;time and uses O(1) extra space.&nbsp;\n\n&nbsp;\nExample 1:\nInput: n = 13\nOutput: [1,10,11,12,13,2,3,4,5,6,7,8,9]\nExample 2:\nInput: n = 2\nOutput: [1,2]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 5 * 104\n\n",
        "solution_py": "class Solution:\n    def lexicalOrder(self, n: int) -> List[int]:\n        result = []\n        orderDic = {}\n        for i in range(1, n + 1):\n            strI = str(i)\n            level = orderDic\n            for char in strI:\n                if char not in level:\n                    level[char] = {}\n                level = level[char]\n        self.traverse(orderDic, \"\", result)\n        return result\n        \n    def traverse(self, dic, temp, result):\n        for key in dic:\n            result.append(int(temp + key))\n            self.traverse(dic[key], temp + key, result)",
        "solution_js": "/**\n * @param {number} n\n * @return {number[]}\n */\nvar lexicalOrder = function(n) {\n    const arr = [];\n    \n    function dfs(baseIndex) {\n        if (baseIndex * 10 > n) {\n            return;\n        }\n        \n        for(let i = baseIndex * 10; i < baseIndex * 10 + 10 && i <= n; i++)  {\n           arr.push(i);\n           dfs(i);\n        }\n    }\n    \n    let stack = [];\n    \n    for(let i = 1; i <= 9 && i <= n; i++) {\n        arr.push(i);        \n        dfs(i);\n    }\n    \n    return arr;\n};",
        "solution_java": "class Solution {\n\n    private final TrieNode trie = new TrieNode(' ');\n\n    class TrieNode{\n\n        private Character digit;\n        private String value;\n        private boolean isWord;\n        private Map<Character, TrieNode> children;\n\n        TrieNode(Character c){\n            this.digit = c;\n            this.isWord = false;\n            this.children = new HashMap<>();\n        }\n\n        void insert(String s){\n            TrieNode current = this;\n            for(Character c : s.toCharArray()){\n                current = current.children.computeIfAbsent(c, k -> new TrieNode(c));\n            }\n            current.value = s;\n            current.isWord = true;\n        }\n\n        List<Integer> getWordsPreOrder(){\n            return getWordsPreOrder(this);\n        }\n\n        private List<Integer> getWordsPreOrder(TrieNode root){\n            List<Integer> result = new ArrayList<>();\n            if(root == null){\n                return result;\n            }\n\n            if(root.isWord){\n                result.add(Integer.parseInt(root.value));\n            }\n            for(TrieNode node : root.children.values()){\n                result.addAll(getWordsPreOrder(node));\n            }\n            return result;\n        }\n    }\n\n    public List<Integer> lexicalOrder(int n) {\n        for(int i = 1 ; i<=n;i++){\n            trie.insert(String.valueOf(i));\n        }\n        return trie.getWordsPreOrder();\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    void dfs(int i, int n, vector<int> &ans){\n        if(i > n) return;\n        ans.push_back(i);\n        for(int j = 0; j< 10; ++j) dfs(i * 10 + j, n, ans);\n    }\npublic:\n    vector<int> lexicalOrder(int n) {\n        vector<int> ans;\n        for(int i =1; i<10; ++i) dfs(i, n, ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Increasing Subsequence",
        "algo_input": "Given an integer array nums, return the length of the longest strictly increasing subsequence.\n\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nExplanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n\n\nExample 2:\n\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\n\n\nExample 3:\n\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2500\n\t-104 &lt;= nums[i] &lt;= 104\n\n\n&nbsp;\nFollow up:&nbsp;Can you come up with an algorithm that runs in&nbsp;O(n log(n)) time complexity?\n",
        "solution_py": "class Solution:\n    def lengthOfLIS(self, nums: list[int]) -> int:\n\n        # Initialize the result\n        res = []\n\n        # Binary search to find the index of the smallest number in result that is greater than or equal to the target\n        def binarySearch(l, r, target):\n\n            nonlocal res\n\n            # If the left and right pointers meet, we have found the smallest number that is greater than the target\n            if l == r:\n                return l\n\n            # Find the mid pointer\n            m = (r - l) // 2 + l\n\n            # If the number at the mid pointer is equal to the target, we have found a number that is equal to the target\n            if res[m] == target:\n                return m\n\n            # Else if the number at the mid poitner is less than the target, we search the right side\n            elif res[m] < target:\n                return binarySearch(m + 1, r, target)\n\n            # Else, we search the left side including the number at mid pointer because it is one of the possible solution since it is greater than the target\n            else:\n                return binarySearch(l, m, target)\n\n        # Iterate through all numbers\n        for n in nums:\n\n            # If the last number in the result is less than the current number\n            if not res or res[-1] < n:\n\n                # Append the current number to the result\n                res.append(n)\n\n                continue\n\n            # Else, find the index of the smallest number in the result that is greater than or equal to the current number\n            i = binarySearch(0, len(res) - 1, n)\n\n            # Replace the current number at such index\n            res[i] = n\n\n        return len(res)",
        "solution_js": "var lengthOfLIS = function(nums) {\n  let len = nums.length;\n  let dp = Array.from({length: len}, v => 1);\n  \n  for (let i = 1 ; i < len; i++) {\n    for (let j = 0; j < i; j++) {\n      if (nums[i] > nums[j] && dp[i] <= dp[j]) {\n        dp[i] = dp[j] + 1;\n      }\n    }\n  }\n  \n  return Math.max(...dp);\n};",
        "solution_java": "class Solution {\n    public int lengthOfLIS(int[] nums) {\n\n        ArrayList<Integer> lis = new ArrayList<>();\n\n        for(int num:nums){\n\n            int size = lis.size();\n\n            if(size==0 ||size>0 && num>lis.get(size-1)){\n                lis.add(num);\n            }else{\n                int insertIndex = bs(lis,num);\n                lis.set(insertIndex,num);\n            }\n        }\n\n        return lis.size();\n    }\n\n    int bs(List<Integer> list, int target){\n        int lo = 0;\n        int hi = list.size()-1;\n\n        while(lo<hi){\n            int mid = (lo+hi)/2;\n            if(list.get(mid)<target){\n                lo=mid+1;\n            }else{\n                hi=mid;\n            }\n        }\n        return lo;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lengthOfLIS(vector<int>& nums) {\n        int n = nums.size();\n        vector<int>dp(n,1);\n        for(int i=n-2;i>=0;i--){\n            for(int j=i+1;j<n;j++){\n                if(nums[j]>nums[i])dp[i]=max(dp[i],1+dp[j]);\n            }\n        }\n       int mx=0;\n       for(int i=0;i<n;i++)mx=max(mx,dp[i]);\n       return mx;\n    }\n};"
    },
    {
        "title": "Subarray Product Less Than K",
        "algo_input": "Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,5,2,6], k = 100\nOutput: 8\nExplanation: The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n\n\nExample 2:\n\nInput: nums = [1,2,3], k = 0\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t1 &lt;= nums[i] &lt;= 1000\n\t0 &lt;= k &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n        if k==0 or k==1:\n            return 0\n        p=1\n        ini=0\n        fin=0\n        n=len(nums)\n        c=0\n        while fin<n:\n            p=p*nums[fin]\n            while p>=k :\n                p=p//nums[ini]\n                ini+=1\n\n            n1=fin-ini+1\n            c+=n1\n            fin+=1\n        return c",
        "solution_js": "var numSubarrayProductLessThanK = function(nums, k) {\n    var used = new Array(nums.length).fill(0);\n    var l, r, runsum=1;\n    let ans=0;\n    \n    l = 0;\n    r = 0;\n    while( r < nums.length ) {\n        if( r < nums.length && runsum * nums[r] >= k ) {\n            if( r != l )\n                runsum /= nums[l];\n            else\n                r++;\n            l++;\n        } else if( l <= r ) {\n            runsum *= nums[r];\n            r++;\n            ans += (r-l);\n        } else break;\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int numSubarrayProductLessThanK(int[] nums, int k) {\n\t\t//if k=0 then ans will always be zero as we have positive integers array only.\n        if(k==0)\n            return 0;\n        \n        int length = 0;\n        long product = 1;\n        int i = 0;\n        int j = 0;\n        int n = nums.length;\n        int ans = 0;\n        \n        while(j<n){\n            product*=nums[j];\n\t\t\t//Add the number to current window if the product is less than k and calculate no of subarrays using length only.\n            if(product<k){\n                length+=1;\n                ans+=length;\n            }\n            else{\n\t\t\t\t//Remove element one by one till product becomes less than k.\n                while(i<=j && product>=k){\n                    product/=nums[i];\n                    i++;\n                }\n\t\t\t\t//As we have added only 1 element to the window and this element can make subarray to j-i element along with itself.\n                ans+=(j-i)+1;\n\t\t\t\t//Update the current subarray length.\n                length=j-i+1;\n            }\n            j++;\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numSubarrayProductLessThanK(vector<int>& nums, int k) {\n        int start = 0;\n        long prod = 1;\n        int count =0; // count of subarray prod  less than k\n        for(int end =0; end< nums.size(); end++){\n            prod *= nums[end];\n    \n           while(prod >= k && start < nums.size()){\n               prod = prod/nums[start];// divide product by nums at start pointer t reduce the prod\n                start++;//move start pointer because no longer nums at start can give us prod < k\n              }\n           if(prod < k)\n            count += end - start +1;\n      }\n    return count;\n    }\n};"
    },
    {
        "title": "Count Odd Numbers in an Interval Range",
        "algo_input": "Given two non-negative integers low and high. Return the count of odd numbers between low and high&nbsp;(inclusive).\n\n&nbsp;\nExample 1:\n\nInput: low = 3, high = 7\nOutput: 3\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\n\nExample 2:\n\nInput: low = 8, high = 10\nOutput: 1\nExplanation: The odd numbers between 8 and 10 are [9].\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= low &lt;= high&nbsp;&lt;= 10^9\n",
        "solution_py": "class Solution:\n    def countOdds(self, low: int, high: int) -> int:        \n        total_nums = high - low\n        \n        answer = total_nums // 2\n        \n        if low % 2 == 1 and high % 2 == 1:\n            return answer + 1\n        \n        if low % 2 == 1:\n            answer = answer + 1\n            \n        if high % 2 == 1:\n            answer = answer + 1\n        \n        return answer",
        "solution_js": "var countOdds = function(low, high) {\n    let total = 0;\n    for (let i = low; i <= high; i++) {\n        if (i % 2 !== 0) {\n            total++;\n        }\n    }\n    return total;\n};",
        "solution_java": "class Solution {\n    public int countOdds(int low, int high) {\n        if(low%2==0 && high%2==0){\n            return (high-low)/2;\n        }\n        return (high-low)/2+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countOdds(int low, int high) {\n        if (low%2 == 0 && high%2 == 0 ){\n            return (high - low)/2;\n        }\n        else{\n            return (high - low)/2 + 1;\n        }\n\n    }\n};"
    },
    {
        "title": "2 Keys Keyboard",
        "algo_input": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:\n\n\n\tCopy All: You can copy all the characters present on the screen (a partial copy is not allowed).\n\tPaste: You can paste the characters which are copied last time.\n\n\nGiven an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 3\nExplanation: Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def minSteps(self, n: int) -> int:      \n        # at every step we can copy or paste\n        # paste -> we need to know the current clipboard content (count)\n        # copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste)\n        \n        memo = {}\n        \n        def dfs(clipboard_count, screen_count):\n            if (clipboard_count, screen_count) in memo:                   \n                return memo[(clipboard_count, screen_count)]\n            \n            # we reached n, this is a valid option\n            if screen_count == n: return 0\n            \n            # we passed n, not a valid option\n            if screen_count > n: return float('inf')                \n            \n            # paste or copy\n            copy_opt = paste_opt = float('inf')\n            \n            # we should only paste if clipboard is not empty\n            if clipboard_count > 0:\n                paste_opt = dfs(clipboard_count, screen_count + clipboard_count)             \n            \n            # we should consider copy only if the last operation was paste\n            if screen_count > clipboard_count:\n                copy_opt = dfs(screen_count, screen_count) \n            \n            # save to memo\n            memo[(clipboard_count, screen_count)] = 1 + min(paste_opt, copy_opt)            \n            return memo[(clipboard_count, screen_count)]\n            \n        return dfs(0, 1)\n            ",
        "solution_js": "var minSteps = function(n) {\n\tlet result = 0;\n\n\tfor (let index = 2; index <= n; index++) {\n\t\twhile (n % index === 0) {\n\t\t\tresult += index;\n\t\t\tn /= index;\n\t\t}\n\t}\n\treturn result;\n};",
        "solution_java": "class Solution {\n    public int minSteps(int n) {\n        int rem = n-1, copied = 0, ans = 0, onScreen = 1;\n        \n        while(rem>0){\n            if(rem % onScreen == 0){\n                ans++; // copy operation\n                copied = onScreen;   \n            }\n            rem-=copied;\n            ans++; // paste operation\n            onScreen = n-rem; // no. of characters on screen currently that can be copied in next copy operation\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n//See the solution for this explanation \n    int byPrimeFactorization(int n) {\n        if(n == 1)\n            return 0;\n        if(n == 2)\n            return 2;\n        int factor = 2, ans = 0;\n        while(n > 1) {\n            while(n % factor == 0) {\n                ans += factor;\n                n /= factor;\n            }\n            factor++;\n        }\n        return ans;\n    }\n   \n    int byDp(int n) {\n        vector<int> dp(1001, INT_MAX);\n        dp[0] = dp[1] = 0;\n        dp[2] = 2, dp[3] = 3;\n        for(int i = 4; i <= n; i++) {\n            dp[i] = i; //maximum number of operations required will be i\n            for(int j = 2; j <= i / 2; j++) { //we copy and paste j A's till we have i A's\n                int x = i - j; //we already have j A's in our stream, so remaining = i - j\n                if(x % j == 0) { //if remaining number of A's is a multiple of J\n                    dp[i] = min(dp[i], dp[j] + 1 + (x / j)); //1 operation to copy, x / j to paste, dp[j] for getting j A's\n                }\n            }\n        }\n        return dp[n];\n    }\n    \n    int minSteps(int n) {\n        return byPrimeFactorization(n);\n    }\n};"
    },
    {
        "title": "Find Largest Value in Each Tree Row",
        "algo_input": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).\n\n&nbsp;\nExample 1:\n\nInput: root = [1,3,2,5,3,null,9]\nOutput: [1,3,9]\n\n\nExample 2:\n\nInput: root = [1,2,3]\nOutput: [1,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [0, 104].\n\t-231 &lt;= Node.val &lt;= 231 - 1\n\n",
        "solution_py": "class Solution(object):\n    def largestValues(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: List[int]\n        \"\"\"\n        if not root:\n            return []\n        ans=[]\n        q=[]\n        q.append(root)\n        while q:\n            s=len(q)\n            t=[]\n            for i in range(s):\n                n=q.pop(0)\n                t.append(n.val)\n                if n.left:\n                    q.append(n.left)\n                if n.right:\n                    q.append(n.right)\n            ans.append(max(t))\n        return ans",
        "solution_js": "var largestValues = function(root) {\n    if(!root) return [];\n    \n    const op = [];\n    const Q = [[root, 1]];\n    while(Q.length) {\n        const [r, l] = Q.shift();\n        \n        if(op.length < l) op.push(-Infinity);\n        op[l-1] = Math.max(op[l-1], r.val);\n        \n        if(r.left) Q.push([r.left, l + 1]);\n        if(r.right) Q.push([r.right, l + 1]);\n    }\n    return op;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n    private List<Integer> li=new ArrayList<>();\n\n    public List<Integer> largestValues(TreeNode root) {\n\n        if(root==null) return li; //if root is NULL\n\n        //using bfs(level-order)\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(root);\n        while(!q.isEmpty()){\n            int size=q.size();\n            int res=Integer.MIN_VALUE;\n            while(size-->0){\n                TreeNode temp=q.poll();\n                if(temp.left!=null) q.add(temp.left);\n                if(temp.right!=null) q.add(temp.right);\n                res =Math.max(res,temp.val); //comparing every node in each level to get max\n            }\n            li.add(res); //adding each level Max value to the list\n        }\n        return li;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int>res;\n    vector<int> largestValues(TreeNode* root) {\n        if(!root) return {};\n        if(!root->left && !root->right) return {root->val};\n        TreeNode*temp;\n        int mx = INT_MIN;\n        queue<TreeNode*>q;\n        q.push(root);\n\n        while(!q.empty()){\n            int sz = q.size();\n            while(sz--){\n                temp = q.front();\n                if(temp->val > mx) mx = temp->val;\n                q.pop();\n                if(temp->left) q.push(temp->left);\n                if(temp->right) q.push(temp->right);\n            }\n            res.push_back(mx);\n            mx = INT_MIN;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Finding MK Average",
        "algo_input": "You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\n\nThe MKAverage can be calculated using these steps:\n\n\n\tIf the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.\n\tRemove the smallest k elements and the largest k elements from the container.\n\tCalculate the average value for the rest of the elements rounded down to the nearest integer.\n\n\nImplement the MKAverage class:\n\n\n\tMKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.\n\tvoid addElement(int num) Inserts a new element num into the stream.\n\tint calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\nOutput\n[null, null, null, -1, null, 3, null, null, null, 5]\n\nExplanation\nMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3);        // current elements are [3]\nobj.addElement(1);        // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10);       // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n                          // After removing smallest and largest 1 element the container will be [3].\n                          // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5);        // current elements are [3,1,10,5]\nobj.addElement(5);        // current elements are [3,1,10,5,5]\nobj.addElement(5);        // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n                          // After removing smallest and largest 1 element the container will be [5].\n                          // The average of [5] equals 5/1 = 5, return 5\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= m &lt;= 105\n\t1 &lt;= k*2 &lt; m\n\t1 &lt;= num &lt;= 105\n\tAt most 105 calls will be made to addElement and calculateMKAverage.\n\n",
        "solution_py": "from sortedcontainers import SortedList\n\nclass MKAverage:\n\n    MAX_NUM = 10 ** 5\n    def __init__(self, m: int, k: int):\n        \n        self.m = m\n        self.k = k\n        \n        # sorted list\n        self.sl = SortedList([0] * m)\n\t\t# sum of k smallest elements\n        self.sum_k = 0\n\t\t# sum of m - k smallest elements\n        self.sum_m_k = 0\n        \n        # queue for the last M elements if the stream\n        self.q = deque([0] * m)\n        \n    def addElement(self, num: int) -> None:\n        # Time: O(logm)\n\t\t\n        m, k, q, sl = self.m, self.k, self.q, self.sl            \n            \n        # update q\n        q.append(num)\n        old = q.popleft()\n        \n        # remove the old num\n        r = sl.bisect_right(old)\n\t\t# maintain sum_k\n        if r <= k:\n            self.sum_k -= old\n            self.sum_k += sl[k]\n\t\t# maintain sum_m_k\n        if r <= m - k:\n            self.sum_m_k -= old\n            self.sum_m_k += sl[m-k]\n        # remove the old num\n        sl.remove(old)\n        \n        # add the new num\n        r = sl.bisect_right(num)\n        if r < k:\n            self.sum_k -= sl[k-1]\n            self.sum_k += num\n        if r < m - k:\n            self.sum_m_k -= sl[m - k - 1]\n            self.sum_m_k += num\n        \n        sl.add(num)\n            \n        return\n\n    def calculateMKAverage(self) -> int:\n\t\t# Time: O(1)\n        if self.sl[0] == 0:\n            return -1\n        return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)",
        "solution_js": "class ArraySegTree{\n    // Array to perfrom operations on, range query operation, PointUpdate operation\n    constructor(A,op=(a,b)=>a+b,upOp=(a,b)=>a+b,opSentinel=0){\n        this.n=A.length,this.t=[...Array(4*this.n+1)],this.op=op,this.upOp=upOp,this.opSentinel=opSentinel\n        //root's idx =1\n        this.build(A,1,0,this.n-1)\n    }\n    left=x=>this.t[2*x];right=x=>this.t[2*x+1]\n    build(A,idx,left,right){\n        if(left==right)\n            return this.t[idx]=A[left]\n        let mid=(left+right)>>1\n        this.build(A,2*idx,left,mid) //go left\n        this.build(A,2*idx+1,mid+1,right) //go right\n        this.t[idx]=this.op(this.left(idx),this.right(idx)) //merge\n    }\n    //just specify l,r on actual queries\n    //Here queries use the actul indices of the starting array A, so rangeQuery(0,n-1) returns the whole array\n    rangeQuery=(l,r,tl=0,tr=this.n-1,idx=1)=>{\n        if(l>r)\n            return this.opSentinel\n        if(l===tl&&r===tr)\n            return this.t[idx]\n        let mid=(tl+tr)>>1\n        return this.op(\n                this.rangeQuery(l,Math.min(r,mid),tl,mid,idx*2),\n                this.rangeQuery(Math.max(l,mid+1),r,mid+1,tr,idx*2+1)\n        )\n    }\n    //just specify arrIdx,newVal on actual pointUpdates\n    pointUpdate=(arrIdx,newVal,tl=0,tr=this.n-1,idx=1)=>{\n        if(tl==tr)\n            return this.t[idx]=this.upOp(this.t[idx],newVal)\n        let mid=(tl+tr)>>1\n        if(arrIdx<=mid)\n            this.pointUpdate(arrIdx,newVal,tl,mid,2*idx)\n        else\n            this.pointUpdate(arrIdx,newVal,mid+1,tr,2*idx+1)\n        this.t[idx]=this.op(this.left(idx),this.right(idx))\n    }\n    seachPrefixIndex=(x,start=0,end=this.n-1)=>{\n        let s=this.rangeQuery(start,end)\n        if(s<x)\n            return -1\n        if(start===end)\n            return start\n        let mid=start+end>>1,left=this.rangeQuery(start,mid)\n        if( left>=x)\n            return this.seachPrefixIndex(x,start,mid)\n        else\n            return this.seachPrefixIndex(x-left,mid+1,end)\n    }\n}\n\nvar MKAverage = function(m, k) {\n    this.A=[],this.m=m,this.k=k,this.div=m-2*k\n    this.S1=new ArraySegTree([...Array(1e5+2)].map(d=>0))//indices\n    this.S2=new ArraySegTree([...Array(1e5+2)].map(d=>0))//sums\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nMKAverage.prototype.addElement = function(num) {\n    this.A.push(num)\n    this.S1.pointUpdate(num,1)\n    this.S2.pointUpdate(num,num)\n    if(this.A.length>this.m){\n        let z=this.A.shift()\n        this.S1.pointUpdate(z,-1)\n        this.S2.pointUpdate(z,-z)\n    }\n};\n\n/**\n * @return {number}\n */\nMKAverage.prototype.calculateMKAverage = function() {\n    if(this.A.length<this.m)\n        return -1\n\n    let S=this.S1.seachPrefixIndex(this.k+1),\n        count1=this.S1.rangeQuery(0,S),\n        take=(count1-this.k)*S\n\n    let E=this.S1.seachPrefixIndex(this.m-this.k),\n        count2=this.S1.rangeQuery(0,E),\n        remove=(count2-this.m+this.k)*E\n\n    let midSum=this.S2.rangeQuery(S+1,E)\n    return (take+midSum-remove)/this.div>>0\n};",
        "solution_java": "class MKAverage {\n    class Node implements Comparable<Node> {\n        int val;\n        int time;\n        \n        Node(int val, int time) {\n            this.val = val;\n            this.time = time;\n        }\n        \n        @Override\n        public int compareTo(Node other) {\n            return (this.val != other.val ? this.val - other.val \n                                          : this.time - other.time);\n        }\n    }\n    \n    private TreeSet<Node> set = new TreeSet<>();          // natural order\n    private Deque<Node> queue = new LinkedList<>();\n    private Node kLeft;\n    private Node kRight;\n    \n    private int m, k;\n    \n    private int time = 0;\n    private int sum = 0;\n\n    public MKAverage(int m, int k) {\n        this.m = m;\n        this.k = k;\n    }\n    \n    public void addElement(int num) {\n        Node node = new Node(num, time++);\n\n        addNode(node);\n        removeNode();\n        \n        if (time == m) init();\n    }\n    \n    private void init() {\n        int i = 0;\n        for (Node node : set) {\n            if (i < k-1);\n            else if (i == k-1) kLeft = node;\n            else if (i < m-k) sum += node.val;\n            else if (i == m-k) {\n                kRight = node;\n                return;\n            }\n            \n            i++;\n        }\n        return;\n    }\n    \n    private void addNode(Node node) {\n        queue.offerLast(node);\n        set.add(node);\n        \n        if (queue.size() <= m) return;\n        \n        if (node.compareTo(kLeft) < 0) {\n            sum += kLeft.val;\n            kLeft = set.lower(kLeft);\n        } else if (node.compareTo(kRight) > 0) {\n            sum += kRight.val;\n            kRight = set.higher(kRight);\n        } else {\n            sum += node.val;\n        } \n    }\n    \n    private void removeNode() {\n        if (queue.size() <= m) return;\n        \n        Node node = queue.pollFirst();\n        \n        if (node.compareTo(kLeft) <= 0) {\n            kLeft = set.higher(kLeft);\n            sum -= kLeft.val;\n        } else if (node.compareTo(kRight) >= 0) {\n            kRight = set.lower(kRight);\n            sum -= kRight.val;\n        } else {\n            sum -= node.val;\n        }\n        \n        set.remove(node);\n    }\n    \n    public int calculateMKAverage() {\n        return (queue.size() < m ? -1 : sum / (m - 2 * k));\n    }\n}",
        "solution_c": "/* \n    Time: addElement: O(logm) | calculateMKAverage: O(1)\n    Space: O(m)\n    Tag: TreeMap, Sorting, Queue\n    Difficulty: H\n*/\n\nclass MKAverage {\n    map<int, int> left, middle, right;\n    queue<int> q;\n    int sizeofLeft, sizeofMiddle, sizeofRight;\n    int k;\n    long long mkSum;\n    int m;\n\n    void addToSet1(int num) {\n        left[num]++;\n        sizeofLeft++;\n    }\n\n    void deleteFromSet1(int num) {\n        left[num]--;\n        if (left[num] == 0) left.erase(num);\n        sizeofLeft--;\n    }\n\n    void addToSet2(int num) {\n        middle[num]++;\n        sizeofMiddle++;\n        mkSum += num;\n    }\n\n    void deleteFromSet2(int num) {\n        middle[num]--;\n        if (middle[num] == 0) middle.erase(num);\n        sizeofMiddle--;\n        mkSum -= num;\n    }\n\n    void addToSet3(int num) {\n        right[num]++;\n        sizeofRight++;\n    }\n\n    void deleteFromSet3(int num) {\n        right[num]--;\n        if (right[num] == 0) right.erase(num);\n        sizeofRight--;\n    }\n\npublic:\n    MKAverage(int m, int k) {\n        sizeofLeft = 0, sizeofMiddle = 0, sizeofRight = 0;\n        mkSum = 0;\n        this->k = k;\n        this->m = m;\n    }\n\n    void addElement(int num) {\n        if (sizeofLeft < k) {\n            addToSet1(num);\n            q.push(num);\n        } else if (sizeofMiddle < (m - (2 * k))) {\n            int lastEle = prev(left.end())->first;\n            if (num >= lastEle) {\n                addToSet2(num);\n            } else {\n                deleteFromSet1(lastEle);\n                addToSet1(num);\n                addToSet2(lastEle);\n            }\n            q.push(num);\n        } else if (sizeofRight < k) {\n            int last1 = prev(left.end())->first;\n            int last2 = prev(middle.end())->first;\n            if (num >= last1 && num >= last2) {\n                addToSet3(num);\n            } else if (num >= last1 && num < last2) {\n                deleteFromSet2(last2);\n                addToSet2(num);\n                addToSet3(last2);\n            } else {\n                deleteFromSet2(last2);\n                addToSet3(last2);\n                deleteFromSet1(last1);\n                addToSet2(last1);\n                addToSet1(num);\n            }\n            q.push(num);\n        } else {\n            int toErase = q.front();\n            q.pop();\n            int first3 = right.begin()->first;\n            int first2 = middle.begin()->first;\n            int first1 = left.begin()->first;\n\n            if (toErase >= first3) {\n                deleteFromSet3(toErase);\n            } else if (toErase >= first2) {\n                deleteFromSet3(first3);\n                deleteFromSet2(toErase);\n                addToSet2(first3);\n            } else {\n                deleteFromSet3(first3);\n                deleteFromSet2(first2);\n                deleteFromSet1(toErase);\n                addToSet1(first2);\n                addToSet2(first3);\n            }\n            addElement(num);\n        }\n    }\n\n    int calculateMKAverage() {\n        if (q.size() < m) return -1;\n        return mkSum / (m - (2 * k));\n    }\n};"
    },
    {
        "title": "Rotate Image",
        "algo_input": "You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n\nYou have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[7,4,1],[8,5,2],[9,6,3]]\n\n\nExample 2:\n\nInput: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 &lt;= n &lt;= 20\n\t-1000 &lt;= matrix[i][j] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    \n    def rotate(self, matrix: List[List[int]]) -> None:\n        \"\"\"\n        Do not return anything, modify matrix in-place instead.\n        \"\"\"\n        # transpose \n        size = len(matrix)\n        for i in range(size):\n            for j in range(i+1, size):\n                matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]\n        \n        print(matrix)\n        \n        # reverse row\n        for row in range(len(matrix)):\n            matrix[row] = matrix[row][::-1]\n        \n        print(matrix)",
        "solution_js": "/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nvar rotate = function(matrix) {\n    let m = matrix.length;\n    let n = matrix[0].length;\n    \n    for (let i = m - 1; i >= 0; i--) {\n        for (let j = 0; j < m; j++) {\n            matrix[j].push(matrix[i].shift());\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public void swap(int[][] matrix, int n1, int m1, int n2, int m2) {\n        int a = matrix[n1][m1];\n        int temp = matrix[n2][m2];\n        matrix[n2][m2] = a;\n        matrix[n1][m1] = temp;\n    }\n    public void rotate(int[][] matrix) {\n        int n = matrix.length;\n        for (int i = 0; i < n/2; i++) {\n            for (int j = 0; j < n; j++) {\n                swap(matrix, i,j, n-i-1, j);\n            }\n        }\n        for (int i = n-1; i >= 0; i--) {\n            for (int j = 0; j < i; j++) {\n                swap(matrix, i,j, j, i);\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void rotate(vector<vector<int>>& matrix) {\n        int row = matrix.size();\n        for(int i=0;i<row; i++){\n            for(int j=0; j<=i;j++){\n                swap(matrix[i][j], matrix[j][i]);\n            }\n        }\n        for(int i=0;i<row;i++){\n            reverse(matrix[i].begin(), matrix[i].end());\n        }\n    }\n};"
    },
    {
        "title": "Invalid Transactions",
        "algo_input": "A transaction is possibly invalid if:\n\n\n\tthe amount exceeds $1000, or;\n\tif it occurs within (and including) 60 minutes of another transaction with the same name in a different city.\n\n\nYou are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.\n\nReturn a list of transactions that are possibly invalid. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nOutput: [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nExplanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.\n\nExample 2:\n\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\nOutput: [\"alice,50,1200,mtv\"]\n\n\nExample 3:\n\nInput: transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\nOutput: [\"bob,50,1200,mtv\"]\n\n\n&nbsp;\nConstraints:\n\n\n\ttransactions.length &lt;= 1000\n\tEach transactions[i] takes the form \"{name},{time},{amount},{city}\"\n\tEach {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.\n\tEach {time} consist of digits, and represent an integer between 0 and 1000.\n\tEach {amount} consist of digits, and represent an integer between 0 and 2000.\n\n",
        "solution_py": "class Transaction:\n    def __init__(self, name, time, amount, city):\n        self.name = name\n        self.time = int(time)\n        self.amount = int(amount)\n        self.city = city\n\nfrom collections import defaultdict\nclass Solution:\n    def invalidTransactions(self, transactions):\n        transactions = [Transaction(*transaction.split(',')) for transaction in transactions]\n        transactions.sort(key=lambda t: t.time) # O(nlogn) time\n\n        trans_indexes = defaultdict(list)\n        for i, t in enumerate(transactions): # O(n) time\n            trans_indexes[t.name].append(i)\n\n        res = []\n        for name, indexes in trans_indexes.items(): # O(n) time\n            left = right = 0\n            for i, t_index in enumerate(indexes):\n                t = transactions[t_index]\n                if (t.amount > 1000):\n                    res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n                    continue\n                while left <= len(indexes)-2 and transactions[indexes[left]].time < t.time - 60: # O(60) time\n                    left += 1\n                while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time\n                    right += 1\n                for i in range(left,right+1): # O(120) time\n                    if transactions[indexes[i]].city != t.city:\n                        res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n                        break\n\n        return res",
        "solution_js": "var invalidTransactions = function(transactions) {\n    const invalid = new Uint8Array(transactions.length).fill(false);\n\n    for(let i = 0; i < transactions.length; i++){\n        const [name, time, amount, city] = transactions[i].split(',');\n\n        if(+amount > 1000) invalid[i] = true;\n\n        for(let j = i + 1; j < transactions.length; j++){\n            const [name1, time1, amount1, city1] = transactions[j].split(',');\n\n            if(Math.abs(+time - +time1) <= 60 && name === name1 && city !== city1){\n                invalid[i] = true;\n                invalid[j] = true;\n            }\n        }\n    }\n\n    return invalid.reduce((acc, val, index) => {\n        if(val) acc.push(transactions[index])\n        return acc;\n    }, [])\n};",
        "solution_java": "class Solution {\n  public List<String> invalidTransactions(String[] transactions) {\n    Map<String, List<Transaction>> nameToTransaction = new HashMap<>();\n    for (int i = 0; i < transactions.length; i++) {\n      Transaction t = new Transaction(transactions[i], i);\n      nameToTransaction.putIfAbsent(t.name, new ArrayList<>());\n      nameToTransaction.get(t.name).add(t);\n    }\n    List<String> invalid = new ArrayList<>();\n    for (List<Transaction> list : nameToTransaction.values()) {\n      for (Transaction t : list) {\n        if (t.isInvalidAmount()) invalid.add(transactions[t.id]);\n        else {\n          for (Transaction otherT : list) {\n            if (t.isInvalidCity(otherT)) {\n              invalid.add(transactions[t.id]);\n              break;\n            }\n          }\n        }\n      }\n    }\n    return invalid;\n  }\n}\n\nclass Transaction {\n  String name, city;\n  int time, amount, id;\n\n  Transaction(String s, int id) {\n    this.id = id;\n    String[] split = s.split(\",\");\n    name = split[0];\n    time = Integer.parseInt(split[1]);\n    amount = Integer.parseInt(split[2]);\n    city = split[3];\n  }\n\n  boolean isInvalidAmount() {\n    return this.amount > 1000;\n  }\n\n  boolean isInvalidCity(Transaction t) {\n    return !city.equals(t.city) && Math.abs(t.time - time) <= 60;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    /*\n      this  question is absolutely frustrating 🙂\n    */\n    \n    /*\n        method to split string\n    */\n    vector<string> split(string s){\n      string t=\"\";\n        vector<string> v;\n        for(int i=0;i<s.length();i++){\n            if(s[i]==','){\n                v.push_back(t);\n                t=\"\";\n            }else{\n            t+=s[i];    \n            }\n            \n        }\n        v.emplace_back(t);\n        return v;\n    }\n    \n    /*\n        this function checks the second condition.\n    */\n    bool check(string s,string time,string city,map<string,vector<string>>mp){\n        for(auto x:mp[s]){\n                     vector<string>out=split(x);\n                     int val1=stoi(out[1]);\n                     int val2=stoi(time);\n                     if(out[3]!=city and abs(val2-val1)<=60){\n                        return true;\n                     }\n                 }\n        return false;\n    }\n    \n    \n    vector<string> invalidTransactions(vector<string>& transactions) {\n        vector<string> res;/* stores the result */\n      \n        map<string,vector<string>>mp;/* to search for only that person*/\n        \n        int n=transactions.size();\n        \n        vector<vector<string>>v(n,vector<string>(4));/*ith v stores info about ith transaction*/\n        int c=0;\n        \n        for(auto x:transactions){\n            vector<string> out=split(x);\n            v[c]=out;\n            mp[out[0]].emplace_back(x);\n            c+=1;\n        }\n        \n        for(int i=0;i<n;i++){\n            \n             if(stoi(v[i][2])>1000){\n                 /*\n                    check for first condition\n                 */\n                 res.emplace_back(transactions[i]);\n             }else{\n                 /*\n                    checks for second condition.\n                 */\n                 if(check(v[i][0],v[i][1],v[i][3],mp)){\n                     res.emplace_back(transactions[i]);\n                 }\n             }\n            \n        }\n     \n        return res;\n    }\n};"
    },
    {
        "title": "Count Nodes Equal to Average of Subtree",
        "algo_input": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.\n\nNote:\n\n\n\tThe average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\n\tA subtree of root is a tree consisting of root and all of its descendants.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [4,8,5,0,1,null,6]\nOutput: 5\nExplanation: \nFor the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.\n\n\nExample 2:\n\nInput: root = [1]\nOutput: 1\nExplanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.\n\n\n&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",
        "solution_py": "class Solution:\n    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n        \n        \n        def calculate_average(root):\n            if root:\n                self.summ+=root.val\n                self.nodecount+=1\n                calculate_average(root.left)\n                calculate_average(root.right)\n        \n        \n        def calculate_for_each_node(root):\n            if root:\n                self.summ = 0\n                self.nodecount = 0\n                calculate_average(root)\n                if ((self.summ)//(self.nodecount)) == root.val:\n                    self.count+=1 \n                calculate_for_each_node(root.left)\n                calculate_for_each_node(root.right)\n                \n                \n        self.count = 0\n        calculate_for_each_node(root)       \n        return self.count",
        "solution_js": "var averageOfSubtree = function(root) {\n    let result = 0;\n    \n    const traverse = node => {\n        if (!node) return [0, 0];\n        \n        const [leftSum, leftCount] = traverse(node.left);\n        const [rightSum, rightCount] = traverse(node.right);\n        \n        const currSum = node.val + leftSum + rightSum;\n        const currCount = 1 + leftCount + rightCount;\n        \n        if (Math.floor(currSum / currCount) === node.val) result++;\n        \n        return [currSum, currCount];\n    };\n    \n    traverse(root);\n    return result;\n};",
        "solution_java": "class Solution {\n    int res = 0;\n    public int averageOfSubtree(TreeNode root) {\n        dfs(root);\n        return res;\n    }\n    \n    private int[] dfs(TreeNode node) {\n        if(node == null) {\n            return new int[] {0,0};\n        }\n        \n        int[] left = dfs(node.left);\n        int[] right = dfs(node.right);\n        \n        int currSum = left[0] + right[0] + node.val;\n        int currCount = left[1] + right[1] + 1;\n        \n        if(currSum / currCount == node.val) {\n            res++;\n        }\n            \n        return new int[] {currSum, currCount};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    pair<int,int> func(TreeNode* root,int &ans){\n        if(!root)return {0,0};\n        auto p1=func(root->left,ans);\n        auto p2=func(root->right,ans);\n        int avg=(root->val+p1.first+p2.first)/(p1.second+p2.second+1);\n        if(avg==root->val)ans++;\n        return {root->val+p1.first+p2.first,p1.second+p2.second+1};\n    }\n    int averageOfSubtree(TreeNode* root) {\n        int ans=0;\n        func(root,ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Insertion Sort List",
        "algo_input": "Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.\n\nThe steps of the insertion sort algorithm:\n\n\n\tInsertion sort iterates, consuming one input element each repetition and growing a sorted output list.\n\tAt each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.\n\tIt repeats until no input elements remain.\n\n\nThe following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.\n\n&nbsp;\nExample 1:\n\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\n\n\nExample 2:\n\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 5000].\n\t-5000 &lt;= Node.val &lt;= 5000\n\n",
        "solution_py": "/**\n * Definition for singly-linked list.\n * class ListNode {\n *     val: number\n *     next: ListNode | null\n *     constructor(val?: number, next?: ListNode | null) {\n *         this.val = (val===undefined ? 0 : val)\n *         this.next = (next===undefined ? null : next)\n *     }\n * }\n */\n\nfunction insertionSortList(head: ListNode | null): ListNode | null {\n  if (!head) return null\n  if (!head.next) return head\n\n  let output = head\n  let curr = head.next\n\n  head.next = null\n\n  while (curr) {\n    const next = curr.next\n    const insertion = curr\n\n    output = insert(output, insertion)\n    curr = next as ListNode\n  }\n\n  return output\n}\n\nfunction insert(head: ListNode, other: ListNode) {\n  let curr = head\n  const val = other.val\n\n  if (val <= head.val) {\n    other.next = head\n    return other\n  }\n\n  while (curr) {\n    if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) {\n      other.next = curr.next\n      curr.next = other\n\n      return head\n    }\n\n    curr = curr.next as ListNode\n  }\n\n  return head\n}",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar insertionSortList = function(head) {\n    let ptr = head;\n    \n    while(ptr.next !== null){\n        if(ptr.val <= ptr.next.val)\n            ptr = ptr.next;\n        else{\n            let temp = ptr.next;\n            ptr.next = ptr.next.next;\n            \n            \n            if(temp.val < head.val)\n                {\n                    temp.next = head;\n                    head = temp;\n                }\n            \n            else{\n                let ptr2 = head;\n                while(ptr2.next != null  && temp.val >= ptr2.next.val){\n                    ptr2 = ptr2.next;\n                }\n                temp.next = ptr2.next;\n                ptr2.next = temp;\n            }\n        }\n    }\n    return head;\n};",
        "solution_java": "class Solution {\n    public ListNode insertionSortList(ListNode head) {\n        ListNode cur = head;\n        ListNode temp = new ListNode(-5001);\n        ListNode prev = temp;\n        while(cur != null){\n            ListNode nxt = cur.next;\n            if(prev.val >= cur.val)\n                prev = temp;\n            while(prev.next != null && prev.next.val < cur.val)\n                prev = prev.next;\n            cur.next = prev.next;\n            prev.next = cur;\n            cur = nxt;\n        }\n        return temp.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* insertionSortList(ListNode* head) {\n        ListNode *prev=head,*cur=head->next;\n        while(cur){\n            ListNode *tmp=head,*pt=NULL;\n            while(tmp!=cur and tmp->val < cur->val){\n                pt=tmp;\n                tmp=tmp->next;\n            }\n            if(tmp==cur){\n                prev=prev->next;\n                cur=cur->next;\n                continue;\n            }\n            prev->next=cur->next;\n            if(!pt){\n                cur->next=head;\n                head=cur;\n            }\n            else{\n                pt->next=cur;\n                cur->next=tmp;\n            }\n            cur=prev->next;\n        }\n        return head;\n    }\n};"
    },
    {
        "title": "Find All Anagrams in a String",
        "algo_input": "Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\n&nbsp;\nExample 1:\n\nInput: s = \"cbaebabacd\", p = \"abc\"\nOutput: [0,6]\nExplanation:\nThe substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n\n\nExample 2:\n\nInput: s = \"abab\", p = \"ab\"\nOutput: [0,1,2]\nExplanation:\nThe substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, p.length &lt;= 3 * 104\n\ts and p consist of lowercase English letters.\n\n",
        "solution_py": "from collections import Counter\nclass Solution:\n    def findAnagrams(self, s: str, p: str) -> List[int]:\n        l='abcdefghijklmnopqrstuvwxyz'\n        if len(p)>len(s):\n            return []\n        d={}\n        for x in l:\n            d[x]=0\n        d1=dict(d)\n        d2=dict(d)\n        for x in range(len(p)):\n            d1[s[x]]+=1\n            d2[p[x]]+=1\n        l1=[]\n        if d1==d2:\n            l1=[0]\n        #print(d1)\n        for x in range(len(p),len(s)):\n            d1[s[x]]+=1\n            d1[s[x-len(p)]]-=1\n            if d1==d2:\n                l1.append(x-len(p)+1)\n        return l1",
        "solution_js": "var findAnagrams = function(s, p) {\n\n    function compareMaps(map1, map2) {\n    var testVal;\n    if (map1.size !== map2.size) {\n        return false;\n    }\n    for (var [key, val] of map1) {\n        testVal = map2.get(key);\n        // in cases of an undefined value, make sure the key\n        // actually exists on the object so there are no false positives\n        if (testVal !== val || (testVal === undefined && !map2.has(key))) {\n            return false;\n        }\n    }\n    return true;\n    }\n\n    let p_map=new Map()\n    let s_map=new Map()\n    let res=[]\n    let pn=p.length\n    let sn=s.length\n    for(let i in p){\n        p_map.set(p[i],p_map.get(p[i])?p_map.get(p[i])+1:1)\n        s_map.set(s[i],s_map.get(s[i])?s_map.get(s[i])+1:1)\n    }\n    let l=0\n    if(compareMaps(s_map,p_map)) res.push(l)\n    for(let r=pn;r<sn;r++){\n        s_map.set(s[r],s_map.get(s[r])?s_map.get(s[r])+1:1)\n        s_map.set(s[l],s_map.get(s[l])-1)\n        if(s_map.get(s[l])===0){\n            s_map.delete(s[l])\n        }\n        if(compareMaps(s_map,p_map)) res.push(l+1)\n        l++\n    }\n    return(res)\n\n};",
        "solution_java": "class Solution { \n    \n    public List<Integer> findAnagrams(String s, String p) {\n        int fullMatchCount = p.length();\n        Map<Character, Integer> anagramMap = new HashMap<>();\n        \n        for (Character c : p.toCharArray())\n            anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1);\n        \n        List<Integer> result = new ArrayList<>();\n        int left = 0, right = 0, currentMatchCount = 0;\n        Map<Character, Integer> currentAnagramMap = new HashMap<>();\n        while (right < s.length()) {\n            char c = s.charAt(right);\n            if (anagramMap.get(c) == null) {\n                currentAnagramMap = new HashMap<>();\n                right++;\n                left = right;\n                currentMatchCount = 0;\n                continue;\n            }\n            currentAnagramMap.put(c, currentAnagramMap.getOrDefault(c, 0) + 1);\n            currentMatchCount++;\n            \n            if (currentAnagramMap.get(c) > anagramMap.get(c)) {\n                char leftC = s.charAt(left);\n                while (leftC != c) {\n                    currentAnagramMap.put(leftC, currentAnagramMap.get(leftC) - 1);\n                    left++;\n                    leftC = s.charAt(left);\n                    currentMatchCount--;\n                }\n                left++;\n                currentAnagramMap.put(c, currentAnagramMap.get(c) - 1);\n                currentMatchCount--;\n            }\n            \n            if (currentMatchCount == fullMatchCount)\n                result.add(left);\n            \n            right++;\n        }\n        return result;\n    }\n}",
        "solution_c": "//easy to understand\nclass Solution {\npublic:\n    bool allZeros(vector<int> &count) {\n        for (int i = 0; i < 26; i++) {\n            if (count[i] != 0) \n                return false;\n        }\n        return true;\n    }\n    vector<int> findAnagrams(string s, string p) {\n        string s1 = p, s2 = s;\n        int n = s1.length(); \n        int m = s2.length();\n        if (n > m) \n            return {};\n\n        vector<int> ans;\n        vector<int> count(26, 0);\n\n        for (int i = 0; i < n; i++) {\n            count[s1[i] - 'a']++;\n            count[s2[i] - 'a']--;\n        }\n        //it will check for s1 = abcd, s2 = cdab\n        if (allZeros(count)) {\n            ans.push_back(0);\n        }\n\n        for (int i = n; i < m; i++) {\n            count[s2[i] - 'a']--;\n            count[s2[i - n] - 'a']++;\n            if (allZeros(count)) \n                ans.push_back(i-n+1);\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Search a 2D Matrix",
        "algo_input": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:\n\n\n\tIntegers in each row are sorted from left to right.\n\tThe first integer of each row is greater than the last integer of the previous row.\n\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput: true\n\n\nExample 2:\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 100\n\t-104 &lt;= matrix[i][j], target &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n        left=0\n        right=len(matrix)-1\n        while left <= right:\n            mid=(left+right)//2\n            if matrix[mid][0] < target:\n                left = mid+1\n            elif matrix[mid][0] >target:\n                right= mid-1\n            else:\n                return True\n        left1=0\n        right1=len(matrix[right])-1\n        while left1 <= right1:\n            mid=(left1+right1)//2\n            if matrix[right][mid] < target:\n                left1 = mid+1\n            elif matrix[right][mid] >target:\n                right1= mid-1\n            else:\n                return True\n        return False",
        "solution_js": "var searchMatrix = function(matrix, target) {\n    let matCopy = [...matrix];\n    let leftIndex = 0;\n    let rightIndex = matrix.length - 1;\n\n    let mid = Math.ceil((matrix.length - 1) / 2);\n\n    let eachMatrixLength = matrix[0].length;\n  \n    if (matrix[mid].includes(target) === true) {\n        return true;\n    } else if (matrix.length == 1) {\n        return false;\n    }\n\n    if (matrix[mid][eachMatrixLength - 1] > target) {\n        rightIndex = mid - 1;\n        matCopy.splice(-mid);\n    } else {\n        leftIndex = mid + 1;\n        matCopy.splice(0, mid);\n    }\n\n    return searchMatrix(matCopy, target);\n   \n};",
        "solution_java": "class Solution {\n    public boolean searchMatrix(int[][] matrix, int target) {\n        if (target < matrix[0][0]) {\n            return false;\n        }\n        for (int i = 0; i < matrix.length; i++) {\n            if (matrix[i][0] > target | i == matrix.length - 1) {\n                if (matrix[i][0] > target) {\n                    i--;\n                }\n                for (int j = 0; j < matrix[i].length; j++) {\n                    if (matrix[i][j] == target) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        for(int i = 0; i < matrix.size(); i ++) {\n            if(matrix[i][0] > target) return false;\n            for(int j = 0; j < matrix[i].size(); j ++) {\n                if(matrix[i][j] == target) return true;\n                else if(matrix[i][j] > target) break;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Throne Inheritance",
        "algo_input": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.\n\nThe kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.\n\nSuccessor(x, curOrder):\n    if x has no children or all of x's children are in curOrder:\n        if x is the king return null\n        else return Successor(x's parent, curOrder)\n    else return x's oldest child who's not in curOrder\n\n\nFor example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.\n\n\n\tIn the beginning, curOrder will be [\"king\"].\n\tCalling Successor(king, curOrder) will return Alice, so we append to curOrder to get [\"king\", \"Alice\"].\n\tCalling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\"].\n\tCalling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n\tCalling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n\n\nUsing the above function, we can always obtain a unique order of inheritance.\n\nImplement the ThroneInheritance class:\n\n\n\tThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.\n\tvoid birth(string parentName, string childName) Indicates that parentName gave birth to childName.\n\tvoid death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.\n\tstring[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]\nOutput\n[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]\n\nExplanation\nThroneInheritance t= new ThroneInheritance(\"king\"); // order: king\nt.birth(\"king\", \"andy\"); // order: king &gt; andy\nt.birth(\"king\", \"bob\"); // order: king &gt; andy &gt; bob\nt.birth(\"king\", \"catherine\"); // order: king &gt; andy &gt; bob &gt; catherine\nt.birth(\"andy\", \"matthew\"); // order: king &gt; andy &gt; matthew &gt; bob &gt; catherine\nt.birth(\"bob\", \"alex\"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; catherine\nt.birth(\"bob\", \"asha\"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; asha &gt; catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; asha &gt; catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= kingName.length, parentName.length, childName.length, name.length &lt;= 15\n\tkingName, parentName, childName, and name consist of lowercase English letters only.\n\tAll arguments childName and kingName are distinct.\n\tAll name arguments of death will be passed to either the constructor or as childName to birth first.\n\tFor each call to&nbsp;birth(parentName, childName), it is guaranteed that&nbsp;parentName is alive.\n\tAt most 105 calls will be made to birth and death.\n\tAt most 10 calls will be made to getInheritanceOrder.\n\n",
        "solution_py": "class ThroneInheritance:\n\n    def __init__(self, kingName: str):\n        # Taking kingName as root\n        self.root = kingName\n\n        # notDead will hold all the people who are alive and their level number\n        self.alive = {}\n        self.alive[kingName] = 0\n\n        # hold edges existing in our graph\n        self.edges = {self.root:[]}\n\n    def birth(self, parentName: str, childName: str) -> None:\n        # birth --> new child so update alive\n        self.alive[childName] = self.alive[parentName]+1\n\n        # add parent to child edges in the edges dictionary\n        if parentName in self.edges:\n            self.edges[parentName].append(childName)\n            if childName not in self.edges:\n                self.edges[childName] = []\n        else:\n            if childName not in self.edges:\n                self.edges[childName] = []\n            self.edges[parentName] = [childName]\n\n    def death(self, name: str) -> None:\n        # removing the dead people from alive map\n        del self.alive[name]\n\n    def getInheritanceOrder(self) -> List[str]:\n\n        hierarchy = []\n        def dfs(cur,parent=-1):\n            nonlocal hierarchy\n\n            # current person available in alive then only add in hierarchy\n            if cur in self.alive:\n                hierarchy.append(cur)\n\n            # traverse all the children of current node\n            for i in self.edges[cur]:\n                if i!=parent:\n                    dfs(i,cur)\n        dfs(self.root)\n        return hierarchy",
        "solution_js": "var bloodList = function(name, parent = null) {\n    return {\n        name,\n        children: []\n    };\n}\n\nvar ThroneInheritance = function(kingName) {\n    this.nameMap = new Map();\n    this.nameMap.set(kingName, bloodList(kingName));\n    this.king = kingName;\n    this.deadList = new Set();\n};\n\n/**\n * @param {string} parentName\n * @param {string} childName\n * @return {void}\n */\nThroneInheritance.prototype.birth = function(parentName, childName) {\n    const parent = this.nameMap.get(parentName);\n    const childId = bloodList(childName, parent);\n    this.nameMap.set(childName, childId);\n    parent.children.push(childId);\n};\n\n/**\n * @param {string} name\n * @return {void}\n */\nThroneInheritance.prototype.death = function(name) {\n    this.deadList.add(name);\n};\n\n/**\n * @return {string[]}\n */\nfunction updateList(list, nameId, deadList) {\n    if (!deadList.has(nameId.name))\n        list.push(nameId.name);\n\n    for (let child of nameId.children) {\n        updateList(list, child, deadList);\n    }\n}\n\nThroneInheritance.prototype.getInheritanceOrder = function() {\n    let list = [];\n    updateList(list, this.nameMap.get(this.king), this.deadList);\n    return list;\n};",
        "solution_java": "class Tree{\n    List<Tree>child;\n    String name;\n    public Tree(String name,List<Tree>child){\n        this.name=name;\n        this.child=child;\n    }\n}\nclass ThroneInheritance {\n    private Set<String>death;\n    private Tree tree;\n    private Map<String,Tree>addtoTree;\n    public ThroneInheritance(String kingName) {\n      death=new HashSet<>();  \n      tree=new Tree(kingName,new ArrayList());\n      addtoTree=new HashMap();\n      addtoTree.put(kingName,tree);   \n    }\n    \n    public void birth(String parentName, String childName) {\n           Tree tmp =addtoTree.get(parentName);\n           Tree childtree=new Tree(childName,new ArrayList());\n           tmp.child.add(childtree);\n            addtoTree.put( childName,childtree); \n    }\n    \n    public void death(String name) {\n        death.add(name);\n    }\n    \n    public List<String> getInheritanceOrder() {\n        List<String>ans=new ArrayList<>();\n        preOreder(tree,ans,death);\n        return ans;\n    }\n    \n    void preOreder(Tree n,List<String>ans,Set<String>death){\n        if(n==null)return;\n        if(!death.contains(n.name))ans.add(n.name);\n         for(Tree name:n.child){\n            preOreder(name,ans,death);\n        }\n    }\n}",
        "solution_c": "class ThroneInheritance {\npublic:\n    ThroneInheritance(string kingName) {\n        curr_king = kingName;\n    }\n    \n    void birth(string parentName, string childName) {\n        children[parentName].push_back(childName);\n    }\n    \n    void death(string name) {\n        dead.insert(name);\n    }\n    \n    void rec(string parent) {\n        if (!dead.count(parent)) inheritance.push_back(parent);\n        for (auto child : children[parent])\n            rec(child);\n    }\n    \n    vector<string> getInheritanceOrder() {\n        inheritance = {};\n        rec(curr_king);\n        return inheritance;\n    }\n    \nprivate:\n    unordered_map<string, vector<string>> children;\n    vector<string> inheritance;\n    unordered_set<string> dead;\n    string curr_king;\n};"
    },
    {
        "title": "Previous Permutation With One Swap",
        "algo_input": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,2,1]\nOutput: [3,1,2]\nExplanation: Swapping 2 and 1.\n\n\nExample 2:\n\nInput: arr = [1,1,5]\nOutput: [1,1,5]\nExplanation: This is already the smallest permutation.\n\n\nExample 3:\n\nInput: arr = [1,9,4,6,7]\nOutput: [1,7,4,6,9]\nExplanation: Swapping 9 and 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t1 &lt;= arr[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n\n    def find_max(self, i, a, n):\n        maxs = i+1\n        for j in range(n-1, i, -1):\n            # if only j is greater than max and smaller than first descending element\n            if(a[maxs] <= a[j] and a[j] < a[i]):\n                maxs = j\n        # Swap\n        a[i], a[maxs] = a[maxs], a[i]\n        return a\n\n    def prevPermOpt1(self, arr):\n        n = len(arr)\n        for i in range(n-1, 0, -1):\n            if(arr[i] < arr[i-1]):\n                # sending the first descending element from right to max_function\n                arr = self.find_max(i-1, arr, n)\n                break\n        return arr",
        "solution_js": "var prevPermOpt1 = function(arr) {\n    const n = arr.length;\n    let i = n - 1;\n    \n    while (i > 0 && arr[i] >= arr[i - 1]) i--;\n    \n    if (i === 0) return arr;\n\n    const swapIndex = i - 1;\n    const swapDigit = arr[swapIndex];\n    \n    let maxIndex = i;\n    i = n - 1;\n    \n    while (swapIndex < i) {\n        const currDigit = arr[i];\n        \n        if (currDigit < swapDigit && currDigit >= arr[maxIndex]) maxIndex = i;\n        i--;\n    }\n\n    [arr[maxIndex], arr[swapIndex]] = [arr[swapIndex], arr[maxIndex]];\n    \n    return arr; \n}; ",
        "solution_java": "class Solution {\n    public int[] prevPermOpt1(int[] arr) {\n        int n=arr.length;\n        int small=arr[n-1];\n        int prev=arr[n-1];\n        for(int i=n-2;i>=0;i--){\n            if(arr[i]<=prev){\n                prev=arr[i];\n            }\n            else{\n                int indte=i;\n                int te=0;\n                    for(int j=i+1;j<n;j++){\n                        if(arr[j]<arr[i]&&arr[j]>te){\n                            te=arr[j];\n                            indte=j;\n                        }\n                }\n                int tem=arr[indte];\n                arr[indte]=arr[i];\n                arr[i]=tem;\n                return arr;\n            }\n        }\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> prevPermOpt1(vector<int>& arr) {\n        int i, p, mn = -1;\n        for(i=arr.size() - 2; i>=0; i--) {\n            if(arr[i] > arr[i + 1]) break;\n        }\n        if(i == -1) return arr;\n\n        for(int j=i + 1; j<arr.size(); j++) {\n            if(arr[j] > mn && arr[j] < arr[i]) mn = arr[j], p = j;\n    \n        }\n        swap(arr[i], arr[p]);\n        return arr;\n    }\n};"
    },
    {
        "title": "Word Ladder II",
        "algo_input": "A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -&gt; s1 -&gt; s2 -&gt; ... -&gt; sk such that:\n\n\n\tEvery adjacent pair of words differs by a single letter.\n\tEvery si for 1 &lt;= i &lt;= k is in wordList. Note that beginWord does not need to be in wordList.\n\tsk == endWord\n\n\nGiven two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].\n\n&nbsp;\nExample 1:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\nExplanation:&nbsp;There are 2 shortest transformation sequences:\n\"hit\" -&gt; \"hot\" -&gt; \"dot\" -&gt; \"dog\" -&gt; \"cog\"\n\"hit\" -&gt; \"hot\" -&gt; \"lot\" -&gt; \"log\" -&gt; \"cog\"\n\n\nExample 2:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput: []\nExplanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= beginWord.length &lt;= 5\n\tendWord.length == beginWord.length\n\t1 &lt;= wordList.length &lt;= 500\n\twordList[i].length == beginWord.length\n\tbeginWord, endWord, and wordList[i] consist of lowercase English letters.\n\tbeginWord != endWord\n\tAll the words in wordList are unique.\n\n",
        "solution_py": "class Solution:\n\n    WILDCARD = \".\"\n\n    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n        \"\"\"\n        Given a wordlist, we perform BFS traversal to generate a word tree where\n        every node points to its parent node.\n\n        Then we perform a DFS traversal on this tree starting at the endWord.\n        \"\"\"\n        if endWord not in wordList:\n            # end word is unreachable\n            return []\n\n        # first generate a word tree from the wordlist\n        word_tree = self.getWordTree(beginWord, endWord, wordList)\n\n        # then generate a word ladder from the word tree\n        return self.getLadders(beginWord, endWord, word_tree)\n\n    def getWordTree(self,\n                    beginWord: str,\n                    endWord: str,\n                    wordList: List[str]) -> Dict[str, List[str]]:\n        \"\"\"\n        BFS traversal from begin word until end word is encountered.\n\n        This functions constructs a tree in reverse, starting at the endWord.\n        \"\"\"\n        # Build an adjacency list using patterns as keys\n        # For example: \".it\" -> (\"hit\"), \"h.t\" -> (\"hit\"), \"hi.\" -> (\"hit\")\n        adjacency_list = defaultdict(list)\n        for word in wordList:\n            for i in range(len(word)):\n                pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n                adjacency_list[pattern].append(word)\n\n        # Holds the tree of words in reverse order\n        # The key is an encountered word.\n        # The value is a list of preceding words.\n        # For example, we got to beginWord from no other nodes.\n        # {a: [b,c]} means we got to \"a\" from \"b\" and \"c\"\n        visited_tree = {beginWord: []}\n\n        # start off the traversal without finding the word\n        found = False\n\n        q = deque([beginWord])\n        while q and not found:\n            n = len(q)\n\n            # keep track of words visited at this level of BFS\n            visited_this_level = {}\n\n            for i in range(n):\n                word = q.popleft()\n\n                for i in range(len(word)):\n                    # for each pattern of the current word\n                    pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n                    for next_word in adjacency_list[pattern]:\n                        if next_word == endWord:\n                            # we don't return immediately because other\n                            # sequences might reach the endWord in the same\n                            # BFS level\n                            found = True\n                        if next_word not in visited_tree:\n                            if next_word not in visited_this_level:\n                                visited_this_level[next_word] = [word]\n                                # queue up next word iff we haven't visited it yet\n                                # or already are planning to visit it\n                                q.append(next_word)\n                            else:\n                                visited_this_level[next_word].append(word)\n\n            # add all seen words at this level to the global visited tree\n            visited_tree.update(visited_this_level)\n\n        return visited_tree\n\n    def getLadders(self,\n                   beginWord: str,\n                   endWord: str,\n                   wordTree: Dict[str, List[str]]) -> List[List[str]]:\n        \"\"\"\n        DFS traversal from endWord to beginWord in a given tree.\n        \"\"\"\n        def dfs(node: str) -> List[List[str]]:\n            if node == beginWord:\n                return [[beginWord]]\n            if node not in wordTree:\n                return []\n\n            res = []\n            parents = wordTree[node]\n            for parent in parents:\n                res += dfs(parent)\n            for r in res:\n                r.append(node)\n            return res\n\n        return dfs(endWord)",
        "solution_js": "const isMatch = (currWord, nextWord) => {\n    let mismatch = 0;\n    for(let i = 0; i < nextWord.length; i += 1) {\n        if(nextWord[i] !== currWord[i]) {\n            mismatch += 1;\n        }\n    }\n\n    return mismatch === 1;\n}\n\nconst getNextWords = (lastRung, dictionary) => {\n    const nextWords = [];\n    for(const word of dictionary) {\n        if(isMatch(word, lastRung)) {\n            nextWords.push(word);\n        }\n    }\n\n    return nextWords;\n}\n\nconst updateLadders = (ladders, dictionary) => {\n    const updatedLadders = [];\n    const nextRung = new Set();\n\n    for(const ladder of ladders) {\n        const nextWords = getNextWords(ladder[ladder.length - 1], dictionary);\n        for(const nextWord of nextWords) {\n            updatedLadders.push([...ladder, nextWord]);\n            nextRung.add(nextWord);\n        }\n    }\n\n    return [updatedLadders, nextRung];\n}\n\nconst updateDictionary = (dictionary, nextRung) => {\n    return dictionary.filter((word) => !nextRung.has(word));\n}\n\n// BFS traversal from endWord to beginWord\n// This limits the paths that we'll need to consider during our traversal from beingWord to endWord\nconst getDictionary = (wordList, endWord, beginWord) => {\n    const dictionary = new Set();\n\n    let currRung = [endWord];\n    while(currRung.length > 0) {\n        const nextRung = new Set();\n        if(!wordList.includes(beginWord)) break;\n\n        while(currRung.length > 0) {\n            const currWord = currRung.pop();\n            dictionary.add(currWord);\n\n            for(const nextWord of wordList) {\n                if(isMatch(currWord, nextWord)) {\n                    nextRung.add(nextWord);\n                }\n            }\n        }\n\n        currRung = [...nextRung];\n        wordList = wordList.filter((word) => !nextRung.has(word));\n    }\n\n    return [...dictionary];\n}\n\nvar findLadders = function(beginWord, endWord, wordList) {\n    if(!wordList.includes(endWord)) return [];\n    if(!wordList.includes(beginWord)) wordList.push(beginWord);\n\n    const result = [];\n    const saveResult = (ladders) => {\n        for(const ladder of ladders) {\n            if(ladder[ladder.length - 1] === endWord) {\n                result.push(ladder);\n            }\n        }\n    }\n\n    let ladders = [[beginWord]];\n    let dictionary = getDictionary(wordList, endWord, beginWord);\n    while(ladders.length > 0) {\n        if(!dictionary.includes(endWord)) {\n            saveResult(ladders);\n            break;\n        }\n\n        const [updatedLadders, nextRung] = updateLadders(ladders, dictionary);\n        ladders = updatedLadders;\n        dictionary = updateDictionary(dictionary, nextRung);\n    }\n\n    return result;\n};",
        "solution_java": "class Solution {\n    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n        Set<String> dict = new HashSet(wordList);\n        if( !dict.contains(endWord) )\n            return new ArrayList();\n        \n        // adjacent words for each word\n        Map<String,List<String>> adjacency = new HashMap();\n        Queue<String> queue = new LinkedList();\n        // does path exist?\n        boolean found = false;\n        \n        // BFS for shortest path, keep removing visited words\n        queue.offer(beginWord);\n        dict.remove(beginWord);\n                \n        while( !found && !queue.isEmpty() ) {\n            int size = queue.size();\n            // adjacent words in current level\n            HashSet<String> explored = new HashSet();\n\n            while( size-- > 0 ) {\n                String word = queue.poll();\n                \n                if( adjacency.containsKey(word) )\n                    continue;\n                \n                // remove current word from dict, and search for adjacent words\n                dict.remove(word);\n                List<String> adjacents = getAdjacents(word, dict);\n                adjacency.put(word, adjacents);\n\n                for(String adj : adjacents) {\n                    if( !found && adj.equals(endWord) ) \n                        found = true;\n                    \n                    explored.add(adj);\n                    queue.offer(adj);\n                }\n            }\n            // remove words explored in current level from dict\n            for(String word : explored)\n                dict.remove(word);\n        }\n\n        // if a path exist, dfs to find all the paths\n        if( found ) \n            return dfs(beginWord, endWord, adjacency, new HashMap());\n        else\n            return new ArrayList();\n    }\n    \n    private List<String> getAdjacents(String word, Set<String> dict) {\n        List<String> adjs = new ArrayList();\n        char[] wordChars = word.toCharArray();\n        \n        for(int i=0; i<wordChars.length; i++) \n            for(char c='a'; c<='z'; c++) {\n                char temp = wordChars[i];\n                wordChars[i] = c;\n                \n                String newAdj = new String(wordChars);\n                if( dict.contains(newAdj) )\n                    adjs.add(newAdj);\n                \n                wordChars[i] = temp;\n            }\n        return adjs;\n    }\n    \n    private List<List<String>> dfs(String src, String dest, \n                                   Map<String,List<String>> adjacency, \n                                   Map<String,List<List<String>>> memo) {\n        if( memo.containsKey(src) )\n            return memo.get(src);\n        \n        List<List<String>> paths = new ArrayList();\n        \n\t\t// reached dest? return list with dest word\n        if( src.equals( dest ) ) {\n            paths.add( new ArrayList(){{ add(dest); }} );\n            return paths;\n        }\n\n\t\t// no adjacent for curr word? return empty list\n        List<String> adjacents = adjacency.get(src);\n        if( adjacents == null || adjacents.isEmpty() )\n            return paths;\n\n        for(String adj : adjacents) {\n            List<List<String>> adjPaths = dfs(adj, dest, adjacency, memo);\n            \n            for(List<String> path : adjPaths) {\n                if( path.isEmpty() ) continue;\n                \n                List<String> newPath = new ArrayList(){{ add(src); }};\n                newPath.addAll(path);\n                \n                paths.add(newPath);\n            }\n        } \n        memo.put(src, paths);\n        return paths;\n    }\n}",
        "solution_c": "// BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime. \n// The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time. \n// Then, use DFS (backtracking) to generate the transformation sequences according to the mapping. \n// The reverse DFS allows us to only make the shortest paths, never having to clear a whole sequence when we encounter better result in BFS\n// No string operations are done, by dealing with indices instead.\n\n\n\nclass Solution {\npublic:\nbool able(string s,string t){\n    int c=0;\n    for(int i=0;i<s.length();i++)\n        c+=(s[i]!=t[i]);\n    return c==1;\n}\nvoid bfs(vector<vector<int>> &g,vector<int> parent[],int n,int start,int end){\n    vector <int> dist(n,1005);\n    queue <int> q;\n    q.push(start);\n    parent[start]={-1};\n    dist[start]=0;\n    while(!q.empty()){\n        int x=q.front();\n        q.pop();\n        for(int u:g[x]){\n            if(dist[u]>dist[x]+1){\n                dist[u]=dist[x]+1;\n                q.push(u);\n                parent[u].clear();\n                parent[u].push_back(x);\n            }\n            else if(dist[u]==dist[x]+1)\n                parent[u].push_back(x);\n        }\n    }\n}\nvoid shortestPaths(vector<vector<int>> &Paths, vector<int> &path, vector<int> parent[],int node){\n    if(node==-1){\n        // as parent of start was -1, we've completed the backtrack\n        Paths.push_back(path);\n        return ;\n    }\n    for(auto u:parent[node]){\n        path.push_back(u);\n        shortestPaths(Paths,path,parent,u);\n        path.pop_back();\n    }\n}\nvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n    // start and end are indices of beginWord and endWord\n    int n=wordList.size(),start=-1,end=-1;\n    vector<vector<string>> ANS;\n    for(int i=0;i<n;i++){\n        if(wordList[i]==beginWord)\n            start=i;\n        if(wordList[i]==endWord)\n            end=i;\n    }\n    \n    // if endWord doesn't exist, return empty list\n    if(end==-1)\n        return ANS;\n    \n    // if beginWord doesn't exist, add it in start of WordList\n    if(start==-1){\n        wordList.emplace(wordList.begin(),beginWord);\n        start=0;\n        end++;\n        n++;\n    }\n    // for each word, we're making adjency list of neighbour words (words that can be made with one letter change)\n    // Paths will store all the shortest paths (formed later by backtracking)\n    vector<vector<int>> g(n,vector<int>()),Paths;\n    \n    // storing possible parents for each word (to backtrack later), path is the current sequence (while backtracking)\n    vector<int> parent[n],path;\n    \n    // creating adjency list for each pair of words in the wordList (including beginword)\n    for(int i=0;i<n-1;i++)\n        for(int j=i+1;j<n;j++)\n            if(able(wordList[i],wordList[j])){\n                g[i].push_back(j);\n                g[j].push_back(i);\n            }\n    \n    bfs(g,parent,n,start,end); \n    \n    // backtracking to make shortestpaths\n    shortestPaths(Paths,path,parent,end);\n    for(auto u:Paths){\n        vector <string> now;\n        for(int i=0;i<u.size()-1;i++)\n            now.push_back(wordList[u[i]]);\n        reverse(now.begin(),now.end());\n        now.push_back(wordList[end]);\n        ANS.push_back(now);\n    }\n    return ANS;\n}\n}; "
    },
    {
        "title": "Palindrome Linked List",
        "algo_input": "Given the head of a singly linked list, return true if it is a palindrome.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,2,1]\nOutput: true\n\n\nExample 2:\n\nInput: head = [1,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 105].\n\t0 &lt;= Node.val &lt;= 9\n\n\n&nbsp;\nFollow up: Could you do it in O(n) time and O(1) space?",
        "solution_py": "class Solution:\n    def isPalindrome(self, head: \"Optional[ListNode]\") -> bool:\n        if head.next == None: return True #if only 1 element, it's always a palindrome\n        forward = head\n        first_half = []\n        fast = head\n\n        while (fast != None and fast.next != None):\n            first_half.append(forward.val)\n            forward = forward.next\n            fast = fast.next.next\n\n        # forward should now be through half the list\n        if fast != None : forward = forward.next  # if length isn't even, skip the middle number\n        \n        reverse = len(first_half)-1\n        while forward != None:\n            if forward.val != first_half[reverse]: return False\n            forward = forward.next\n            reverse -= 1\n\n        return True",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nvar isPalindrome = function(head) {\n    let slow = head;\n    let fast = head;\n    // Moving slow one step at a time while fast, two steps\n    while (fast && fast.next) {\n        slow = slow.next;\n        fast = fast.next.next;\n    }\n    // This way, slow will end up right after the middle node\n    // Reverse the list from that node\n    slow = reverse(slow);\n    fast = head;\n    // Now check for equality first half and second half of the list\n    while (slow) {\n        if (slow.val !== fast.val) {\n            return false;\n        }\n        slow = slow.next;\n        fast = fast.next;\n    }\n    return true;\n};\n\n// Function to reverse a LinkedList\nfunction reverse(head) {\n    let prev = null;\n    while (head) {\n        let nextNode = head.next;\n        head.next = prev;\n        prev = head;\n        head = nextNode;\n    }\n    return prev;\n}",
        "solution_java": "class Solution {\n    public boolean isPalindrome(ListNode head) {\n        \n        ListNode mid = getMiddle(head);\n        ListNode headSecond = reverse(mid);\n        ListNode reverseHead = headSecond;\n        \n        while(head != null && headSecond != null){\n            if(head.val != headSecond.val){\n                break;\n            }\n            head = head.next;\n            headSecond = headSecond.next;\n        }\n        reverse(reverseHead);\n        \n        return head==null || headSecond == null;\n    }\n    \n    public ListNode reverse(ListNode head){\n        if(head==null) return head;\n        ListNode prev = null;\n        ListNode present = head;\n        ListNode next = head.next;\n        while(present != null){\n            present.next = prev;\n            prev = present;\n            present = next;\n            if(next!=null)\n            next = next.next;\n        }\n        return prev;\n    }\n    \n    public ListNode getMiddle(ListNode head){\n        ListNode temp = head;\n        int count = 0;\n        while(temp!=null){\n            temp = temp.next;\n            count++;\n        }\n        int mid = count/2;\n        temp = head;\n        for(int i=0; i<mid;i++){\n            temp = temp.next;\n        }\n        return temp;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* reverse(ListNode* head)\n    {\n        ListNode* prev=nullptr;\n        while(head)\n        {\n            ListNode* current=head->next;\n            head->next=prev;\n            prev=head;\n            head=current;\n        }\n        return prev;\n    }\n    bool isPalindrome(ListNode* head) {\n         if(!head || !head->next) return true;\n        ListNode* tort=head;\n        ListNode* hare=head;\n        while(hare->next && hare->next->next)\n        {\n            tort=tort->next;\n            hare=hare->next->next;\n        }\n        tort->next=reverse(tort->next);\n         tort=tort->next;\n        ListNode* dummy=head;\n        while(tort)\n        {\n            if(tort->val!=dummy->val)\n                return false;\n            tort=tort->next;\n            dummy=dummy->next;\n        }\n        return true;\n    }\n};\n\nTime Complexity: O(n/2)+O(n/2)+O(n/2)\nSpace Complexity: O(1)"
    },
    {
        "title": "Available Captures for Rook",
        "algo_input": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.\n\nWhen the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.\n\nReturn the number of available captures for the white rook.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: In this example, the rook is attacking all the pawns.\n\n\nExample 2:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 0\nExplanation: The bishops are blocking the rook from attacking any of the pawns.\n\n\nExample 3:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: The rook is attacking the pawns at positions b5, d6, and f5.\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == 8\n\tboard[i].length == 8\n\tboard[i][j] is either 'R', '.', 'B', or 'p'\n\tThere is exactly one cell with board[i][j] == 'R'\n\n",
        "solution_py": "class Solution:\n    def numRookCaptures(self, board: List[List[str]]) -> int:\n\t\t# Checking for possible case to the right of Rook\n        def right_position(n,i):\n            List = i[0:n][::-1] # taking list to the right of rook\n            pIndex,bIndex = -1,-1\n            if 'p' in List: # Checking if  'p' in list   \n                pIndex = List.index('p')\n            if 'B' in List: # Checking if 'B' in list\n                bIndex = List.index('B')\n            print(bIndex,pIndex,List)\n            if bIndex == -1 and pIndex >-1: # if list does not have 'B' and have 'p'\n                return True\n            if pIndex == -1: # if list does not have 'p'\n                return False\n            return bIndex>pIndex \n        def left_position(n,i):\n            List = i[n+1:]# taking list to the right of rook\n            pIndex,bIndex = -1,-1\n            if 'p' in List:\n                pIndex = List.index('p')\n            if 'B' in List:\n                bIndex = List.index('B')\n            print(bIndex,pIndex,List)\n            if bIndex == -1 and pIndex >-1:\n                return True\n            if pIndex == -1:\n                return False\n            return bIndex>pIndex\n        Count = 0\n\t\t# Checking for possibilites in row\n        for i in board:\n            if 'R' in i:\n                print(i)\n                n = i.index('R')\n                if left_position(n,i):\n                    Count += 1\n                if right_position(n,i):\n                    Count += 1\n        Col = []\n\t\t# checking for possibilites in col\n        for i in range(0,len(board)):\n            Col.append(board[i][n]) # taking the elements from the same col of Rook\n        n = Col.index('R')\n        if left_position(n,Col):\n            Count += 1\n        if right_position(n,Col):\n            Count += 1\n        return Count",
        "solution_js": "var numRookCaptures = function(board) {\n    const r=board.length;\n    const c=board[0].length;\n\n    let res=0\n    const dir=[[0,1],[0,-1],[1,0],[-1,0]]; // all the 4 possible directions\n    let rook=[];\n\n    // finding the rook's position\n    for(let i=0;i<r;i++){\n        for(let j=0;j<c;j++){\n            if(board[i][j]==='R'){\n                rook=[i,j]\n                break;\n            }\n        }\n    }\n\n    // traversing all the 4 directions\n    for(let [x,y] of dir){\n        res+=helper(x,y,rook[0],rook[1])\n    }\n\n    return res;\n\n    function helper(x,y,i,j){\n        let newX=x+i\n        let newY=y+j\n        let attack=0\n        while(newX<r&&newY<c&&newX>=0&&newY>=0){\n            if(board[newX][newY]==='p'){\n                attack++\n                break; // break because Rook can't attack more than one pawn in same direction\n            }else if(board[newX][newY]==='B'){\n                break\n            }\n            // keep moving towards the same direction\n            newX+=x\n            newY+=y\n        }\n        return attack\n    }\n};",
        "solution_java": "class Solution {\n    public int numRookCaptures(char[][] board) {\n        int ans = 0;\n\n        int row = 0;\n        int col = 0;\n        for (int i = 0; i < 8; i++) {\n            for (int j = 0; j < 8; j++) {\n                if (board[i][j] == 'R') {\n                    row = i;\n                    col = j;\n                    break;\n                }\n            }\n        }\n\n        int j = col;\n        while (j >= 0) {\n            if (board[row][j] == 'B') {\n                break;\n            } else if (board[row][j] == 'p') {\n                ans++;\n                break;\n            }\n\n            j--;\n        }\n\n        j = col;\n        while (j <= board[0].length - 1) {\n            if (board[row][j] == 'B') {\n                break;\n            } else if (board[row][j] == 'p') {\n                ans++;\n                break;\n            }\n\n            j++;\n        }\n\n        int i = row;\n        while (i <= board.length - 1) {\n            if (board[i][col] == 'B') {\n                break;\n            } else if (board[i][col] == 'p') {\n                ans++;\n                break;\n            }\n\n            i++;\n        }\n\n        i = row;\n        while (i >= 0) {\n            if (board[i][col] == 'B') {\n                break;\n            } else if (board[i][col] == 'p') {\n                ans++;\n                break;\n            }\n\n            i--;\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numRookCaptures(vector<vector<char>>& board) {\n        int res=0;\n        int p=-1,q=-1;\n        for(int i=0;i<board.size();i++)\n        {\n            for(int j=0;j<board[0].size();j++)\n            {\n                if(board[i][j]=='R') // storing position of R\n                {\n                    p=i;\n                    q=j;\n                    break;\n                }\n            }\n            if(p>=0)\n                break;\n        }\n        // traverse Up, Down, Left and Right from R\n        for(int i=p+1;i<board.size();i++)\n        {\n            if(board[i][q]!='.')\n            {\n                if(board[i][q]=='p')\n                    res++;\n                break;\n            }\n        }\n        for(int i=p-1;i>=0;i--)\n        {\n            if(board[i][q]!='.')\n            {\n                if(board[i][q]=='p')\n                    res++;\n                break;\n            }\n        }\n        \n        for(int j=q+1;j<board[0].size();j++)\n        {\n            if(board[p][j]!='.')\n            {\n                if(board[p][j]=='p')\n                    res++;\n                break;\n            }\n        }\n        for(int j=q-1;j>=0;j--)\n        {\n            if(board[p][j]!='.')\n            {\n                if(board[p][j]=='p')\n                    res++;\n                break;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Minimum Distance Between BST Nodes",
        "algo_input": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 100].\n\t0 &lt;= Node.val &lt;= 105\n\n\n&nbsp;\nNote: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/\n",
        "solution_py": "# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n        if root is None:\n            return 0\n        temp1=float(inf)\n        from collections import deque\n        a=deque([root])\n        b=[]\n        while a:\n            node=a.popleft()\n            b.append(node.val)\n            if node.left:\n                a.append(node.left)\n            if node.right:\n                a.append(node.right)\n        b.sort()\n        for i in range(0,len(b)-1):\n            if b[i+1]-b[i]",
        "solution_js": "/**\n * @param {TreeNode} root\n * @return {number}\n */\nvar minDiffInBST = function(root) {\n    let arr = [];\n    \n\tconst helper = (node) => {\n\t\tif (node) {\n\t\t\thelper(node.left);\n\t\t\tarr.push(node.val);\n\t\t\thelper(node.right);\n\t\t}\n\t}\n\thelper(root);\n    \n\tlet min = Infinity;\n\tfor (let i = 0; i < arr.length - 1; i++) {\n\t\tconst diff = Math.abs(arr[i] - arr[i + 1]);\n\t\tmin = Math.min(min, diff);\n\t}\n    \n\treturn min;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    \n    int mini=Integer.MAX_VALUE;\n\n    public void find(TreeNode root,ArrayList<Integer>arr){\n    \n    if(root==null){\n        return;\n    }\n    \n    \n    arr.add(root.val);\n    \n    find(root.left,arr);\n    \n    for(int i=arr.size()-2;i>=0;i--){\n    \n        mini=Math.min(mini,Math.abs(root.val-arr.get(i)));\n    }\n    \n    find(root.right,arr);\n    \n    arr.remove(arr.size()-1);\n    }\n\n    public int minDiffInBST(TreeNode root) {\n    ArrayList<Integer>arr=new ArrayList<>();\n    find(root,arr);\n    return mini;    \n    }\n}",
        "solution_c": "class Solution {\n    int minDiff=INT_MAX,prev=INT_MAX;\npublic:\n    void inorder(TreeNode* p){\n        if(p==NULL) return;\n        inorder(p->left);\n        minDiff=min(minDiff,abs(p->val-prev));\n        prev=p->val;\n        inorder(p->right);\n    }\n    int minDiffInBST(TreeNode* root) {\n        inorder(root);\n        return minDiff;\n    }\n};"
    },
    {
        "title": "Remove Max Number of Edges to Keep Graph Fully Traversable",
        "algo_input": "Alice and Bob have an undirected graph of n nodes and three types of edges:\n\n\n\tType 1: Can be traversed by Alice only.\n\tType 2: Can be traversed by Bob only.\n\tType 3: Can be traversed by both Alice and Bob.\n\n\nGiven an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\n\nReturn the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput: 2\nExplanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n\n\nExample 2:\n\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput: 0\nExplanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n\n\nExample 3:\n\n\n\nInput: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput: -1\nExplanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n\n&nbsp;\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= edges.length &lt;= min(105, 3 * n * (n - 1) / 2)\n\tedges[i].length == 3\n\t1 &lt;= typei &lt;= 3\n\t1 &lt;= ui &lt; vi &lt;= n\n\tAll tuples (typei, ui, vi) are distinct.\n\n",
        "solution_py": "class DSUF:\n    def __init__(self, n):\n        self.arr = [-1] * n\n    def find(self, node):\n        p = self.arr[node]\n        if p == -1:\n            return node\n        self.arr[node] = self.find(p)\n        return self.arr[node]\n    def union(self, a, b):\n        aP = self.find(a)\n        bP = self.find(b)\n        if aP == bP:\n            return 0\n        self.arr[aP] = bP\n        return 1\n    def countParents(self):\n        count = 0\n        for i in self.arr:\n            if i == -1:\n                count += 1\n        return count\n\nclass Solution:\n    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n        # Solution - DSU\n        # Time - O(ElogV)\n        # Space - O(V)\n        \n        aliceSet = DSUF(n)\n        bobSet = DSUF(n)\n        \n        bothEdges = []\n        bobEdges = []\n        aliceEdges= []\n        for i in range(len(edges)):\n            if edges[i][0] == 3:\n                bothEdges.append(edges[i])\n            elif edges[i][0] == 1:\n                aliceEdges.append(edges[i])\n            else:\n                bobEdges.append(edges[i])\n        \n        usedEdgeCount = 0\n        \n        # connect both edges\n        for edge in bothEdges:\n            aReq = aliceSet.union(edge[1]-1, edge[2]-1)\n            bReq = bobSet.union(edge[1]-1, edge[2]-1)\n            if aReq and bReq:\n                usedEdgeCount += 1\n        \n        # connect individual edges\n        for edge in aliceEdges:\n            usedEdgeCount += aliceSet.union(edge[1]-1, edge[2]-1)\n        \n        for edge in bobEdges:\n            usedEdgeCount += bobSet.union(edge[1]-1, edge[2]-1)\n        \n        if aliceSet.countParents() == 1 and bobSet.countParents() == 1:\n            return len(edges) - usedEdgeCount\n        \n        return -1",
        "solution_js": "// A common disjoint set class\nfunction DS(n) {\n    var root = [...new Array(n + 1).keys()];\n    var rank = new Array(n + 1).fill(0);\n    this.find = function(v) {\n        if (root[v] !== v) root[v] = this.find(root[v]);\n        return root[v];\n    }\n    this.union = function (i, j) {\n        var [a, b] = [this.find(i), this.find(j)];\n        if (a === b) return false;\n        if (rank[a] > rank[b]) root[b] = a;\n        else if (rank[a] < rank[b]) root[a] = b;\n        else  root[a] = b, rank[b]++;\n        return true;\n    }\n\t// check if the nodes 1-n is in the same set\n    this.canFullyTraverse = function() {\n        var key = this.find(1);\n        for (var i = 2; i <= n; i++) {\n            if (this.find(i) !== key) return false;\n        }\n        return true;\n    }\n}\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number}\n */\nvar maxNumEdgesToRemove = function(n, edges) {\n\t// two persons disjoint set\n    var ds1 = new DS(n);\n    var ds2 = new DS(n);\n\t// sort edges by type, to make sure we can handle type 3 first\n    edges.sort((a, b) => b[0] - a[0]);\n    var result = 0;\n    edges.forEach(([type, u, v]) => {\n\t\t// when edge type is 3, union u, v for both person's ds\n\t\t// if they are already in the same set, this edge can be remove, result++\n        if (type === 3) {\n            var [r1, r2] = [ds1.union(u, v), ds2.union(u, v)];\n            if (!r1 && !r2) {\n                result++;\n            }\n\t\t// for specific person\n        } else if (type === 1) {\n            if (!ds1.union(u, v)) {\n                result++;\n            }\n        } else {\n            if (!ds2.union(u, v)) {\n                result++;\n            }\n        }\n    });\n\t// if one person cannot fully traverse, return -1\n\t// otherwise, return result\n    if (ds1.canFullyTraverse() && ds2.canFullyTraverse()) {\n        return result;\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int maxNumEdgesToRemove(int n, int[][] edges) \n    {\n        Arrays.sort(edges, (a, b)->{\n            return b[0]-a[0];\n        });//giving the priority to third type of edge or the edge which Bob and Alice both can access\n        \n        //1-based indexing of nodes \n        int []parentAlice= new int[n+1];//Graph 1 for Alice connectedness\n        int []parentBob= new int[n+1];//Graph 2 for Bob connectedness\n        \n        for(int i= 0; i< n+1; i++){//every node is pointing to itself, at first no connection is considered all sets are independent(no dependency) \n            parentAlice[i]= i;\n            parentBob[i]= i;\n        }\n        \n        //number of merged unique node for Alice and Bob that are required to maintain the connectedness of Alice and Bob graph nodes//intialised with one because merging happens in pair \n        int mergeAlice= 1;\n        int mergeBob= 1;\n        \n        //number of cyclic or the non dependent node, that are not required for the connectedness of Alice and Bob nodes  \n        int removeEdge= 0;\n        \n        for(int []edge: edges)\n        {\n            int cat= edge[0];//category of edge 1)edge Alice can only access 2)edge Bob can only access 3)edge both Alice and Bob can access\n            int u= edge[1];\n            int v= edge[2];\n            \n            if(cat == 3){//edge both Alice and Bob an access\n                \n                //creating dependency of nodes in graph 1 and 2 \n                boolean tempAlice= union(u, v, parentAlice);\n                boolean tempBob= union(u, v, parentBob);\n                \n                if(tempAlice == true)\n                    mergeAlice+= 1;\n                \n                if(tempBob == true)\n                    mergeBob+= 1;\n                \n                if(tempAlice == false && tempBob == false)//retundant or the cyclic non-dependent edge//both Alice and Bob don't rquire it connection is already there between these pair of nodes\n                    removeEdge+= 1;\n            }\n            else if(cat == 2){//edge Bob can only access \n                \n                //creating dependency of nodes in graph 2\n                boolean tempBob= union(u, v, parentBob);\n                \n                if(tempBob == true)\n                    mergeBob+= 1;\n                else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n                    removeEdge+= 1;\n            }\n            else{//edge Alice can only access \n                \n                //creating dependency of nodes in graph 1\n                boolean tempAlice= union(u, v, parentAlice);\n                \n                if(tempAlice == true)\n                    mergeAlice+= 1; \n                else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n                    removeEdge+= 1;\n            }\n        }\n        if(mergeAlice != n || mergeBob != n)//all node are not connected, connectedness is not maintained \n            return -1;\n        return removeEdge;//number of edge removed by maintaining the connectedness \n    }\n    \n    public int find(int x, int[] parent)\n    {\n        if(parent[x] == x)//when we found the absolute root or the leader of the set \n            return x;\n        \n        int temp= find(parent[x], parent);\n        \n        parent[x]= temp;//Path Compression//child pointing to the absolute root or the leader of the set, while backtracking\n        \n        return temp;//returning the absolute root \n    }\n    \n    public boolean union(int x, int y, int[] parent)\n    {\n        int lx= find(x, parent);//leader of set x or the absolute root\n        int ly= find(y, parent);//leader of set y or the absolute root\n        \n        if(lx != ly){//belong to different set merging \n            \n            //Rank Compression is not done, but you can do it \n            parent[lx]= ly;\n            \n            return true;//union done, dependency created\n        }\n        else\n            return false;//no union done cycle is due to this edge \n    }//Please do Upvote, it helps a lot \n}",
        "solution_c": "class Solution {\npublic:\n    vector < int > Ar , Ap , Br , Bp; // alice and bob parent and rank arrays\n    static bool cmp(vector < int > & a , vector < int > & b){\n      return a[0] > b[0];\n    }\n    // lets create the alice graph first\n    // find function for finding the parent nodes\n    int find1(int x){\n     if(x == Ap[x]) return x;\n         return Ap[x] = find1(Ap[x]);\n    }\n    // if nodes are already connected return 1 else make the connection and return 0\n    bool union1( int x , int y){\n      int parX = find1(x);\n    int parY = find1(y);\n        if(parX == parY) return 1;\n        if(Ar[parX] > Ar[parY]){\n          Ap[parY] = parX;\n        }\n         else if(Ar[parX] < Ar[parY]){\n          Ap[parX] = parY;\n        }\n        else {\n           Ap[parY] = parX;\n            Ar[parX]++;\n        }\n        return 0;\n    }\n    // same thing do for bob graph\n     int find2(int x){\n     if(x == Bp[x]) return x;\n         return Bp[x] = find2(Bp[x]);\n    }\n\n    bool union2( int x , int y){\n      int parX = find2(x);\n    int parY = find2(y);\n        if(parX == parY) return 1;\n        if(Br[parX] > Br[parY]){\n          Bp[parY] = parX;\n        }\n         else if(Br[parX] < Br[parY]){\n          Bp[parX] = parY;\n        }\n        else {\n           Bp[parY] = parX;\n            Br[parX]++;\n        }\n        return 0;\n    }\n\n    int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {\n       Ar.resize(n , 1); Ap.resize(n , 1); Br.resize(n , 1); Bp.resize(n , 1);\n\n        for(int i = 0; i<n ; i++){\n         Ap[i] = i;\n            Bp[i] = i;\n        }\n\n        sort(edges.begin() , edges.end() , cmp);\n        int ans = 0;\n        // give priority to 3rd type of vertices\n        for(auto a : edges){\n         if(a[0] != 3) continue;\n            if(union1(a[1]-1 , a[2]-1))ans++;\n\n           union2(a[1] -1, a[2]-1);\n\n        }\n        // now try the edges one by one and check if it the given nodes are already connected in respective alice and bob graph or not\n        for(auto a : edges){\n        if(a[0] == 3) continue;\n            if(a[0] == 1) {\n             if(union1(a[1]-1 , a[2]-1))ans++; }\n\n            else {\n              if(union2(a[1]-1 , a[2]-1))ans++;}\n        }\n        int cnt1 = 0, cnt2 = 0;\n        for(int i = 0; i< n ; i++){\n          if(Ap[i] == i) cnt1++;\n            if(Bp[i] == i) cnt2++;\n        }\n        if(cnt1 >1 | cnt2 >1) return -1;\n\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Sum of Digits in Base K",
        "algo_input": "Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.\n\nAfter converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.\n\n&nbsp;\nExample 1:\n\nInput: n = 34, k = 6\nOutput: 9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\n\n\nExample 2:\n\nInput: n = 10, k = 10\nOutput: 1\nExplanation: n is already in base 10. 1 + 0 = 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\t2 &lt;= k &lt;= 10\n\n",
        "solution_py": "class Solution:\n    def sumBase(self, n: int, k: int) -> int:\n        cnt = 0\n        while n:\n            cnt += (n % k)\n            n //= k\n        print(cnt)\n        return cnt",
        "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar sumBase = function(n, k) {\n    return n.toString(k).split(\"\").reduce((acc, cur) => +acc + +cur)\n};",
        "solution_java": "class Solution {\n    public int sumBase(int n, int k) {\n        int res = 0;\n        for (; n > 0; n /= k)\n            res += n % k;\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumBase(int n, int k) {\n        int sum=0;\n        while(n!=0) sum+=n%k,n=n/k;\n        return sum;\n    }\n};"
    },
    {
        "title": "Binary Tree Postorder Traversal",
        "algo_input": "Given the root of a&nbsp;binary tree, return the postorder traversal of its nodes' values.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,2,3]\nOutput: [3,2,1]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [1]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of the nodes in the tree is in the range [0, 100].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow up: Recursive solution is trivial, could you do it iteratively?",
        "solution_py": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime:   O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tif root is None:\n\t\t\treturn []\n\n\t\tpostorder = []\n\t\tstack = [root]\n\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tpostorder.append(node.val)\n\t\t\tif node.left is not None:\n\t\t\t\tstack.append(node.left)\n\t\t\tif node.right is not None:\n\t\t\t\tstack.append(node.right)\n\n\t\treturn postorder[::-1]\n\n\nclass Solution:\n\t\"\"\"\n\tTime:   O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.postorder_generator(root))\n\n\t@classmethod\n\tdef postorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.postorder_generator(tree.left)\n\t\t\tyield from cls.postorder_generator(tree.right)\n\t\t\tyield tree.val",
        "solution_js": "class Pair{\n    constructor(node, state){\n        this.node = node;\n        this.state = state;\n    }\n}\nvar postorderTraversal = function(root) {\n    let ans = [];\n    let st = []; // stack\n    root != null && st.push(new Pair(root, 1));\n\n    while(st.length > 0){\n        let top = st[st.length - 1];\n\n        if(top.state == 1){\n\n            top.state++;\n            if(top.node.left != null){\n                st.push(new Pair(top.node.left, 1))\n            }\n        } else if(top.state == 2){\n            top.state++;\n            if(top.node.right != null){\n                st.push(new Pair(top.node.right, 1))\n            }\n        } else{\n            ans.push(top.node.val);\n            st.pop();\n        }\n    }\n    return ans;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n    List<Integer> res = new ArrayList<>();\n    public List<Integer> postorderTraversal(TreeNode root) {\n        traversal(root);\n        return res;\n    }\n\n    public void traversal(TreeNode root){\n        if(root == null)\n            return;\n        traversal(root.left);\n        traversal(root.right);\n        res.add(root.val);\n    }\n}",
        "solution_c": "class Solution {\n    void solve(TreeNode *root, vector<int> &ans){\n        if(root == NULL) return;\n        solve(root->left, ans);\n        solve(root->right, ans);\n        ans.push_back(root->val);\n    }\npublic:\n    vector<int> postorderTraversal(TreeNode* root) {\n        vector<int> ans;\n        solve(root, ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Shortest Bridge",
        "algo_input": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water.\n\nAn island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.\n\nYou may change 0's to 1's to connect the two islands to form one island.\n\nReturn the smallest number of 0's you must flip to connect the two islands.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,1],[1,0]]\nOutput: 1\n\n\nExample 2:\n\nInput: grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t2 &lt;= n &lt;= 100\n\tgrid[i][j] is either 0 or 1.\n\tThere are exactly two islands in grid.\n\n",
        "solution_py": "class Solution:\n    def shortestBridge(self, grid):\n        m, n = len(grid), len(grid[0])\n        start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n        \n        \n        stack = [(start_i, start_j)]\n        visited = set(stack)\n        while stack:\n            i, j = stack.pop()\n            visited.add((i, j))  \n            for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n                if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n                    stack.append((ii, jj))\n                    visited.add((ii, jj))\n        \n        \n        ans = 0\n        queue = list(visited)\n        while queue:\n            new_queue = []\n            for i, j in queue:\n                for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n                    if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n                        if grid[ii][jj] == 1:\n                            return ans\n                        new_queue.append((ii, jj))\n                        visited.add((ii, jj))\n            queue = new_queue\n            ans += 1",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst DIR = [\n    [0,1],\n    [0,-1],\n    [1,0],\n    [-1,0]\n];\n\nvar shortestBridge = function(grid) {\n    const que = [];\n    const ROWS = grid.length;\n    const COLS = grid[0].length;\n\n    // find first insland\n    outer:\n    for(let row=0; row<ROWS; row++) {\n        for(let col=0; col<COLS; col++) {\n            if(grid[row][col] == 1) {\n                const stack = [[row, col]];\n                while(stack.length) {\n                    const [r, c] = stack.pop();\n                    que.push([r, c]);\n                    grid[r][c] = 2; // mark as visited.\n                    for(const dir of DIR) {\n                        const newRow = r+dir[0];\n                        const newCol = c+dir[1];\n                        if(newRow<0 || newCol<0 || newRow>=ROWS || newCol>=COLS) continue;\n                        if(grid[newRow][newCol] != 1) continue;\n                        stack.push([newRow, newCol]);\n                    }\n                }\n                break outer;\n            }\n        }\n    }\n    let steps = 0;\n    while(que.length) {\n        let size = que.length;\n        for(let i=0; i<size; i++) {\n            const [row, col] = que.shift();\n            for(const dir of DIR) {\n                const newRow = row+dir[0];\n                const newCol = col+dir[1];\n                if(newRow<0 || newCol<0 || newRow>=ROWS || newCol>=COLS) continue;\n                if(grid[newRow][newCol] == 2) continue;\n                if(grid[newRow][newCol] == 1) return steps;\n                grid[newRow][newCol] = 2; // mark as visited.\n                que.push([newRow, newCol]);\n            }\n        }\n        steps++;\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}};\n    public int shortestBridge(int[][] grid) {\n        boolean[][] visited=new boolean[grid.length][grid[0].length];\n        LinkedList<Pair> queue=new LinkedList<Pair>();\n        boolean found=false;\n        for(int i=0;i<grid.length && !found;i++){\n            for(int j=0;j<grid[0].length && !found;j++){\n                if(grid[i][j]==1){\n                    dfs(grid,i,j,queue,visited);\n                    found=true;\n                }\n            }\n        }\n        int level=0;\n        while(queue.size()>0){\n            int size=queue.size();\n            while(size-- >0){\n                Pair pair=queue.poll();\n                for(int k=0;k<4;k++){\n                    int rowDash=pair.row+dirs[k][0];\n                    int colDash=pair.col+dirs[k][1];\n                    if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n                       visited[rowDash][colDash]==true )continue;\n                    if(grid[rowDash][colDash]==1) return level;\n                    queue.add(new Pair(rowDash,colDash));\n                    visited[rowDash][colDash]=true;\n                }\n            }\n            level++;\n        }\n        return -1;\n    }\n    private void dfs(int[][] grid,int i,int j,LinkedList<Pair> queue,boolean[][] visited){\n        visited[i][j]=true;\n        queue.add(new Pair(i,j));\n        for(int k=0;k<4;k++){\n            int rowDash=i+dirs[k][0];\n            int colDash=j+dirs[k][1];\n        if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n           visited[rowDash][colDash]==true || grid[rowDash][colDash]==0)continue;\n        dfs(grid,rowDash,colDash,queue,visited);\n        }\n    }\n    static class Pair{\n        int row;\n        int col;\n        public Pair(int row,int col){\n            this.row=row;\n            this.col=col;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void findOneIsland(vector<vector<int>>& grid, int i, int j, queue<pair<int, int>>& q){\n        if(i<0 || j<0 || i==grid.size() || j==grid.size() || grid[i][j]!=1)\n            return;\n        grid[i][j] = 2;\n        q.push({i,j});\n\n        findOneIsland(grid, i, j-1, q);\n        findOneIsland(grid, i, j+1, q);\n        findOneIsland(grid, i-1, j, q);\n        findOneIsland(grid, i+1, j, q);\n\n    }\n    int shortestBridge(vector<vector<int>>& grid) {\n        int n = grid.size();\n        queue<pair<int, int>> q;\n        int res=0;\n        bool OneIslandFound = false;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                if(grid[i][j]==1){\n                    OneIslandFound = true;\n                    findOneIsland(grid, i, j, q);\n                    break;\n                }\n            }\n            if(OneIslandFound)\n                break;\n        }\n\n        while(!q.empty()){\n            int i=q.front().first, j=q.front().second;\n            q.pop();\n            if(i!=0 && grid[i-1][j]<2){\n                if(grid[i-1][j]==1){\n                    res = grid[i][j]-2;\n                    break;\n                }\n                if(grid[i-1][j]==0){\n                    grid[i-1][j] = grid[i][j]+1;\n                    q.push({i-1, j});\n                }\n            }\n\n            if(i!=grid.size()-1 && grid[i+1][j]<2){\n                if(grid[i+1][j]==1){\n                    res = grid[i][j]-2;\n                    break;\n                }\n                if(grid[i+1][j]==0){\n                    grid[i+1][j] = grid[i][j]+1;\n                    q.push({i+1, j});\n                }\n            }\n\n            if(j!=0 && grid[i][j-1]<2){\n                if(grid[i][j-1]==1){\n                    res = grid[i][j]-2;\n                    break;\n                }\n                if(grid[i][j-1]==0){\n                    grid[i][j-1] = grid[i][j]+1;\n                    q.push({i, j-1});\n                }\n            }\n\n            if(j!=grid.size()-1 && grid[i][j+1]<2){\n                if(grid[i][j+1]==1){\n                    res = grid[i][j]-2;\n                    break;\n                }\n                if(grid[i][j+1]==0){\n                    grid[i][j+1] = grid[i][j]+1;\n                    q.push({i, j+1});\n                }\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "N-Repeated Element in Size 2N Array",
        "algo_input": "You are given an integer array nums with the following properties:\n\n\n\tnums.length == 2 * n.\n\tnums contains n + 1 unique elements.\n\tExactly one element of nums is repeated n times.\n\n\nReturn the element that is repeated n times.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,3,3]\nOutput: 3\nExample 2:\nInput: nums = [2,1,2,5,3,2]\nOutput: 2\nExample 3:\nInput: nums = [5,1,5,2,5,3,5,4]\nOutput: 5\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 5000\n\tnums.length == 2 * n\n\t0 &lt;= nums[i] &lt;= 104\n\tnums contains n + 1 unique elements and one of them is repeated exactly n times.\n\n",
        "solution_py": "class Solution:\n    def repeatedNTimes(self, nums: List[int]) -> int:\n        return Counter(nums).most_common(1)[0][0]",
        "solution_js": "var repeatedNTimes = function(nums) {\n\n//   loop through the array and then as we go over every num we filter that number and get the length. If the length is equal to 1 that is not the element so we continue if its not equal to one its the element we want and we just return that element. \n\n  for (let num of nums) {\n    let len = nums.filter(element => element === num).length\n    if (len == 1) continue;\n    else return num\n  }\n\n};",
        "solution_java": "class Solution {\n    public int repeatedNTimes(int[] nums) {\n        int count = 0;\n        for(int i = 0; i < nums.length; i++) {\n            for(int j = i + 1; j < nums.length; j++) {\n                if(nums[i] == nums[j])\n                    count = nums[j];\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int repeatedNTimes(vector<int>& nums) {\n        unordered_map<int, int> mp;\n        for(auto it : nums) mp[it]++;\n        int n;\n        for(auto it : mp) {\n            if(it.second == nums.size() / 2) {\n                n = it.first;\n                break;\n            }\n        }\n        return n;\n    }\n};"
    },
    {
        "title": "Sum of Subsequence Widths",
        "algo_input": "The width of a sequence is the difference between the maximum and minimum elements in the sequence.\n\nGiven an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.\n\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,1,3]\nOutput: 6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\n\nExample 2:\n\nInput: nums = [2]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def sumSubseqWidths(self, nums: List[int]) -> int:\n        nums.sort()\n        n = len(nums)\n        M = 10**9+7\n        res = 0\n        le = 1\n        re = pow(2, n-1, M)\n        #by Fermat's Little Thm\n        #inverse of 2 modulo M\n        inv = pow(2, M-2, M)\n        for num in nums:\n            res = (res + num * (le - re))%M\n            le = (le * 2) % M\n            re = (re * inv) % M\n        return res",
        "solution_js": "var sumSubseqWidths = function(nums) {\n    const mod = 1000000007;\n    nums.sort((a, b) => a - b), total = 0, power = 1;\n    for(let i = 0; i < nums.length; i++) {\n        total = (total + nums[i] * power) % mod;\n        power = (power * 2) % mod;\n    }\n\n    power = 1;\n    for(let i = nums.length - 1; i >= 0; i--) {\n        total = (total - nums[i] * power + mod) % mod;\n        power = (power * 2) % mod;\n    }\n\n    return (total + mod) % mod\n};",
        "solution_java": "class Solution {\n    public int sumSubseqWidths(int[] nums) {\n        int MOD = (int)1e9 + 7;\n        Arrays.sort(nums);\n\n        long ans = 0;\n        long p = 1;\n        for(int i = 0; i < nums.length; i++){\n            ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD;\n            p = (p * 2) % MOD;\n        }\n        return (int)ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumSubseqWidths(vector<int>& nums) {\n        vector < long long > pow(nums.size() ); \n        pow[0] = 1;\n          for(int i = 1 ; i<nums.size(); i++){ \n             pow[i] = pow[i-1] * 2 % 1000000007; \n          }\n        sort(nums.begin() , nums.end()); \n       long long ans = 0 ;   \n        for(int i = 0 ; i<nums.size(); i++){ \n              ans = (ans + pow[i]*nums[i]) % 1000000007; \n               ans = (ans - pow[nums.size()-i-1] * (long long)nums[i] ) % 1000000007; \n           \n          } \n        return ans; \n    }\n};"
    },
    {
        "title": "Reverse String",
        "algo_input": "Write a function that reverses a string. The input string is given as an array of characters s.\n\nYou must do this by modifying the input array in-place with O(1) extra memory.\n\n&nbsp;\nExample 1:\nInput: s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\nOutput: [\"o\",\"l\",\"l\",\"e\",\"h\"]\nExample 2:\nInput: s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\nOutput: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is a printable ascii character.\n\n",
        "solution_py": "class Solution(object):\n    def reverseString(self, s):\n        for i in range(len(s)):\n            s.insert(i,s.pop())\n        return s",
        "solution_js": "var reverseString = function(s) {\n    for(let i = 0 ; i < s.length / 2 ; i++){\n        [s[i], s[s.length - i - 1]] = [s[s.length - i - 1], s[i]]\n    }\n    return s;\n};",
        "solution_java": "class Solution {\n    public void reverseString(char[] s) {\n        int start = 0, end = s.length-1;\n\n        while(start < end) {\n            char temp = s[end];\n            s[end] = s[start];\n            s[start] = temp;\n            start++;\n            end--;\n        }\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void reverseString(vector<char>& s) {\n        int i = -1, j = s.size();\n        while (++i < --j){\n            //Instead of using temp we can do the following\n            s[i] = s[j] + s[i];\n            s[j] = s[i] - s[j];\n            s[i] = s[i] - s[j];\n        }\n    }\n};"
    },
    {
        "title": "Day of the Year",
        "algo_input": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.\n\n&nbsp;\nExample 1:\n\nInput: date = \"2019-01-09\"\nOutput: 9\nExplanation: Given date is the 9th day of the year in 2019.\n\n\nExample 2:\n\nInput: date = \"2019-02-10\"\nOutput: 41\n\n\n&nbsp;\nConstraints:\n\n\n\tdate.length == 10\n\tdate[4] == date[7] == '-', and all other date[i]'s are digits\n\tdate represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.\n\n",
        "solution_py": "class Solution:\n    def dayOfYear(self, date: str) -> int:\n        d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}\n        year=int(date[:4])\n        if year%4==0:\n            if year%100==0:\n                if year%400==0:\n                    d[2]=29\n            else:\n                d[2]=29\n        month=int(date[5:7])\n        day=int(date[8:])\n        ans=0\n        for i in range(1,month+1):\n            ans+=d[i]\n        return ans-(d[month]-day)",
        "solution_js": "var dayOfYear = function(date) {\n    let dat2 = new Date(date)\n    let dat1 = new Date(dat2.getFullYear(),00,00)\n    let totalTime = dat2 - dat1\n    return Math.floor(totalTime/1000/60/60/24)\n};",
        "solution_java": "class Solution {\n    public int dayOfYear(String date) {\n        int days = 0;\n        int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};\n        String[] year = date.split(\"-\");\n        int y = Integer.valueOf(year[0]);\n        int month = Integer.valueOf(year[1]);\n        int day = Integer.valueOf(year[2]);\n        boolean leap = false;\n        for(int i = 0; i < month-1; i++){\n            days = days+arr[i];\n        }\n        days = days+day;\n        if(y%4==0){\n            if(y%100==0){\n                if(y%400==0){\n                    leap = true;\n                }\n                else{\n                    leap = false;\n                }\n            }\n            else{\n                leap = true;\n            }\n        }\n        else{\n            leap = false;\n        }\n        if(leap==true && month>2){\n            System.out.println(\"Leap Year\");\n            days = days+1;\n        }\n        return days;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool leapyear(int year){\n        return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));\n    }\n        \n    int dayOfYear(string date) {\n        vector<int> v;\n        int ans = 0;\n        int n = date.length();\n        for (int i = 0; i < n; i++) {\n            if (date[i] >= '0' && date[i] <= '9') {\n                ans = ans * 10 + (date[i] - '0'); // subtract '0' to get the integer value\n            } else {\n                v.push_back(ans);\n                ans = 0;\n            }\n        }\n        v.push_back(ans); // add the last value to the vector\n        if (v.size() != 3) return -1; // error handling for invalid input\n        int year = v[0];\n        int month = v[1];\n        int day = v[2];\n        if (month == 1) return day;\n        if (month == 2) return 31 + day;\n       \n        if (month == 3) return leapyear(year) ? 60 + day : 59 + day;\n         if (month == 4) return leapyear(year) ? 91 + day : 90 + day;\n         if (month == 5) return leapyear(year) ? 121 + day : 120 + day;\n         if (month == 6) return leapyear(year) ? 152 + day : 151 + day;\n         if (month == 7) return leapyear(year) ? 182 + day : 181 + day;\n         if (month == 8) return leapyear(year) ? 213 + day : 212 + day;\n         if (month == 9) return leapyear(year) ? 244 + day : 243 + day;\n         if (month == 10) return leapyear(year) ? 274+ day : 273 + day;\n         if (month == 11) return leapyear(year) ? 305 + day : 304 + day;\n         if (month == 12) return leapyear(year) ? 335 + day : 334 + day;\n        return -1;\n    }\n};"
    },
    {
        "title": "Push Dominoes",
        "algo_input": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.\n\nAfter each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.\n\nWhen a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.\n\nFor the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.\n\nYou are given a string dominoes representing the initial state where:\n\n\n\tdominoes[i] = 'L', if the ith domino has been pushed to the left,\n\tdominoes[i] = 'R', if the ith domino has been pushed to the right, and\n\tdominoes[i] = '.', if the ith domino has not been pushed.\n\n\nReturn a string representing the final state.\n\n&nbsp;\nExample 1:\n\nInput: dominoes = \"RR.L\"\nOutput: \"RR.L\"\nExplanation: The first domino expends no additional force on the second domino.\n\n\nExample 2:\n\nInput: dominoes = \".L.R...LR..L..\"\nOutput: \"LL.RR.LLRRLL..\"\n\n\n&nbsp;\nConstraints:\n\n\n\tn == dominoes.length\n\t1 &lt;= n &lt;= 105\n\tdominoes[i] is either 'L', 'R', or '.'.\n\n",
        "solution_py": "class Solution:\n    def pushDominoes(self, dom: str) -> str:\n        from collections import deque\n        n = len(dom)\n        d = set()\n        q = deque()\n        arr = [0 for i in range(n)]\n        for i in range(n):\n            if dom[i] == \"L\":\n                arr[i] = -1\n                d.add(i)\n                q.append((i,\"L\"))\n            if dom[i] == \"R\":\n                arr[i] = 1\n                d.add(i)\n                q.append((i,\"R\"))\n        while q:\n            t1 = set()\n            for _ in range(len(q)):\n                t = q.popleft()\n                if t[1] == \"L\":\n                    if t[0]-1 >= 0 and t[0]-1 not in d:\n                        t1.add(t[0]-1)\n                        arr[t[0]-1] -= 1\n                else:\n                    if t[0]+1 < n and t[0]+1 not in d:\n                        t1.add(t[0]+1)\n                        arr[t[0]+1] += 1\n            for val in t1:\n                d.add(val)\n                if arr[val] > 0:\n                    q.append((val,\"R\"))\n                elif arr[val]<0:\n                    q.append((val,\"L\"))\n        ans = \"\"\n        for val in arr:\n            if val<0:\n                ans += \"L\"\n            elif val>0:\n                ans += \"R\"\n            else:\n                ans += \".\"\n        return ans",
        "solution_js": "/**\n * @param {string} dominoes\n * @return {string}\n */\nvar pushDominoes = function(dominoes) {\n    \n    let len = dominoes.length;\n    let fall = [];\n    let force = 0;\n    let answer = \"\";\n    \n    // Traverse from left to right. Focus on the dominoes falling to the right\n    for (let i = 0; i < len; i++) {\n        if (dominoes[i] == 'R') {\n            force = len;\n        } else if (dominoes[i] == 'L') {\n            force = 0;\n        } else {\n            force = Math.max(force-1,0);\n        }\n        fall[i] = force;\n    }\n    \n    //console.log('fall array 1: ', fall);\n    \n    // Traverse from right to left. Focus on the dominoes falling to the left\n    // Subtract the value from the values above\n    for (let i = len-1; i >= 0; i--) {\n        if (dominoes[i] == 'L') {\n            force = len;\n        } else if (dominoes[i] == 'R') {\n            force = 0;\n        } else {\n            force = Math.max(force-1,0);\n        }\n        fall[i] -= force;\n    }    \n    \n    //console.log('fall array 2: ', fall);\n    \n    // Just traverse through the fall[] array and assign the values in the answer string accordingly\n    for (let i = 0; i < len; i++) {\n        if (fall[i] < 0)\n            answer += 'L';\n        else if (fall[i] > 0 )\n            answer += 'R';\n        else\n            answer += '.';\n    }\n    \n    //console.log('answer: ', answer);\n    \n    return answer;\n    \n};",
        "solution_java": "// Time complexity: O(N)\n// Space complexity: O(N), where N is the length of input string\nclass Solution {\n    public String pushDominoes(String dominoes) {\n        // ask whether dominoes could be null\n        final int N = dominoes.length();\n        if (N <= 1) return dominoes;\n        char[] res = dominoes.toCharArray();\n        int i = 0;\n        while (i < N) {\n            if (res[i] == '.') {\n                i++;\n            } else if (res[i] == 'L') { // push left\n                int j = i-1;\n                while (j >= 0 && res[j] == '.') {\n                    res[j--] = 'L';\n                }\n                i++;\n            } else { // res[i] == 'R'\n                int j = i+1;\n                while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side\n                    j++;\n                }\n                if (j < N && res[j] == 'L') { // if found 'L', push left and right\n                    for (int l = i+1, r = j-1; l < r; l++, r--) {\n                        res[l] = 'R';\n                        res[r] = 'L';\n                    }\n                    i = j + 1;\n                } else { // if no 'L', push right\n                    while (i < j) {\n                        res[i++] = 'R';\n                    }\n                }\n            }\n        }\n        return String.valueOf(res);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string pushDominoes(string dominoes) {\n        #define SET(ch, arr) \\\n                    if (dominoes[i] == ch) { count = 1; prev = ch; } \\\n                    else if (dominoes[i] != '.') prev = dominoes[i]; \\\n                    if (prev == ch && dominoes[i] == '.') arr[i] = count++;\n\n        string res = \"\";\n        char prev;\n        int n = dominoes.size(), count = 1;\n\n        vector<int> left(n, 0), right(n, 0);\n        for (int i = 0; i < n; i++) {\n            SET('R', right);\n        }\n\n        prev = '.';\n        for (int i = n-1; i >= 0; i--) {\n            SET('L', left);\n        }\n\n        for (int i = 0; i < n; i++) {\n            if (!left[i] && !right[i]) res += dominoes[i];\n            else if (!left[i]) res += 'R';\n            else if (!right[i]) res += 'L';\n            else if (left[i] == right[i]) res += '.';\n            else if (left[i] < right[i]) res += 'L';\n            else res += 'R';\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Unique Paths III",
        "algo_input": "You are given an m x n integer array grid where grid[i][j] could be:\n\n\n\t1 representing the starting square. There is exactly one starting square.\n\t2 representing the ending square. There is exactly one ending square.\n\t0 representing empty squares we can walk over.\n\t-1 representing obstacles that we cannot walk over.\n\n\nReturn the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput: 2\nExplanation: We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n\n\nExample 2:\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput: 4\nExplanation: We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n\n\nExample 3:\n\nInput: grid = [[0,1],[2,0]]\nOutput: 0\nExplanation: There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 20\n\t1 &lt;= m * n &lt;= 20\n\t-1 &lt;= grid[i][j] &lt;= 2\n\tThere is exactly one starting cell and one ending cell.\n\n",
        "solution_py": "class Solution:\n    def uniquePathsIII(self, grid: List[List[int]]) -> int:\n        ans, empty = 0, 1\n        \n        def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None:\n            if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1:\n                return\n            nonlocal ans\n            if grid[row][col] == 2:\n                if empty == count:\n                    ans += 1\n                return\n            if (row, col) not in visited:\n                visited.add((row, col))\n                dfs(grid, row + 1, col, count + 1, visited)\n                dfs(grid, row - 1, col, count + 1, visited)\n                dfs(grid, row, col + 1, count + 1, visited)\n                dfs(grid, row, col - 1, count + 1, visited)\n                visited.remove((row, col))\n        \n        row, col = 0, 0\n        for i in range(len(grid)):\n            for j in range(len(grid[0])):\n                if grid[i][j] == 1:\n                    row, col = i, j\n                elif grid[i][j] == 0:\n                    empty += 1\n        dfs(grid, row, col, 0, set())\n        return ans",
        "solution_js": "// 980. Unique Paths III\nvar uniquePathsIII = function(grid) {\n    const M = grid.length; // grid height\n    const N = grid[0].length; // grid width\n    let result = 0; // final result\n    let startY = 0, startX = 0; // starting point coordinates\n    let finalY = 0, finalX = 0; // endpoint coordinates\n    let empty = 0; // count of empty squares\n    let visit = Array(M); // visited squares (MxN of booleans)\n\n    // Initialization of required variables\n    for (let i = 0; i < M; i++) {\n        visit[i] = Array(N).fill(false); // now: \"visit[i][j] === false\"\n        for (let j = 0; j < N; j++) {\n            switch (grid[i][j]) {\n                case 0 : empty++; break;\n                case 1 : startY = i; startX = j; break;\n                case 2 : finalY = i; finalX = j; break;\n            }\n        }\n    }\n\n    // Recursively run DFS and get the answer in the \"result\" variable\n    dfs(startY, startX, visit, 0);\n    return result;\n\n    // DFS implementation\n    function dfs (startY, startX, visit, step) {\n\n        // If it's a wrong square, then exit immediately\n        if (startY < 0 || startY >= M || // off grid (height)\n            startX < 0 || startX >= N || // off grid (width)\n            visit[startY][startX] || // already processed\n            grid [startY][startX] === -1 // this is an obstacle\n        ) return; // ... exit now\n\n        // Base case: we're at the endpoint, need to stop the recursion.\n        // If all of squares are visited, increase the \"result\":\n        // (count of paths from start to the end).\n        if (startY === finalY && startX === finalX) {\n            if (step - 1 === empty) result++;\n            return;\n        }\n\n        // Run DFS for neighboring squares.\n        // Increase the number of steps (count of the visited squares).\n        visit[startY][startX] = true; // mark current square as visited\n        dfs(startY-1, startX, visit, step + 1); // top\n        dfs(startY, startX+1, visit, step + 1); // right\n        dfs(startY+1, startX, visit, step + 1); // bottom\n        dfs(startY, startX-1, visit, step + 1); // left\n        visit[startY][startX] = false; // restore visited square\n    }\n};",
        "solution_java": "class Solution {\n    int walk = 0;\n    public int uniquePathsIII(int[][] grid) {\n        int m = grid.length;\n        int n = grid[0].length;\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 0) {\n                    walk++;\n                }\n            }\n        }\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 1) {\n                    return ways(grid, i, j, m, n, 0);\n                }\n            }\n        }\n        return 0;\n    }\n    public int ways(int[][] grid, int cr, int cc, int m, int n, int count) {\n        if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) {\n            return 0;\n        }\n        if (grid[cr][cc] == 2) {\n            if (count - 1 == walk) return 1;\n            return 0;\n        }\n        grid[cr][cc] = -1;\n        int ans = 0;\n        int[] r = {0, 1, 0, -1};\n        int[] c = {1, 0, -1, 0};\n        for (int i = 0; i < 4; i++) {\n            ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1);\n        }\n        grid[cr][cc] = 0;\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dfs(vector<vector<int>>&grid,int x,int y,int zero){\n        // Base Condition\n        if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || grid[x][y] == -1){\n            return 0;\n        }\n        if(grid[x][y] == 2){\n            return zero == -1 ? 1 : 0; // Why zero = -1, because in above example we have 9 zero's. So, when we reach the final cell we are covering one cell extra that means if all zero all covered then on reaching final it will make zero count = -1\n            // If that's the case we find the path and return '1' otherwise return '0';\n        }\n        grid[x][y] = -1; // mark the visited cells as -1;\n        zero--; // and reduce the zero by 1\n\n        int totalPaths = dfs(grid, x + 1, y, zero) + // calculating all the paths available in 4 directions\n            dfs(grid, x - 1, y, zero) +\n            dfs(grid, x, y + 1, zero) +\n            dfs(grid, x, y - 1, zero);\n\n        // Let's say if we are not able to count all the paths. Now we use Backtracking over here\n        grid[x][y] = 0;\n        zero++;\n\n        return totalPaths; // if we get all the paths, simply return it.\n    }\n\n    int uniquePathsIII(vector<vector<int>>& grid) {\n       int start_x,start_y=0,cntzero=0;\n\n        for(int i=0;i<grid.size();i++){\n            for(int j=0;j<grid[0].size();j++){\n                if(grid[i][j]==0) cntzero++;\n               else if(grid[i][j]==1){\n                    start_x=i;\n                    start_y=j;\n                }\n            }\n        }\n      return dfs(grid,start_x,start_y,cntzero);\n\n    }\n};"
    },
    {
        "title": "Number of Wonderful Substrings",
        "algo_input": "A wonderful string is a string where at most one letter appears an odd number of times.\n\n\n\tFor example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not.\n\n\nGiven a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.\n\nA substring is a contiguous sequence of characters in a string.\n\n&nbsp;\nExample 1:\n\nInput: word = \"aba\"\nOutput: 4\nExplanation: The four wonderful substrings are underlined below:\n- \"aba\" -&gt; \"a\"\n- \"aba\" -&gt; \"b\"\n- \"aba\" -&gt; \"a\"\n- \"aba\" -&gt; \"aba\"\n\n\nExample 2:\n\nInput: word = \"aabb\"\nOutput: 9\nExplanation: The nine wonderful substrings are underlined below:\n- \"aabb\" -&gt; \"a\"\n- \"aabb\" -&gt; \"aa\"\n- \"aabb\" -&gt; \"aab\"\n- \"aabb\" -&gt; \"aabb\"\n- \"aabb\" -&gt; \"a\"\n- \"aabb\" -&gt; \"abb\"\n- \"aabb\" -&gt; \"b\"\n- \"aabb\" -&gt; \"bb\"\n- \"aabb\" -&gt; \"b\"\n\n\nExample 3:\n\nInput: word = \"he\"\nOutput: 2\nExplanation: The two wonderful substrings are underlined below:\n- \"he\" -&gt; \"h\"\n- \"he\" -&gt; \"e\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 105\n\tword consists of lowercase English letters from 'a'&nbsp;to 'j'.\n",
        "solution_py": "class Solution:\n    def wonderfulSubstrings(self, word: str) -> int:\n        cnt, res, mask = [1] + [0] * 1023, 0, 0\n        for ch in word:\n            mask ^= 1 << (ord(ch) - ord('a'))\n            res += cnt[mask]\n            for n in range(10):\n                res += cnt[mask ^ 1 << n];\n            cnt[mask] += 1\n        return res",
        "solution_js": "/**\n * @param {string} word\n * @return {number}\n */\nvar wonderfulSubstrings = function(word) {\n    let hashMap={},ans=0,binaryRepresentation=0,t,pos,number,oneBitToggled;\n    hashMap[0]=1;\n    for(let i=0;i<word.length;i++){\n        pos = word[i].charCodeAt(0)-\"a\".charCodeAt(0);//Let's use position 0 for a, 1 for b .... 9 for j\n        t = (1 << pos);\n        binaryRepresentation = (binaryRepresentation^t);//Toggle the bit at pos in the current mask(pattern)\n        //This loop will check same binaryRepresentation and all the other binaryRepresentation with difference of 1 bit\n        for(let i=0;i<10;i++){//Check all the numbers by changing 1 position\n            number = (1<<i);//Change 1 bit at a time \n            oneBitToggled = (binaryRepresentation^number);\n            if(hashMap[oneBitToggled]!==undefined){\n                ans += hashMap[oneBitToggled];\n            }\n        }\n        if(hashMap[binaryRepresentation]===undefined){\n            hashMap[binaryRepresentation]=1;\n        }else{\n            ans += hashMap[binaryRepresentation];\n            hashMap[binaryRepresentation]++;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public long wonderfulSubstrings(String word) {\n        int n = word.length();\n        long count = 0;\n        \n        long[] freq = new long[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap\n        \n        freq[0] = 1;\n        int res = 0; // initialize the frequency of 0000000000 as 1 because when no element is encountered, then th bitmask is 0\n        \n        for (int i = 0; i < n; i++) {\n            int mask = (1 << (word.charAt(i) - 'a'));\n            res ^= mask; // toggling bit of the current character to make it from odd to even OR even to odd\n            int chkMask = 1;\n            \n            count += freq[res];\n            for (int j = 1; j <= 10; j++) {  // Loop for checking all possiblities of different places of the Different Bit\n                count += freq[chkMask ^ res];\n                chkMask <<= 1;\n            }\n            \n            freq[res]++; // increasing the frequency of the current bitmask\n        }\n        \n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long wonderfulSubstrings(string word) {\n        int n=word.length();\n        int mask=0;\n        unordered_map<int,int>m;\n        m[0]++;\n        long long int ans=0;\n        for(int i=0;i<n;i++){\n            mask = mask^(1<<(word[i]-'a'));\n            int temp=mask;\n            int j=0;\n            while(j<=9){\n               int x=temp^(1<<j);\n                ans+=m[x];\n                j++;\n\n            }\n            ans+=m[mask];\n            m[mask]++;\n        }\n\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Permutations II",
        "algo_input": "Given a collection of numbers, nums,&nbsp;that might contain duplicates, return all possible unique permutations in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,2]\nOutput:\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\n\n\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 8\n\t-10 &lt;= nums[i] &lt;= 10\n\n",
        "solution_py": "class Solution(object):\n    def permuteUnique(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: List[List[int]]\n        \"\"\"\n        if len(nums) == 1:\n            return [[nums[0]]]\n\n        res = self.permuteUnique(nums[1:])\n\n        for i in range(len(res)-1, -1 , -1):\n            j = 0\n            while j < len(res[i]):\n                if res[i][j] == nums[0]: #to account for repeated nums\n                    break\n                lst = res[i][:]\n                lst.insert(j, nums[0])\n                res.append(lst)\n                j += 1\n\n            res[i].insert(j,nums[0])\n\n        return res",
        "solution_js": "var permuteUnique = function(nums) {\n    const answer = []\n\n    function perm (pos, array) {\n\n        if (pos >= array.length) {\n            answer.push(array)\n        }\n\n        const setObject = new Set()\n\n        for (let index=pos; index<array.length; index++) {\n            if (setObject.has(array[index])) {\n                continue\n            }\n            setObject.add(array[index])\n\n            // swap numbers\n            let temp = array[pos]\n            array[pos] = array[index]\n            array[index] = temp\n\n            perm(pos + 1, [...array])\n\n            // undo swapping for next iteration\n            temp = array[index]\n            array[index] = array[pos]\n            array[pos] = temp\n        }\n    }\n\n    perm(0, nums)\n\n    return answer\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> permuteUnique(int[] nums) {\n        List<List<Integer>> ans = new ArrayList<>();\n        Arrays.sort(nums);\n        boolean used[] = new boolean[nums.length];\n        \n        permutationsFinder(nums,ans,new ArrayList<>(),used);\n        \n        return ans;\n    }\n    \n    static void permutationsFinder(int[] nums,List<List<Integer>> ans,List<Integer> list,boolean used[]){\n        if(list.size() == nums.length){\n            ans.add(new ArrayList<>(list));\n            return;\n        }\n        \n        for(int i=0;i<nums.length;i++){\n            if(used[i]) continue;\n            if(i>0 && nums[i]==nums[i-1] && !used[i-1]) continue;\n            list.add(nums[i]);\n            used[i] = true;\n            permutationsFinder(nums,ans,list,used);\n            list.remove(list.size()-1);\n            used[i] = false;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void fun(vector<int>& nums, vector<vector<int>>&ans,int i)\n    {\n        if(i==nums.size())\n        {\n            ans.push_back(nums);\n            return;\n        }\n        int freq[21]={0};\n        for(int j=i;j<nums.size();j++)\n        {\n            if(freq[nums[j]+10]==0)\n            {\n            swap(nums[i],nums[j]);\n            fun(nums,ans,i+1);\n            swap(nums[i],nums[j]);\n            }\n            freq[nums[j]+10]++;\n        }\n\n    }\n    vector<vector<int>> permuteUnique(vector<int>& nums) {\n        vector<vector<int>>ans;\n        fun(nums,ans,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Remove Duplicate Letters",
        "algo_input": "Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.\n\n&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;= 104\n\ts consists of lowercase English letters.\n\n\n&nbsp;\nNote: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\n",
        "solution_py": "class Solution:\n    def removeDuplicateLetters(self, s: str) -> str:\n        \n\t\tlast_occ = {}\n\t\tstack = []\n\t\tvisited = set()\n\n\t\tfor i in range(len(s)):\n\t\t\tlast_occ[s[i]] = i\n\n\t\tfor i in range(len(s)):\n\n\t\t\tif s[i] not in visited:\n\t\t\t\twhile (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):\n\t\t\t\t\tvisited.remove(stack.pop())\n\n\t\t\t\tstack.append(s[i])\n\t\t\t\tvisited.add(s[i])\n\n\t\treturn ''.join(stack)",
        "solution_js": "var removeDuplicateLetters = function(s) {\n    let sset = [...new Set(s)]\n    if(Math.min(sset) == sset[0]) return [...sset].join('');\n    else {\n        sset.sort();\n        return [...sset].join('');\n    }\n};",
        "solution_java": "class Solution {\n    public String removeDuplicateLetters(String s) {\n        int[] lastIndex = new int[26];\n        for (int i = 0; i < s.length(); i++){\n            lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence\n        }\n        \n        boolean[] seen = new boolean[26]; // keep track seen\n        Stack<Integer> st = new Stack();\n        \n        for (int i = 0; i < s.length(); i++) {\n            int curr = s.charAt(i) - 'a';\n            if (seen[curr]) continue; // if seen continue as we need to pick one char only\n            while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){\n                seen[st.pop()] = false; // pop out and mark unseen\n            }\n            st.push(curr); // add into stack\n            seen[curr] = true; // mark seen\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (!st.isEmpty())\n            sb.append((char) (st.pop() + 'a'));\n        return sb.reverse().toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string removeDuplicateLetters(string s) {\n        int len = s.size();\n        string res = \"\";\n        unordered_map<char, int> M;\n        unordered_map<char, bool> V;\n        stack<int> S;\n        \n        for (auto c : s) {\n            if (M.find(c) == M.end()) M[c] = 1;\n            else M[c]++; \n        }\n        for (unordered_map<char, int>::iterator iter=M.begin(); iter!=M.end(); iter++) V[iter->first] = false;\n        \n        cout<<M.size()<<V.size()<<endl;\n        for (int i=0; i<len; i++) {\n            M[s[i]]--;\n            if (V[s[i]] == true) continue;\n            \n            while (!S.empty() and s[i] < s[S.top()] and M[s[S.top()]] > 0) {\n                V[s[S.top()]] = false;\n                S.pop();\n            }\n            S.push(i);\n            V[s[i]] = true;\n        }\n        while (!S.empty()) {\n            res = s[S.top()] + res;\n            S.pop();\n        }\n        return res;\n    }\n};\n\n\nAnalysis\nTime complexity O(n)\nspace complexity O(n)"
    },
    {
        "title": "Most Frequent Subtree Sum",
        "algo_input": "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.\n\nThe subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).\n\n&nbsp;\nExample 1:\n\nInput: root = [5,2,-3]\nOutput: [2,-3,4]\n\n\nExample 2:\n\nInput: root = [5,2,-5]\nOutput: [2]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n        def dfs(root):\n            \n            if not root: return 0\n            \n            l = dfs(root.left)\n            r = dfs(root.right)\n            res = root.val + l + r\n            \n            d[res] += 1\n            return res\n        \n        d = collections.Counter()\n        dfs(root)\n        maxi = max(d.values())\n        return [i for i in d if d[i] == maxi]\n        \n\t\t# An Upvote will be encouraging\n        \n        ",
        "solution_js": "var findFrequentTreeSum = function(root) {\n\tconst hash = new Map();\n\tconst result = [];\n\tlet max = 0;\n\tconst dfs = (node = root) => {\n\t\tif (!node) return 0;\n\t\tconst { left, right, val } = node;\n\t\tconst sum = val + dfs(left) + dfs(right);\n\t\tconst count = hash.get(sum) ?? 0;\n\t\thash.set(sum, count + 1);\n\t\tmax = Math.max(max, count + 1);\n\t\treturn sum;\n\t};\n\n\tdfs();\n\thash.forEach((value, key) => value === max && result.push(key));\n\treturn result;\n};",
        "solution_java": "class Solution {\n    public int[] findFrequentTreeSum(TreeNode root) {\n\n        HashMap<Integer,Integer> map=new HashMap<>();\n        int sum=sum(root,map);\n        int max=0;\n        int count=0;\n        for(Integer key:map.keySet()){\n            max=Math.max(max,map.get(key));\n        }\n\n        for(Integer key:map.keySet()){\n            if(max==map.get(key)){\n                count++;\n            }\n        }\n        int[] ans=new int[count];\n        int counter=0;\n        for(Integer key:map.keySet()){\n            if(max==map.get(key)){\n                ans[counter++]=key;\n            }\n        }\n\n        return ans;\n\n    }\n    public int sum(TreeNode root,HashMap<Integer,Integer> map){\n        if(root==null)return 0;\n        int lh=sum(root.left,map);\n        int rh=sum(root.right,map);\n        map.put(lh+rh+root.val,map.getOrDefault(lh+rh+root.val,0)+1);\n        return lh+rh+root.val;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    unordered_map<int, int> m;\n    int maxi = 0;\n    int f(TreeNode* root){\n        if(!root) return 0;\n        int l = f(root->left);\n        int r = f(root->right);\n        int sum = root->val + l + r;\n        m[sum]++;\n        maxi = max(maxi, m[sum]);\n        return sum;\n    }\npublic:\n    vector<int> findFrequentTreeSum(TreeNode* root) {\n        vector<int> ans;\n        f(root);\n        for(auto &e : m){\n            if(e.second == maxi) ans.push_back(e.first);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Mirror Reflection",
        "algo_input": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.\n\nThe square room has walls of length p&nbsp;and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.\n\nGiven the two integers p and q, return the number of the receptor that the ray meets first.\n\nThe test cases are guaranteed so that the ray will meet a receptor eventually.\n\n&nbsp;\nExample 1:\n\nInput: p = 2, q = 1\nOutput: 2\nExplanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n\n\nExample 2:\n\nInput: p = 3, q = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= q &lt;= p &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def mirrorReflection(self, p: int, q: int) -> int:\n\n        L = lcm(p,q)\n\n        if (L//q)%2 == 0:\n            return 2\n\n        return (L//p)%2",
        "solution_js": "// Time complexity: O(log (min(p,q))\n// Space complexity: O(1)\n\nvar mirrorReflection = function(p, q) {\n\tlet ext = q, ref = p;\n\t\n\twhile (ext % 2 == 0 && ref % 2 == 0) {\n\t\text /= 2;\n\t\tref /= 2;\n\t}\n\t\n\tif (ext % 2 == 0 && ref % 2 == 1) return 0;\n\tif (ext % 2 == 1 && ref % 2 == 1) return 1;\n\tif (ext % 2 == 1 && ref % 2 == 0) return 2;\n\t\n\treturn -1;\n};",
        "solution_java": " class Solution {\n    public int mirrorReflection(int p, int q) {\n        while (p % 2 == 0 && q % 2 == 0){\n            p >>= 1; q >>= 1;\n        }\n        return 1 - p % 2 + q % 2;\n    }\n};",
        "solution_c": "class Solution {\npublic:\n    int mirrorReflection(int p, int q) {\n        while (p % 2 == 0 && q % 2 == 0){\n            p/=2;\n            q/=2;\n        }\n        return 1 - p % 2 + q % 2;\n    }\n};"
    },
    {
        "title": "Partition Labels",
        "algo_input": "You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.\n\nNote that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\n\nReturn a list of integers representing the size of these parts.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.\n\n\nExample 2:\n\nInput: s = \"eccbbbbdec\"\nOutput: [10]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def partitionLabels(self, s: str) -> List[int]:\n        d = defaultdict(list)\n        for i, char in enumerate(s):\n            d[char].append(i)\n        nums = []\n        \n        for v in d.values():\n            nums.append([v[0], v[-1]])\n\n        start = nums[0][0]\n        maxIndex = nums[0][1]\n        ans = []\n        for i in range(1, len(nums)):\n            if nums[i][0] <= maxIndex:\n                maxIndex = max(maxIndex, nums[i][1])\n            else:\n                ans.append(maxIndex - start + 1)\n                start = nums[i][0]\n                maxIndex = nums[i][1]\n        ans.append(maxIndex - start + 1)\n        # print(ans)\n        return ans",
        "solution_js": "var partitionLabels = function(s) {\n    let last = 0, first = 0;\n\n    let arr = [...new Set(s)], ss = [];\n    let temp = '';\n\n    first = s.indexOf(arr[0]);\n    last = s.lastIndexOf(arr[0]);\n\n    for(let i = 1; i<arr.length; i++){\n        if(s.indexOf(arr[i]) < last){\n            if(last < s.lastIndexOf(arr[i])){\n            last = s.lastIndexOf(arr[i]);\n            }\n        }\n        else{\n            temp = s.slice(first,last+1);\n            ss.push(temp.length);\n            first = s.indexOf(arr[i]);\n            last = s.lastIndexOf(arr[i]);\n        }\n    }\n\n    temp = s.slice(first,last+1);\n    ss.push(temp.length);\n    return ss;\n};",
        "solution_java": "class Solution {\n    public List<Integer> partitionLabels(String s) {\n        \n    List<Integer>lr=new ArrayList<>();\n\n    HashMap<Character,Boolean>mp=new HashMap<>();\n\n    int count=0;\n\n    for(int i=0;i<s.length();i++){\n\n    if(!mp.containsKey(s.charAt(i))&&s.lastIndexOf(Character.toString(s.charAt(i)))!=i){\n        mp.put(s.charAt(i),true);\n    }\n    else if(mp.containsKey(s.charAt(i))&&s.lastIndexOf(Character.toString(s.charAt(i)))==i){\n\n    mp.remove(s.charAt(i));\n\n    }\n    \n    if(mp.isEmpty()){\n    lr.add(count+1);\n    count=0;\n    }\n    else{\n        count++;\n    }\n    }\n\n\n    return lr;\n\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> partitionLabels(string s) {\n        unordered_map<char,int>mp;\n        // filling impact of character's\n        for(int i = 0; i < s.size(); i++){\n            char ch = s[i];\n            mp[ch] = i;\n        }\n        // making of result\n        vector<int> res;\n        int prev = -1;\n        int maxi = 0;\n\n        for(int i = 0; i < s.size(); i++){\n            maxi = max(maxi, mp[s[i]]);\n            if(maxi == i){\n                // partition time\n                res.push_back(maxi - prev);\n                prev = maxi;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Maximum Side Length of a Square with Sum Less than or Equal to Threshold",
        "algo_input": "Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput: 2\nExplanation: The maximum side length of square with sum less than 4 is 2 as shown.\n\n\nExample 2:\n\nInput: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 300\n\t0 &lt;= mat[i][j] &lt;= 104\n\t0 &lt;= threshold &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n        # prefix matrix\n        dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)]\n        \n        for i in range(1, len(mat)+1):\n            for j in range(1, len(mat[0])+1):\n                dp[i][j] = dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1] + mat[i-1][j-1]\n                       \n        #bin search\n        max_side = 0\n        for i in range(1, len(mat) + 1):\n            for j in range(1, len(mat[0]) + 1):\n                if min(i, j) < max_side:\n                    continue\n                left = 0\n                right = min(i,j)\n                while left <= right:\n                    mid = (left+right)//2\n                    pref_sum = dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid]\n                    if pref_sum <= threshold:\n                        max_side = max(max_side, mid)\n                        left = mid + 1\n                    else:\n                        right = mid - 1\n        return max_side\n                    ",
        "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} threshold\n * @return {number}\n */\nvar maxSideLength = function(mat, threshold) {\n    const n = mat.length, m = mat[0].length;\n    \n    // build sum matrix\n    let sum = [];\n    for(let i=0; i<=n; i++) {\n        sum.push(new Array(m+1).fill(0));\n        for(let j=0; j<=m; j++) {\n            if(i==0 || j==0) {\n                continue;\n            }\n            sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + mat[i-1][j-1];\n        }\n    }\n    \n    // function to check square sum <= threshold\n    const underThreshold = function(len) {\n        for(let i=len; i<=n; i++) {\n            for(let j=len; j<=m; j++) {\n                if(sum[i][j] - sum[i-len][j] - sum[i][j-len] + sum[i-len][j-len] <= threshold) {\n                    return true;\n                }\n            }\n        }\n        return false;\n    };\n    \n    // binary search\n    let l=0, r=Math.min(n, m);\n    while(l<=r) {\n        const mid = Math.floor((l+r)/2);\n        if(underThreshold(mid)) {\n            l = mid+1;\n        } else {\n            r = mid-1;\n        }\n    }\n    return r;\n};",
        "solution_java": "class Solution {\n    public int maxSideLength(int[][] mat, int threshold) {\n        int rows = mat.length;\n        int cols = mat[0].length;\n        int[][] preSum = new int[rows+1][cols+1];\n        for(int i=1;i<=rows;i++){\n            for(int j=1;j<=cols;j++){\n                preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + mat[i-1][j-1];\n            }\n        }\n        int lo=1,hi=Math.min(rows,cols);\n        while(lo<=hi){\n            int m = (lo+hi)>>1;\n            if(fun(preSum,threshold,rows,cols,m)) lo=m+1;\n            else hi=m-1;\n        }\n        return lo-1;\n    }\n    private boolean fun(int[][] preSum, int maxSum,int rows, int cols, int size){\n        for(int r=size;r<=rows;r++){\n            for(int c=size;c<=cols;c++){\n                int sum = preSum[r][c] - preSum[r-size][c] - preSum[r][c-size] + preSum[r-size][c-size];\n                if(sum <= maxSum) return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxSideLength(vector<vector<int>>& mat, int threshold) {\n        int m = mat.size();\n        int n = mat[0].size();\n        \n        int least = min (m,n);\n        \n        vector<vector<int>> dp (m+1, vector<int> (n+1, 0));\n        \n        /*\n        create dp matrix with sum of all squares\n        so for the following input matrix\n         1 1 1 1\n         1 0 0 0\n         1 0 0 0\n         1 0 0 0\n         \n        m = 4; n = 4; least = 4; threshold = 6\n        you get the dp matrix to be:\n         0 0 0 0 0\n         0 1 2 3 4\n         0 2 3 4 5\n         0 3 4 5 6\n         0 4 5 6 7\n        */\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                dp[i+1][j+1] = mat[i][j] + dp[i+1][j] + dp[i][j+1] - dp[i][j];\n            }\n        }\n        \n        int sum = 0;\n        \n        /*\n        from the previous example the once we start looking from least = 4 to see if the sum is less than threshold\n        for least = 4; sum = 7 - 0 - 0 + 0. (looking at the full 4 x 4 matrix) 7 is > threshold.. so keep looking..\n        for least = 3; sum = 5 - 0 - 0 + 0. (looking at the 3 x 3 matrix) .. 5 < threshold.. return 3.\n        \n        say if the threshold was lower e.g. threshold = 2?\n        continuing...\n        for least = 3; sum = 6 - 3 - 0 + 0 = 3.\n        for least = 3; sum = 6 - 0 - 3 + 0 = 3;\n        for least = 3; sum = 7 - 4 - 4 + 1 = 0;\n        \n        */\n        \n        for(int k = least; k > 0; k--) {\n            for(int i = k; i < m+1; i++) {\n                for(int j = k; j < n+1; j++) {\n                    sum = dp[i][j] - dp[i-k][j] - dp[i][j-k] + dp[i-k][j-k];\n                    if(sum <= threshold) {\n                        return k;\n                    }\n                }\n            }\n        }\n        \n        return 0;\n    }\n};"
    },
    {
        "title": "Longest Uncommon Subsequence II",
        "algo_input": "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.\n\nAn uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.\n\nA subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n\n\n\tFor example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"aebdc\" to get \"abc\". Other subsequences of \"aebdc\" include \"aebdc\", \"aeb\", and \"\" (empty string).\n\n\n&nbsp;\nExample 1:\nInput: strs = [\"aba\",\"cdc\",\"eae\"]\nOutput: 3\nExample 2:\nInput: strs = [\"aaa\",\"aaa\",\"aa\"]\nOutput: -1\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= strs.length &lt;= 50\n\t1 &lt;= strs[i].length &lt;= 10\n\tstrs[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findLUSlength(self, s: List[str]) -> int:\n        def lcs(X, Y):\n            m = len(X)\n            n = len(Y)\n            L = [[None]*(n + 1) for i in range(m + 1)]\n            for i in range(m + 1):\n                for j in range(n + 1):\n                    if i == 0 or j == 0 :\n                        L[i][j] = 0\n                    elif X[i-1] == Y[j-1]:\n                        L[i][j] = L[i-1][j-1]+1\n                    else:\n                        L[i][j] = max(L[i-1][j], L[i][j-1])\n            return L[m][n]\n            \n        k = 0 \n        mp = {}\n        for i in s:\n            if len(i) not in mp:\n                mp[len(i)] = [i]\n            else:\n                mp[len(i)].append(i)\n            k = max(k , len(i))\n        \n        t = k\n        while(k):\n            if k not in mp:\n              k -= 1\n            else:\n                curr = mp[k]\n                n = len(curr)\n                for i in range(n):\n                    f = 0\n                    for j in range(n):\n                        if(i != j and curr[i] == curr[j]):\n                            f = 1\n                            break\n                    if(not(f)):\n                        ff = 0 \n                        for j in range(k+1 , t+1):\n                            if(ff):break\n                            if(j not in mp): continue\n                            for jj in mp[j]:\n                                if(lcs(curr[i] , jj) == len(curr[i])):\n                                    ff = 1\n                                    break\n                        if(not(ff)):return len(curr[i])\n                k-=1\n                \n        return -1\n\n        \n\n        ",
        "solution_js": "var findLUSlength = function(strs) {\n\tstrs.sort((a, b) => b.length - a.length);\n\tconst isSubsequence = (a, b) => {\n\t\tconst A_LENGTH = a.length;\n\t\tconst B_LENGTH = b.length;\n\t\tif (A_LENGTH > B_LENGTH) return false;\n\t\tif (a === b) return true;\n\t\tconst matches = [...b].reduce((pos, str) => {\n\t\t\treturn a[pos] === str ? pos + 1 : pos;\n\t\t}, 0);\n\t\treturn matches === A_LENGTH;\n\t}\n\n\tfor (let a = 0; a < strs.length; a++) {\n\t\tlet isUncommon = true;\n\n\t\tfor (let b = 0; b < strs.length; b++) {\n\t\t\tif (a === b) continue;\n\t\t\tif (isSubsequence(strs[a], strs[b])) {\n\t\t\t\tisUncommon = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (isUncommon) return strs[a].length;\n\n\t}\n\treturn -1;\n};",
        "solution_java": "class Solution {\n    public int findLUSlength(String[] strs) {\n        Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length\n         // store the frequency of all strings in array\n        Map<String,Integer> map = new HashMap<>();\n        for(String s : strs) map.put(s,map.getOrDefault(s,0)+1);\n\n        for(int i=0;i<strs.length;i++){\n            if(map.get(strs[i]) != 1) continue; // string is not unique\n            int j;\n            for(j=0;j<i;j++){\n                if(isSubsequence(strs[i],strs[j])) break;\n            }\n            // if it is not a subsequence of any other larger string\n             if(j == i) return strs[i].length();\n        }\n        return -1; // no string satisfies the criterion\n    }\n    public boolean isSubsequence(String a, String b){\n        int i=0,j=0;\n        while(i<a.length() && j<b.length())\n            if(a.charAt(i) == b.charAt(j++)) i++;\n        return i == a.length();\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    bool isCommon(string &s,string &t){\n        int index=0;\n        for(int i=0;i<s.size();i++){\n            if(s[i]==t[index]){\n                if(++index==t.size()){\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n    bool isUncommon(vector<string>&strs,int index){\n        for(int i=0;i<strs.size() and strs[index].size()<=strs[i].size();i++){\n            if(index!=i and isCommon(strs[i],strs[index])){\n                return false;\n            }\n        }\n        return true;\n    }\npublic:\n    int findLUSlength(vector<string>& strs) {\n        sort(strs.begin(),strs.end(),[](string &s,string &t){\n            return s.size()>t.size();\n        });\n        int ans=-1;\n        for(int i=0;i<strs.size();i++){\n            if(isUncommon(strs,i)){\n                ans=strs[i].size();\n                break;\n            } \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Ugly Number II",
        "algo_input": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\n\nGiven an integer n, return the nth ugly number.\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 12\nExplanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1690\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def nthUglyNumber(self, n: int) -> int:\n        h1, h2, h3 = [], [], []\n        heapq.heappush(h1, 1)\n        heapq.heappush(h2, 1)\n        heapq.heappush(h3, 1)\n        ugly_number = 1\n        last_ugly_number = 1\n        count = 1\n        while count < n:\n            if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:\n                # pop from h1\n                x = heapq.heappop(h1)\n                ugly_number = 2 * x\n                if ugly_number == last_ugly_number:\n                    # do nothing\n                    continue\n                count+=1\n                last_ugly_number = ugly_number\n                heapq.heappush(h1, ugly_number)\n                heapq.heappush(h2, ugly_number)\n                heapq.heappush(h3, ugly_number)\n\n            elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:\n                # pop from h2\n                x = heapq.heappop(h2)\n                ugly_number = 3 * x\n                if ugly_number == last_ugly_number:\n                    continue\n                count+=1\n                last_ugly_number = ugly_number\n                heapq.heappush(h1, ugly_number)\n                heapq.heappush(h2, ugly_number)\n                heapq.heappush(h3, ugly_number)\n            else:\n                # pop from h3\n                x = heapq.heappop(h3)\n                ugly_number = 5 * x\n                if ugly_number == last_ugly_number:\n                    continue\n                count+=1\n                last_ugly_number = ugly_number\n                heapq.heappush(h1, ugly_number)\n                heapq.heappush(h2, ugly_number)\n                heapq.heappush(h3, ugly_number)\n\n        return last_ugly_number",
        "solution_js": "var nthUglyNumber = function(n) {\nlet uglyNo = 1;\nlet uglySet = new Set(); // Set to keep track of all the ugly Numbers to stop repetition\nuglySet.add(uglyNo);\nlet minHeap = new MinPriorityQueue(); // Javascript provides inbuilt min and max heaps, constructor does not require callback function for primitive types but a comparator callback for object data types, to know which key corresponds to the priority\n//callback looks like this new MinPriorityQueue((bid) => bid.value)\n// if this is confusing, check the documentation here\n// https://github.com/datastructures-js/priority-queue/blob/master/README.md#constructor\nwhile(n>1){\n    if(!uglySet.has(uglyNo*2)){// add only if the set does not have this ugly no.\n        minHeap.enqueue(uglyNo*2,uglyNo*2);// enqueue takes two inputs element and priority respectively, both are same here\n        uglySet.add(uglyNo*2);\n    }\n    if(!uglySet.has(uglyNo*3)){\n        minHeap.enqueue(uglyNo*3,uglyNo*3);\n        uglySet.add(uglyNo*3);\n    }\n    if(!uglySet.has(uglyNo*5)){\n        minHeap.enqueue(uglyNo*5,uglyNo*5);\n        uglySet.add(uglyNo*5);\n    }\n    uglyNo = minHeap.dequeue().element;//dequeue returns an object with two properties priority and element\n    n--;\n}\n\nreturn uglyNo;\n};",
        "solution_java": "// Ugly number II\n// https://leetcode.com/problems/ugly-number-ii/\n\nclass Solution {\n    public int nthUglyNumber(int n) {\n        int[] dp = new int[n];\n        dp[0] = 1;\n        int i2 = 0, i3 = 0, i5 = 0;\n        for (int i = 1; i < n; i++) {\n            dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5));\n            if (dp[i] == dp[i2] * 2) i2++;\n            if (dp[i] == dp[i3] * 3) i3++;\n            if (dp[i] == dp[i5] * 5) i5++;\n        }\n        return dp[n - 1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int nthUglyNumber(int n) {\n\n        int dp[n+1];\n        dp[1] = 1;\n\n        int p2 = 1, p3 = 1, p5 = 1;\n        int t;\n\n        for(int i = 2; i < n+1; i++){\n            t = min(dp[p2]*2, min(dp[p3]*3, dp[p5]*5));\n            dp[i] = t;\n\n            if(dp[i] == dp[p2]*2){\n                p2++;\n            }\n            if(dp[i] == dp[p3]*3){\n                p3++;\n            }\n            if(dp[i] == dp[p5]*5){\n                p5++;\n            }\n        }\n        return dp[n];\n\n    }\n};"
    },
    {
        "title": "Search in Rotated Sorted Array",
        "algo_input": "There is an integer array nums sorted in ascending order (with distinct values).\n\nPrior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 &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,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].\n\nGiven the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n&nbsp;\nExample 1:\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutput: 4\nExample 2:\nInput: nums = [4,5,6,7,0,1,2], target = 3\nOutput: -1\nExample 3:\nInput: nums = [1], target = 0\nOutput: -1\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t-104 &lt;= nums[i] &lt;= 104\n\tAll values of nums are unique.\n\tnums is an ascending array that is possibly rotated.\n\t-104 &lt;= target &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def search(self, nums: List[int], target: int) -> int:\n        l, r = 0, len(nums) - 1\n        \n        while l<=r:\n            mid = (l+r)//2\n            if target == nums[mid]:\n                return mid\n            \n            if nums[l]<=nums[mid]:\n                if target > nums[mid] or target<nums[l]:\n                    l = mid + 1\n                else:\n                    r = mid - 1\n            \n            else:\n                if target < nums[mid] or target > nums[r]:\n                    r = mid - 1\n                else:\n                    l = mid + 1\n        \n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n    const len = nums.length;\n    if (len === 1 && nums[0] === target) return 0;\n    const h = nums.findIndex((val, i) => nums[i === 0 ? nums.length - 1 : i - 1] > val);\n    if (h !== 0) nums = nums.slice(h).concat(nums.slice(0, h));\n    // console.log(h, nums)\n    let lo = 0, hi = len - 1;\n    while (lo !== hi) {\n        if (lo + 1 === hi) {\n            if (nums[lo] === target) return (lo + h) % len;\n            if (nums[hi] === target) return (hi + h) % len;\n            break;\n        }\n\n        const i = Math.floor((lo + hi + 1) / 2);\n        // console.log(lo, hi, i)\n        const val = nums[i];\n        if (val === target) return (i + h) % len;\n        if (val > target) hi = i;\n        else lo = i;\n    }\n\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int search(int[] nums, int target) {\n        int pivot = findPivot(nums);\n        int ans = binarySearch(nums, target, 0, pivot);\n        if(ans!=-1){\n            return ans;\n        }\n        return binarySearch(nums, target, pivot+1, nums.length-1);\n    }\n    \n    public int findPivot(int[] arr){\n        int start = 0, end = arr.length-1;\n        while(start<=end){\n            int mid = start + (end-start)/2;\n            if(mid<end && arr[mid]>arr[mid+1]){\n                return mid;\n            }\n            if(mid>start && arr[mid-1]>arr[mid]){\n                return mid-1;\n            }\n            if(arr[mid]<=arr[start]){\n                end = mid-1;\n            }else{\n                start = mid+1;\n            }\n        }\n        return -1;\n    }\n    \n    public int binarySearch(int[] arr, int target, int start, int end){\n        \n        while(start<=end){\n            int mid = start+ (end-start)/2;\n            \n            \n                if(target<arr[mid]){\n                    end = mid-1;\n                }else if(target>arr[mid]){\n                    start = mid+1;\n                }else{\n                    return mid;\n                }\n            \n            \n        }\n        return -1;\n    }\n    \n}",
        "solution_c": "class Solution \n{\npublic:\n    int search(vector<int>& nums, int target) \n    {\n        int n=nums.size()-1;\n        if(nums[0]==target)\n            return 0;\n        if(nums.size()==1)\n           return -1; \n        // find the index of the minimum element ie pivot\n        int pivot=-1;\n        int low=0;\n        int high=n;\n        while(low<=high)\n        {\n            int mid=(low+high)/2;\n            if(mid==0)\n            {\n                if(nums[mid]< nums[mid+1] && nums[mid]< nums[n])\n                {\n                    pivot=mid;\n                    break;\n                }\n                else\n                {\n                    low=mid+1;\n                }\n            }\n            \n            else if(mid==n)\n            {\n                if(nums[mid] < nums[0] && nums[mid] < nums[mid-1])\n                {\n                    pivot=mid;\n                    break;\n                }\n                else \n                {\n                    high=mid-1;\n                }\n            }\n            else if(nums[mid]<nums[mid+1] && nums[mid]<nums[mid-1])\n            {\n                pivot=mid;\n                break;\n            }\n            else if(nums[mid]>=nums[0] && nums[mid]<=nums[n])\n                high=mid-1;\n            else if(nums[mid] >= nums[0])\n                low=mid+1;\n            else if(nums[mid] < nums[0])\n                high=mid-1;\n        }\n        cout<<pivot<<endl;\n        if(target < nums[0])\n        {\n            int low1=pivot;\n            int high1=n;\n            while(low1<=high1)\n            {\n                int mid1=(low1+high1)/2;\n                if(nums[mid1]==target)\n                    return mid1;\n                else if(nums[mid1] > target)\n                    high1=mid1-1;\n                else if(nums[mid1]<target)\n                    low1=mid1+1;\n            }\n            \n        }\n        if(target > nums[0])\n        {\n            int low2=0;\n            int high2=pivot-1;\n            if(pivot==0)\n            {\n                low2=0;\n                high2=n;\n            }\n            while(low2<=high2)\n            {\n                int mid2=(low2+high2)/2;\n                if(nums[mid2]==target)\n                    return mid2;\n                else if(nums[mid2] > target)\n                    high2=mid2-1;\n                else if(nums[mid2]<target)\n                    low2=mid2+1;\n            }\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "String to Integer (atoi)",
        "algo_input": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).\n\nThe algorithm for myAtoi(string s) is as follows:\n\n\n\tRead in and ignore any leading whitespace.\n\tCheck if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.\n\tRead in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.\n\tConvert these digits into an integer (i.e. \"123\" -&gt; 123, \"0032\" -&gt; 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).\n\tIf the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.\n\tReturn the integer as the final result.\n\n\nNote:\n\n\n\tOnly the space character ' ' is considered a whitespace character.\n\tDo not ignore any characters other than the leading whitespace or the rest of the string after the digits.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"42\"\nOutput: 42\nExplanation: The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n         ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n         ^\nStep 3: \"42\" (\"42\" is read in)\n           ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231 - 1], the final result is 42.\n\n\nExample 2:\n\nInput: s = \"   -42\"\nOutput: -42\nExplanation:\nStep 1: \"   -42\" (leading whitespace is read and ignored)\n            ^\nStep 2: \"   -42\" ('-' is read, so the result should be negative)\n             ^\nStep 3: \"   -42\" (\"42\" is read in)\n               ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231 - 1], the final result is -42.\n\n\nExample 3:\n\nInput: s = \"4193 with words\"\nOutput: 4193\nExplanation:\nStep 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n         ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n         ^\nStep 3: \"4193 with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n             ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231 - 1], the final result is 4193.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 200\n\ts consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.\n\n",
        "solution_py": "class Solution:\n\n    def assign_sign(self, sign):\n      # verify that we haven't already got a sign\n      #&nbsp;\"+42-\" -> we don't want to return -42; hence check\n      if not self.is_neg and not self.is_pos:\n          # no sign has been set yet\n        if sign==\"+\":\n          self.is_pos = True\n        elif sign==\"-\":\n          self.is_neg = True\n      return\n\n    def add_to_int(self, num):\n      if not self.num:\n        self.num = num\n      else:\n        self.num = (self.num*10) + num\n\n    def myAtoi(self, s: str) -> int:\n        #&nbsp;remove the leading and trailing spaces\n        self.is_neg = False\n        self.is_pos = False\n        self.num = None\n        s=s.strip()\n        for i in s:\n          # ignore the rest of the string if a non digit character is read\n          if i in (\"+\",\"-\"):\n            #&nbsp;only read the first symbol; break if second symbol is read\n            if self.is_pos or self.is_neg or isinstance(self.num, int):\n              #&nbsp;one of the two symbols is read or a number is read\n              break\n            self.assign_sign(i)\n            continue\n          try:\n            i = int(i)\n            self.add_to_int(i)\n          except ValueError:\n            # it's neither a sign, nor a number; terminate\n            break\n\n        # outside the loop; compile the result\n        if not self.num:\n          return 0\n        upper_limit = 2**31 - 1\n        if self.is_pos or (not self.is_pos and not self.is_neg):\n          if self.num > upper_limit:\n            self.num = upper_limit\n        elif self.is_neg:\n          if self.num > upper_limit+1:\n            self.num = upper_limit+1\n          self.num = -1 * self.num\n        return self.num",
        "solution_js": "const toNumber = (s) => {\n    let res = 0;\n    for (let i = 0; i < s.length; i++) {\n        res = res * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));\n    }\n    \n    return res\n}\n\nvar myAtoi = function(s) {\n    s = s.trim();\n    let r = s.match(/^(\\d+|[+-]\\d+)/);\n    \n    if (r) {\n        let m = r[0], res;\n        switch (m[0]) {\n            case \"-\":\n                res = toNumber(m.slice(1)) * -1;\n                break;\n            case '+':\n                res = toNumber(m.slice(1));\n                break;\n            default:\n                res = toNumber(m);\n                break;\n        }\n        \n        if (res < (1 << 31)) return (1 << 31);\n        if (res > -(1 << 31) - 1) return -(1 << 31) - 1;\n        return res;\n    }\n    \n    return 0;\n};",
        "solution_java": "class Solution {\n    public int myAtoi(String s) {\n        long n=0;\n        int i=0,a=0;\n        s=s.trim();\n        if(s.length()==0)\n            return 0;\n        if(s.charAt(i)=='+' || s.charAt(i)=='-')\n            a=1;\n        while(a<s.length())\n            if(s.charAt(a)=='0')\n                a++;\n            else \n                break;\n        for(i=a;i<a+11 && i<s.length();i++)\n        {\n            if(s.charAt(i)>='0' && s.charAt(i)<='9')\n                n=n*10+(int)(s.charAt(i)-'0');\n            else\n                break;\n        }\n        if(s.charAt(0)=='-')\n            n=-n;\n        if(n>2147483647)\n            n=2147483647;\n        if(n<-2147483648)\n            n=-2147483648;\n        return (int)n;\n    }\n}",
        "solution_c": "class Solution\n{\n    public:\n        int myAtoi(string s)\n        {\n            long long ans = 0;\n            int neg = 1;\n            int i = 0;\n            while (i < s.length() and s[i] == ' ')\n            {\n                i++;\n            }\n\n            if (s[i] == '-' || s[i] == '+')\n            {\n                neg = s[i] == '-' ? -1 : 1;\n                i++;\n            }\n\n            while (i < s.length() && (s[i] >= '0' && s[i] <= '9'))\n            {\n\n                ans = ans *10 + (s[i] - '0');\n               \t// ans *= 10;\n                i++;\n                if (ans * neg >= INT_MAX) return INT_MAX;\n                if (ans * neg <= INT_MIN) return INT_MIN;\n            }\n            return ans * neg;\n        }\n};"
    },
    {
        "title": "Jump Game",
        "algo_input": "You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.\n\nReturn true if you can reach the last index, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,1,1,4]\nOutput: true\nExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\nInput: nums = [3,2,1,0,4]\nOutput: false\nExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def canJump(self, nums: List[int]) -> bool:\n        \"\"\"\n        # Memoization + DFS Solution\n        # TLE as we have as much as n decisions depending on nums[i] which could be\n        # 10^5 as an uppercase according to problem constraints\n        # better off with a greedy approach\n\n        cache = {} # i : bool\n\n        def dfs(i):\n            if i == len(nums) -1:\n                return True\n            if nums[i] == 0:\n                return False\n            if i in cache:\n                return cache[i]\n            for j in range(1, nums[i] + 1):\n                res = dfs(i + j)\n                if res:\n                    cache[i] = True\n                    return cache[i]\n            cache[i] = False\n            return cache[i]\n\n        return dfs(0)\n        \"\"\"\n        # Greedy Solution\n        # Key with greedy is to find a local and gobal optimum\n        # here we find the furthest distance we can travel with each index\n\n        # futhest index reachable\n        reachable = 0\n\n        # iterate through all indexes and if the current index is futher than what we can travel return fasle\n        for i in range(len(nums)):\n            if i > reachable:\n                return False\n\n            reachable = max(reachable, nums[i] + i)\n            # if the futherest distance we can jump to is greater or equal than the last index break\n            if reachable >= len(nums) - 1:\n                break\n\n        return True",
        "solution_js": "var canJump = function(nums) {\n    let target = nums.length-1;\n    let max = 0,index = 0;\n\n    while(index <= target){\n        max = Math.max(max,index + nums[index]);\n\n        if(max >= target) return true;\n\n        if(index >= max && nums[index] === 0) return false;\n\n        index++;\n    }\n\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean canJump(int[] nums)\n    {\n        int maxjump = 0;\n        for(int i=0;i<nums.length;i++)\n        {\n            // If the current index 'i' is less than current maximum jump 'curr'. It means there is no way to jump to current index...\n            // so we should return false\n            if(maxjump<i)\n                return false;\n            else\n                maxjump = Math.max(maxjump,nums[i]+i); // Update the current maximum jump...\n        }\n        return true;\n    }\n}\n\n//nums[i]+1 gives themax jump index possible from i",
        "solution_c": "class Solution {\npublic:\n    bool canJump(vector<int>& nums) {\n        int ans = nums[0];\n        if(nums.size()>1&&ans==0) return false;\n        for(int i=1; i<nums.size(); i++){\n            ans = max(ans-1,nums[i]);\n            if(ans<=0&&i!=nums.size()-1) return false;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Combination Sum II",
        "algo_input": "Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates&nbsp;where the candidate numbers sum to target.\n\nEach number in candidates&nbsp;may only be used once in the combination.\n\nNote:&nbsp;The solution set must not contain duplicate combinations.\n\n&nbsp;\nExample 1:\n\nInput: candidates = [10,1,2,7,6,1,5], target = 8\nOutput: \n[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]\n\n\nExample 2:\n\nInput: candidates = [2,5,2,1,2], target = 5\nOutput: \n[\n[1,2,2],\n[5]\n]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;candidates.length &lt;= 100\n\t1 &lt;=&nbsp;candidates[i] &lt;= 50\n\t1 &lt;= target &lt;= 30\n\n",
        "solution_py": "class Solution(object):\n    def combinationSum2(self, candidates, target):\n        res = []\n        def dfs(nums,summ,curr):\n            if summ>=target:\n                if summ == target:\n                    res.append(curr)\n                return\n            for i in range(len(nums)):\n                if i !=0 and nums[i]==nums[i-1]:\n                    continue\n                dfs(nums[i+1:],summ+nums[i],curr+[nums[i]])\n        dfs(sorted(candidates),0,[])\n        return res",
        "solution_js": "/**\n * @param {number[]} candidates\n * @param {number} target\n * @return {number[][]}\n */\nvar combinationSum2 = function(candidates, target) {\n    candidates.sort((a, b) => a - b);\n    \n    const ans = [];\n    \n    function dfs(idx, t, st) {\n        if (t === 0) {\n            ans.push(Array.from(st));\n            return;\n        }\n        for (let i = idx; i < candidates.length; i++) {\n            if (i > idx && candidates[i - 1] === candidates[i]) continue;\n            if (candidates[i] > t) break;\n            st.push(candidates[i]);\n            dfs(i + 1, t - candidates[i], st);\n            st.pop();\n        }\n    }\n    \n    dfs(0, target, []);\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> combinationSum2(int[] candidates, int target) {\n        List<List<Integer>> res = new ArrayList<>();\n        List<Integer> path = new ArrayList<>();\n        // O(nlogn)\n        Arrays.sort(candidates);\n        boolean[] visited = new boolean[candidates.length];\n        helper(res, path, candidates, visited, target, 0);\n        return res;\n    }\n    private void helper(List<List<Integer>> res,\n                  List<Integer> path, int[] candidates,\n                  boolean[] visited, int remain, int currIndex\n                 ){\n        if (remain == 0){\n            res.add(new ArrayList<>(path));\n            return;\n        }\n        if (remain < 0){\n            return;\n        }\n\n        for(int i = currIndex; i < candidates.length; i++){\n            if (visited[i]){\n                continue;\n            }\n            if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){\n                continue;\n            }\n            int curr = candidates[i];\n            path.add(curr);\n            visited[i] = true;\n            helper(res, path, candidates, visited, remain - curr, i + 1);\n            path.remove(path.size() - 1);\n\n            visited[i] = false;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> ans;vector<int> temp;\n    void f(vector<int>& nums,int target,int i){\n        if(target==0){\n            ans.push_back(temp);\n            return;\n        }\n        if(i>=nums.size())\n            return;\n        if(nums[i]<=target){\n            temp.push_back(nums[i]);\n            f(nums,target-nums[i],i+1);\n            temp.pop_back();\n            while(i<nums.size()-1 && nums[i]==nums[i+1]) i++;\n            f(nums,target,i+1);\n        }\n        else\n            f(nums,target,i+1);\n    }\n    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {\n        sort(candidates.begin(),candidates.end());\n        f(candidates,target,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Constrained Subsequence Sum",
        "algo_input": "Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i &lt; j, the condition j - i &lt;= k is satisfied.\n\nA subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\n\nExample 2:\n\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\n\nExample 3:\n\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n        deque = []\n        for i, num in enumerate(nums):\n                \n            while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i]\n                deque.pop(0)\n                \n            if deque:  # compute the max sum we can get at index i\n                nums[i] = nums[deque[0]] + num\n            \n            while(deque and nums[deque[-1]] < nums[i]): \n                # delet all the sequence that smaller than current sum, becaus there will never be\n                # considers ==> smaller than current sequence, and end before current sequence\n                deque.pop()\n                \n            if nums[i] > 0: # if nums[i] < 0, it can't be a useful prefix sum    \n            \tdeque.append(i)\n        \n        return max(nums)",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar constrainedSubsetSum = function(nums, k) {\n    const queue = [[0, nums[0]]];\n    let max = nums[0];\n    for (let i = 1; i < nums.length; i++) {\n        const cur = queue.length ? nums[i] + Math.max(0, queue[0][1]) : nums[i];\n        max = Math.max(max, cur);\n        while(queue.length && queue[queue.length-1][1] < cur) queue.pop();\n        queue.push([i, cur]);\n        while(queue.length && queue[0][0] <= i-k) queue.shift();\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int constrainedSubsetSum(int[] nums, int k) {\n        int n=nums.length;\n        int[] dp=new int[n];\n        int res=nums[0];\n        Queue<Integer> queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap\n\n        Arrays.fill(dp,Integer.MIN_VALUE);\n        dp[0]=nums[0];\n        queue.offer(0);\n\n        for(int j=1;j<n;j++){\n            int i=Math.max(j-k,0); // get the furthest index possible\n            while(!queue.isEmpty() && queue.peek()<i) queue.poll(); // find the global max in the specified range for that particular j index\n            int idx=queue.peek();\n            dp[j]=Math.max(dp[idx]+nums[j],nums[j]);\n            res=Math.max(res,dp[j]);\n            queue.offer(j);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int constrainedSubsetSum(vector<int>& nums, int k) {\n        priority_queue<array<int, 2>> que;\n        int ret = nums[0], curr;\n        que.push({nums[0], 0});\n        for (int i = 1; i < nums.size(); i++) {\n            while (!que.empty() && que.top()[1] < i - k) {\n                que.pop();\n            }\n            curr = max(0, que.top()[0]) + nums[i];\n            ret = max(ret, curr);\n            que.push({curr, i});\n        }\n        return ret;\n    }\n};"
    },
    {
        "title": "Minimum Distance to the Target Element",
        "algo_input": "Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that&nbsp;abs(x)&nbsp;is the absolute value of x.\n\nReturn abs(i - start).\n\nIt is guaranteed that target exists in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4,5], target = 5, start = 3\nOutput: 1\nExplanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n\n\nExample 2:\n\nInput: nums = [1], target = 1, start = 0\nOutput: 0\nExplanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\n\n\nExample 3:\n\nInput: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput: 0\nExplanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 104\n\t0 &lt;= start &lt; nums.length\n\ttarget is in nums.\n\n",
        "solution_py": "class Solution:\n    def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n        if nums[start] == target: return 0\n        left, right = start-1, start+1\n        N = len(nums)\n        while True:\n            if left >=0 and nums[left] == target:\n                return start - left\n            if right < N and nums[right] == target:\n                return right - start\n            left -= 1\n            right += 1",
        "solution_js": "var getMinDistance = function(nums, target, start) {\n    let min = Infinity;\n    for(let i=nums.indexOf(target);i<nums.length;i++){\n        if(nums[i]===target){\n            if(Math.abs(i-start)<min) min = Math.abs(i-start);\n        }\n    }\n    return min;\n};",
        "solution_java": "class Solution {\n    public int getMinDistance(int[] nums, int target, int start) {\n        int ans = Integer.MAX_VALUE;\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] == target) {\n                ans = Math.min(ans, Math.abs(i - start));\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution{\npublic:\n    int getMinDistance(vector<int>& nums, int target, int start){\n        int ans = INT_MAX;\n        for(int i = 0; i < nums.size(); i++){\n            int temp = 0;\n            if (nums[i] == target){\n                temp = abs(i - start);\n                if (temp < ans){\n                    ans = temp;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Boomerangs",
        "algo_input": "You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).\n\nReturn the number of boomerangs.\n\n&nbsp;\nExample 1:\n\nInput: points = [[0,0],[1,0],[2,0]]\nOutput: 2\nExplanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\n\n\nExample 2:\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 2\n\n\nExample 3:\n\nInput: points = [[1,1]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tn == points.length\n\t1 &lt;= n &lt;= 500\n\tpoints[i].length == 2\n\t-104 &lt;= xi, yi &lt;= 104\n\tAll the points are unique.\n\n",
        "solution_py": "class Solution:\n    def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n        def sq(a):\n            return a * a\n\n        def euclid(a, b, c, d):\n            dist = sq(a - c) + sq(b - d)\n            return sq(dist)\n\n        n = len(points)\n        res = 0\n        for i in range(n):\n            count = defaultdict(lambda : 0)\n            for j in range(n):\n                d = euclid(points[i][0], points[i][1], points[j][0], points[j][1])\n                res += count[d] * 2\n                count[d] += 1\n\n        return res",
        "solution_js": "var numberOfBoomerangs = function(points) {\n\tconst POINTS_LEN = points.length;\n\tlet result = 0;\n\n\tfor (let i = 0; i < POINTS_LEN; i++) {\n\t\tconst hash = new Map();\n\n\t\tfor (let j = 0; j < POINTS_LEN; j++) {\n\t\t\tif (i === j) continue;\n\t\t\tconst [x1, y1] = points[i];\n\t\t\tconst [x2, y2] = points[j];\n\t\t\tconst dis = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);\n\t\t\tconst value = hash.get(dis) ?? 0;\n\n\t\t\tif (value > 0) result += value * 2;\n\t\t\thash.set(dis, value + 1);\n\t\t}\n\t}\n\n\treturn result;\n};",
        "solution_java": "class Solution {\n    public int numberOfBoomerangs(int[][] points) {\n        \n        int answer = 0;\n        \n        for (int p=0; p<points.length;p++) {\n            \n            int[] i = points[p];\n            \n            HashMap<Double, Integer> hm = new HashMap<Double, Integer>();\n            \n            for (int q=0;q<points.length;q++) {\n                \n                if (q==p) {\n                    continue;\n                }\n                \n                int[] j = points[q];\n                \n                double distance = Math.sqrt(Math.pow(j[0]-i[0], 2) + Math.pow(j[1]-i[1], 2));\n                \n                if (distance > 0) {\n                    if (hm.containsKey(distance)) {\n                        hm.put(distance, hm.get(distance) + 1);\n                    } else {\n                        hm.put(distance, 1);\n                    }\n                }\n                \n            }\n            \n            for (Double dist : hm.keySet()) {\n                int occ = hm.get(dist);\n                if (occ > 1) {\n                    answer = answer + ((occ) * (occ - 1));\n                }\n            }\n        }\n        \n        return answer;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfBoomerangs(vector<vector<int>>& points) {\n\n        int cnt = 0, n = points.size();\n        for(int i = 0; i < n; i++)\n        {\n            map<int, int> mp;\n            for(int j = 0; j < n; j++)\n            {\n                if(i == j)\n                    continue;\n\n                int tmp = findDistance(points[i], points[j]);\n                if(mp.find(tmp) != mp.end())\n                    cnt += mp[tmp] * 2; // 2 is multiplied bcoz the order of j & k can be k & j also\n\n                mp[tmp]++;\n            }\n        }\n\n        return cnt;\n    }\n\n    int findDistance(vector<int> &p1, vector<int> &p2)\n    {\n        return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);\n    }\n};"
    },
    {
        "title": "Sum of Distances in Tree",
        "algo_input": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n\nYou are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\n\nReturn an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput: [8,12,6,10,10,10]\nExplanation: The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.\n\n\nExample 2:\n\nInput: n = 1, edges = []\nOutput: [0]\n\n\nExample 3:\n\nInput: n = 2, edges = [[1,0]]\nOutput: [1,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 3 * 104\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tThe given input represents a valid tree.\n\n",
        "solution_py": "from typing import List\n\nROOT_PARENT = -1\n\nclass Solution:\n    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n        \"\"\"\n        @see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N)\n        :param n:\n        :param edges:\n        :return:\n        \"\"\"\n        g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree\n\n        root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)\n\n        # considering \"root\" as starting node, we create a tree.\n        # Now defining,\n        # tree_nodes[i] = number of nodes in the tree rooted at node i\n        # distances[i] = sum of distances of all nodes from ith node to all the\n        # other nodes of the tree\n        tree_nodes, distances = [0] * n, [0] * n\n\n        def postorder(rt: int, parent: int):\n            \"\"\"\n            updating tree_nodes and distances from children of rt. To update them, we must know their\n            values at children. And that is why post order traversal is used\n\n            After the traversal is done,\n                tree_nodes[rt] = all the nodes in tree rooted at rt\n                distances[rt] = sum of distances from rt to all the nodes of tree rooted at rt\n\n            :param rt:\n            :param parent:\n            \"\"\"\n            tree_nodes[rt] = 1\n\n            for c in g[rt]:\n                if c != parent:\n                    postorder(c, rt)\n\n                    # adding number of nodes in subtree rooted at c to tree rooted at rt\n                    tree_nodes[rt] += tree_nodes[c]\n\n                    # moving to rt from c will increase distances by nodes in tree rooted at c\n                    distances[rt] += distances[c] + tree_nodes[c]\n\n        def preorder(rt: int, parent: int):\n            \"\"\"\n            we start with \"root\" and update its children.\n            distances[root] = sum of distances between root and all the other nodes in tree.\n\n            In this function, we calculate distances[c] with the help of distances[root] and\n            that is why preorder traversal is required.\n            :param rt:\n            :param parent:\n            :return:\n            \"\"\"\n            for c in g[rt]:\n                if c != parent:\n                    distances[c] = (\n                            (n - tree_nodes[c]) # rt -> c increase this much distance\n                            +\n                            (distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance\n                    )\n                    preorder(c, rt)\n\n        postorder(root, ROOT_PARENT)\n        preorder(root, ROOT_PARENT)\n\n        return distances\n\n    @staticmethod\n    def create_undirected_graph(edges: List[List[int]], n: int):\n        \"\"\"\n        :param edges:\n        :param n:\n        :return: graph from edges. Note that this undirect graph is a tree. (Any node can be\n                 picked as root node)\n        \"\"\"\n        g = [[] for _ in range(n)]\n\n        for u, v in edges:\n            g[u].append(v)\n            g[v].append(u)\n\n        return g",
        "solution_js": "var sumOfDistancesInTree = function(n, edges) {\n    let graph = {};\n    for (let [start, end] of edges) {\n        if (!graph[start]) graph[start] = [];\n        if (!graph[end]) graph[end] = [];\n        graph[start].push(end);\n        graph[end].push(start);\n    }\n    \n    let visited = new Set(), distanceFromZero = 0, totalChildren = {};\n    // Find the sum distance from node O to all other nodes and the total children of each node\n    function dfs(node, sum = 0) {\n        visited.add(node);\n        distanceFromZero += sum;\n        if (!graph[node]) return;\n        let child = 0;\n        for (let nextNode of graph[node]) {\n            if (visited.has(nextNode)) continue;\n            child += dfs(nextNode, sum + 1);\n        }\n        totalChildren[node] = child;\n        return child + 1;\n    }\n    dfs(0);\n\n    let dp = [distanceFromZero];\n    visited = new Set();\n    function findDistance(node) {\n        visited.add(node);\n        if (!graph[node]) return;\n        for (let nextNode of graph[node]) {\n            if (visited.has(nextNode)) {\n                dp[node] = dp[nextNode] + (n - 2);\n                break;\n            }\n        }\n        if (node !== 0 && totalChildren[node]) dp[node] -= totalChildren[node] * 2;\n        for (let nextNode of graph[node]) {\n            if (visited.has(nextNode)) continue;\n            else findDistance(nextNode);\n        }\n    }\n\n    findDistance(0);\n    return dp;\n};",
        "solution_java": "class Solution {\n    private Map<Integer, List<Integer>> getGraph(int[][] edges) {\n        Map<Integer, List<Integer>> graph = new HashMap<>();\n        for(int[] edge: edges) {\n            graph.putIfAbsent(edge[0], new LinkedList<>());\n            graph.putIfAbsent(edge[1], new LinkedList<>());\n            \n            graph.get(edge[0]).add(edge[1]);\n            graph.get(edge[1]).add(edge[0]);       \n        }\n        \n        return graph;\n    }\n    \n    public int[] sumOfDistancesInTree(int n, int[][] edges) {     \n        if(n < 2 || edges == null) {\n            return new int[]{0};\n        }\n        \n        int[] countSubNodes = new int[n];\n        Arrays.fill(countSubNodes, 1);\n        int[] distances = new int[n];\n        Map<Integer, List<Integer>> graph = getGraph(edges);\n        postOrderTraversal(0, -1, countSubNodes, distances, graph);\n        preOrderTraversal(0, -1, countSubNodes, distances, graph, n);\n        return distances;\n    }\n    \n    private void postOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map<Integer, List<Integer>> graph) {\n        List<Integer> children = graph.get(node);\n        for(int child: children) {\n            if(child != parent) {\n                postOrderTraversal(child, node, countSubNodes, distances, graph);\n                countSubNodes[node] += countSubNodes[child];\n                distances[node] += distances[child] + countSubNodes[child];\n            }\n        }\n    }\n    \n    private void preOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map<Integer, List<Integer>> graph, int n) {\n        List<Integer> children = graph.get(node);\n        for(int child: children) {\n            if(child != parent) {\n\t\t\t\tdistances[child] = distances[node] + (n - countSubNodes[child]) - countSubNodes[child];\n\t\t\t\tpreOrderTraversal(child, node, countSubNodes, distances, graph, n);            \n            }\n        }\n    }\n}``",
        "solution_c": "/*\n    \n    Finding sum of distance from ith node to all other nodes takes O(n), so it will take O(n^2)\n    if done naively to find distance for all.\n    \n            x---------------------y\n          /  \\                    \\\n         o    o                    o\n        /                         / \\  \n       o                         o   o\n       \n      Above is a graph where x and y are subtrees with them as the root. They both are neighbors\n      and are connected by an edge.\n      \n      From x's POV\n             x\n          /  |   \\                    \n         o    o   y                  \n        /          \\                    \n       o            o                \n                  /  \\\n                 o    o\n                 \n    From y's POV\n                 y                  \n               /    \\                    \n              x      o                \n            /  |    /  \\\n           o   o   o    o\n          /\n         o \n         \n    As evident froma above, the tree structure looks different when we change the root of tree.\n    So even if we find the sum of distance for node 0 as root, the subanswers are actually not correct\n    for other nodes when they are the root of tree. The subanswers are only correct when node 0 is root,\n    since that is how it was computed.\n    \n    We use something called re-rooting, this allows us to find a relation so that we can change the root of the tree\n    and use the answer from its neighbor to compute answer for it.\n    So if we compute the answer for node 0 as root, we can find the answers for its children, then those children can \n    be used to compute for their neighbors and so on.\n    \n    For the 1st diagram:\n    distance[x] = sum(x) + sum(y) + count(y)\n    \n    distance[x] is the overall sum of distance with root as x\n    sum(i) is the sum of distance of all the descendents for a subtree rooted at i\n    count(i) is the no. of descendent nodes in the subtree rooted at i\n    \n    Now why count(y) ?\n    Consider a node z in subtree y, dist(x, z) = dist(y, z) + 1\n    So sum(y) already accounts for dist(y, z) and we just need to add 1\n    So if there are n_y nodes in the subtree, we need to add +1 that many times.\n    \n    distance[x] = sum(x) + sum(y) + count(y) -----------------1\n    distance[y] = sum(y) + sum(x) + count(x) -----------------2\n    \n    From (1) - (2)\n    distance[x] - distance[y] = count(y) - count(x) ----------3\n    distance[x] = distance[y] - count(x) + count(y)\n    \n    Above relation can be used to find the answer for a neighbor, when the answer for\n    the other neighbor is known.\n    \n    In our case, we can compute the answer for node 0 as root in one traversal of post order.\n    Then in another traversal with again root as 0, compute the answer for its children and from\n    them to their children nodes and so on.\n    \n    distance[child] = distance[parent] - count(child) + (N - count(child))\n    Since we also know the no. of nodes in subtree with child as root, the remaining nodes = (N - count(child))\n    \n    \n    Re-rooting Ref: https://leetcode.com/problems/sum-of-distances-in-tree/solution/\n    \n    TC: O(N)\n    SC: O(N)\n*/\nclass Solution {\nprivate:\n    int n = 0;\n    // subtree_distance[i] = Sum of distance to other nodes when the ith-node is root\n    vector<int> subtree_distance;\n    // subtree_count[i] = no. of nodes in the subtree with ith-node as root\n    vector<int> subtree_count;\npublic:\n    void postorder(int root, int parent, vector<vector<int>>& graph) {\n        // Perform DFS for the child nodes\n        for(auto child: graph[root]) {\n            // Avoid iterating to the parent, it will create a loop otherwise\n            if(child != parent) {\n                postorder(child, root, graph);\n                // Update the subtree count and sum of distance\n                subtree_count[root] += subtree_count[child];\n                // distance[X] = distance[X] + distance[Y] + n_Y\n                subtree_distance[root] += subtree_distance[child] + subtree_count[child];\n            }\n        }\n    }\n    \n    void preorder(int root, int parent, vector<vector<int>>& graph) {\n        for(auto child: graph[root]) {\n            if(child != parent) {\n                // distance[child] = distance[parent] - count[child] + count(parent)\n                subtree_distance[child] = subtree_distance[root] - subtree_count[child] + (n - subtree_count[child]);\n                preorder(child, root, graph);\n            }\n        }\n    }\n    \n    vector<int> reRootingSol(int n, vector<vector<int>>& edges) {\n        // create an undirected graph\n        vector<vector<int> > graph(n);\n        for(auto edge: edges) {\n            int src = edge[0], dst = edge[1];\n            graph[src].emplace_back(dst);\n            graph[dst].emplace_back(src);\n        }\n        \n        this->n = n;\n        this->subtree_count.resize(n, 1);\n        this->subtree_distance.resize(n, 0);\n        \n        // This computes the subtree sum and subtree node count when 0 is the root of graph\n        // Imagine looking at the graph from node 0's POV\n        postorder(0, -1, graph);\n        // Since we have computed the sum distance from node's POV, we can use that information\n        // to find the sum of distance from each node's POV i.e imagine looking at the graph from\n        // POV of each node\n        preorder(0, -1, graph);\n        return this->subtree_distance;\n    }\n    \n    vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {\n        return reRootingSol(n, edges);\n    }\n};"
    },
    {
        "title": "Number of Orders in the Backlog",
        "algo_input": "You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:\n\n\n\t0 if it is a batch of buy orders, or\n\t1 if it is a batch of sell orders.\n\n\nNote that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.\n\nThere is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:\n\n\n\tIf the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.\n\tVice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.\n\n\nReturn the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\nOutput: 6\nExplanation: Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.\n\n\nExample 2:\n\nInput: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\nOutput: 999999984\nExplanation: Here is what happens with the orders:\n- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= orders.length &lt;= 105\n\torders[i].length == 3\n\t1 &lt;= pricei, amounti &lt;= 109\n\torderTypei is either 0 or 1.\n",
        "solution_py": "class Solution:\n    def getNumberOfBacklogOrders(self, orders):\n        b, s = [], []\n        heapq.heapify(b)\n        heapq.heapify(s)\n        \n        for p,a,o in orders:\n            if o == 0:\n                heapq.heappush(b, [-p, a])\n                \n            elif o == 1:\n                heapq.heappush(s, [p, a])\n            \n            # Check \"good\" condition\n            while s and b and s[0][0] <= -b[0][0]:\n                a1, a2 = b[0][1], s[0][1]\n                \n                if a1 > a2:\n                    b[0][1] -= a2\n                    heapq.heappop(s)\n                elif a1 < a2:\n                    s[0][1] -= a1\n                    heapq.heappop(b)\n                else:\n                    heapq.heappop(b)\n                    heapq.heappop(s)\n                    \n        count = sum([a for p,a in b]) + sum([a for p,a in s])\n        return count % (10**9 + 7)",
        "solution_js": "var getNumberOfBacklogOrders = function(orders) {\n    const buyHeap = new Heap((child, parent) => child.price > parent.price)\n    const sellHeap = new Heap((child, parent) => child.price < parent.price)\n    \n    for (let [price, amount, orderType] of orders) {\n        \n        // sell\n        if (orderType) {\n            \n            // while there are amount to be decremented from the sell,\n            // orders to in the buy backlog, and the price of the largest\n            // price is greater than the sell price decrement the\n            // amount of the order with the largest price by the amount\n            while (amount > 0 && buyHeap.peak() && buyHeap.peak().price >= price) {\n                if (buyHeap.peak().amount > amount) {\n                    buyHeap.peak().amount -= amount\n                    amount = 0\n                } else {\n                    amount -= buyHeap.pop().amount\n                }\n            }\n            \n            // if there is any amount left, add it to the sale backlog\n            if (amount) {\n                sellHeap.push({ price, amount })\n            }\n\n        // buy\n        } else {\n            \n            // while there are amount to be decremented from the buy,\n            // orders to in the sell backlog, and the price of the smallest\n            // price is less than the buy price decrement the\n            // amount of the order with the smallest price by the amount\n            while (amount > 0 && sellHeap.peak() && sellHeap.peak().price <= price) {\n                if (sellHeap.peak().amount > amount) {\n                    sellHeap.peak().amount -= amount\n                    amount = 0\n                } else {\n                    amount -= sellHeap.pop().amount;\n                }\n            }\n            \n            // if there is any amount left, add it to the buy backlog\n            if (amount) {\n                buyHeap.push({ price, amount })\n            }\n        }\n    }\n    \n    // total all of the amounts in both backlogs and return the result\n    let accumultiveAmount = 0;\n    for (const { amount } of buyHeap.store) {\n        accumultiveAmount += amount;\n    }\n    for (const { amount } of sellHeap.store) {\n        accumultiveAmount += amount;\n    }\n    return accumultiveAmount % 1000000007\n};\n\nclass Heap {\n    constructor(fn) {\n        this.store = [];\n        this.fn = fn;\n    }\n    \n    peak() {\n        return this.store[0];\n    }\n    \n    size() {\n        return this.store.length;\n    }\n    \n    pop() {\n        if (this.store.length < 2) {\n            return this.store.pop();\n        }\n        const result = this.store[0];\n        this.store[0] = this.store.pop();\n        this.heapifyDown(0);\n        return result;\n    }\n    \n    push(val) {\n        this.store.push(val);\n        this.heapifyUp(this.store.length - 1);\n    }\n    \n    heapifyUp(child) {\n        while (child) {\n            const parent = Math.floor((child - 1) / 2);\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                child = parent;\n            } else {\n                return child;\n            }\n        }\n    }\n    \n    heapifyDown(parent) {\n        while (true) {\n            let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n            if (this.shouldSwap(child2, child)) {\n                child = child2\n            }\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                parent = child;\n            } else {\n                return parent;\n            }\n        }\n    }\n    \n    shouldSwap(child, parent) {\n        return child && this.fn(this.store[child], this.store[parent]);\n    }\n}",
        "solution_java": "class Solution {\n    \n    PriorityQueue<Order> buyBackLog;\n    PriorityQueue<Order> sellBackLog;\n    \n    static int MOD = 1_000_000_007;\n    \n    \n    public int getNumberOfBacklogOrders(int[][] orders) {\n        \n        //max heap, heapify on price\n        buyBackLog = new PriorityQueue<Order>((a, b) -> (b.price - a.price));\n        //min heap, heapify on price\n        sellBackLog = new PriorityQueue<Order>((a, b) -> (a.price - b.price));\n        \n        \n        //handle all order\n        for(int[] order : orders){\n            int price     = order[0];\n            int quantity  = order[1];\n            int orderType = order[2];\n            \n            if(orderType == 0){\n                //buy order \n                handleBuyOrder(new Order(price, quantity));\n                \n            }else if(orderType == 1){ \n                //sell order\n                handleSellOrder(new Order(price, quantity));\n            }\n        }\n        \n        long counts = 0L;\n        \n        //count buy backlog\n        while(!buyBackLog.isEmpty()){\n            counts += buyBackLog.remove().quantity; \n            counts %= MOD;\n        }\n        \n        //count sell backlog\n        while(!sellBackLog.isEmpty()){\n            counts += sellBackLog.remove().quantity; \n            counts %= MOD;\n        }\n        \n        \n        return (int) (counts % MOD);\n    }\n    \n    \n    \n    \n    private void handleBuyOrder(Order buyOrder){\n        //just add buyorder, if there is no sell back log\n        if(sellBackLog.isEmpty()){\n            buyBackLog.add(buyOrder);\n            return;\n        }\n        \n        \n        while(!sellBackLog.isEmpty() && buyOrder.price >= sellBackLog.peek().price && buyOrder.quantity > 0){\n            //selloder with minumum price\n            Order sellOrder = sellBackLog.remove();\n            \n            if(buyOrder.quantity >= sellOrder.quantity){\n                buyOrder.quantity -= sellOrder.quantity;\n                sellOrder.quantity = 0;\n            } else {\n                //decrement sell order, add remaining sellorder\n                sellOrder.quantity -= buyOrder.quantity;\n                sellBackLog.add(sellOrder);\n                \n                buyOrder.quantity = 0;\n            }\n        }\n        \n        //add reaming buyorder\n        if(buyOrder.quantity > 0){\n            buyBackLog.add(buyOrder);\n        }\n    }\n    \n    \n    private void handleSellOrder(Order sellOrder){\n        //just add sell order, if there is no buy backlog\n        if(buyBackLog.isEmpty()){\n            sellBackLog.add(sellOrder);\n            return;\n        }\n        \n        \n        while(!buyBackLog.isEmpty() && buyBackLog.peek().price >= sellOrder.price && sellOrder.quantity > 0){\n            //buy order with maximum price\n            Order buyOrder = buyBackLog.remove();\n            \n            if(sellOrder.quantity >= buyOrder.quantity){\n                sellOrder.quantity -= buyOrder.quantity;\n                buyOrder.quantity = 0;\n                \n            }else{\n                //decrement buy order quantity, add remaining buyorder\n                buyOrder.quantity -= sellOrder.quantity;\n                buyBackLog.add(buyOrder);\n                \n                sellOrder.quantity = 0;\n            }\n        }\n        \n        //add remaining sell order\n        if(sellOrder.quantity > 0){\n            sellBackLog.add(sellOrder);\n        }\n    }\n}\n\nclass Order{\n    int price;\n    int quantity;\n    \n    public Order(int price, int quantity){\n        this.price = price;\n        this.quantity = quantity;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n        int n = orders.size();\n        //0 - buy  , 1 - sell; \n        priority_queue<vector<int>> buyBacklog;\n        priority_queue<vector<int> , vector<vector<int>> , greater<vector<int>>> sellBacklog;\n        \n        for(auto order : orders) {\n            if(order[2] == 0) \n                buyBacklog.push(order);\n            else \n                sellBacklog.push(order);\n            \n            while(!buyBacklog.empty() && !sellBacklog.empty() && sellBacklog.top()[0] <= buyBacklog.top()[0])  {\n                auto btop = buyBacklog.top();\n                buyBacklog.pop();\n                auto stop = sellBacklog.top();\n                sellBacklog.pop();\n                int diff = btop[1] - stop[1];\n                if(diff > 0) {\n                    btop[1] = diff;\n                    buyBacklog.push(btop);\n                }\n                else if(diff<0) {\n                    stop[1] = abs(diff);\n                    sellBacklog.push(stop);\n                }\n            }\n        }\n        \n        int ans = 0 , mod = 1e9+7;\n        while(!buyBacklog.empty()){\n            ans = (ans +buyBacklog.top()[1])%mod;\n            buyBacklog.pop();\n        }\n        while(!sellBacklog.empty()){\n            ans = (ans+ sellBacklog.top()[1])%mod;\n            sellBacklog.pop();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Deletions to Make Character Frequencies Unique",
        "algo_input": "A string s is called good if there are no two different characters in s that have the same frequency.\n\nGiven a string s, return the minimum number of characters you need to delete to make s good.\n\nThe frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aab\"\nOutput: 0\nExplanation: s is already good.\n\n\nExample 2:\n\nInput: s = \"aaabbbcc\"\nOutput: 2\nExplanation: You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".\n\nExample 3:\n\nInput: s = \"ceabaacb\"\nOutput: 2\nExplanation: You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts&nbsp;contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def minDeletions(self, s: str) -> int:\n        # Get the frequency of each character sorted in reverse order\n        frequencies = sorted(Counter(s).values(), reverse=True)\n        \n        total_deletions = 0\n        next_unused_freq = len(s)\n        for freq in frequencies:\n            # It is impossible for the frequency to be higher\n            next_unused_freq = min(next_unused_freq, freq)\n            total_deletions += freq - next_unused_freq\n\n            # We cannot have another character with this frequency,\n            # so decrement next_unused_freq\n            if next_unused_freq > 0:\n                next_unused_freq -= 1\n\n        return total_deletions",
        "solution_js": "var minDeletions = function(s) {\n    let freq = new Array(26).fill(0); // Create an array to store character frequencies\n    \n    for (let i = 0; i < s.length; i++) {\n        freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; // Count the frequency of each character\n    }\n    \n    freq.sort((a, b) => a - b); // Sort frequencies in ascending order\n    \n    let del = 0; // Initialize the deletion count\n    \n    for (let i = 24; i >= 0; i--) {\n        if (freq[i] === 0) {\n            break; // No more characters with this frequency\n        }\n        \n        if (freq[i] >= freq[i + 1]) {\n            let prev = freq[i];\n            freq[i] = Math.max(0, freq[i + 1] - 1);\n            del += prev - freq[i]; // Update the deletion count\n        }\n    }\n    \n    return del; // Return the minimum deletions required\n};",
        "solution_java": "class Solution {\n    private int N = 26;\n    public int minDeletions(String s) {\n        int[] array = new int[N];\n        for (char ch : s.toCharArray()) {\n            array[ch - 'a']++;\n        }\n        int ans = 0;\n        Set<Integer> set = new HashSet<>();\n        for (int i : array) {\n            if (i == 0) continue;\n            while (set.contains(i)) {\n                i--;\n                ans++;\n            }\n            if (i != 0) {\n                set.add(i);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minDeletions(string s) {\n        //Array to store the count of each character.\n        vector<int> freq (26, 0);\n        \n        //Calculatimg frequency of all characters.\n        for (char c : s){\n            freq[c - 'a']++;\n        }\n        \n        //sorting the frequencies. So the greatest frequencies are in right side.\n        sort(freq.begin(), freq.end());\n        \n        int del = 0; //to store the deletions.\n        \n        //Checking if 2 frequencies are same, if same then decrease the frequency so that it becomes less than the next greater one.So Start from the 2nd greatest frequency that is at freq[24].\n        for (int i = 24; i >= 0; i--) {\n            \n            if(freq[i] == 0) break; // if frequency is 0 that means no more character is left.\n            \n            if(freq[i] >= freq[i+1]){\n                int prev = freq[i]; //To store the frequency before deletion.\n                freq[i] = max(0, freq[i+1] -1); //New frequency should be 1 less than the previous frequency in the array.\n                del += prev - freq[i]; //Calculating deleted characters \n            }\n        }\n        return del;\n    }\n};"
    },
    {
        "title": "Kids With the Greatest Number of Candies",
        "algo_input": "There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.\n\nReturn a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.\n\nNote that multiple kids can have the greatest number of candies.\n\n&nbsp;\nExample 1:\n\nInput: candies = [2,3,5,1,3], extraCandies = 3\nOutput: [true,true,true,false,true] \nExplanation: If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n\n\nExample 2:\n\nInput: candies = [4,2,1,1,2], extraCandies = 1\nOutput: [true,false,false,false,false] \nExplanation: There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\n\n\nExample 3:\n\nInput: candies = [12,1,12], extraCandies = 10\nOutput: [true,false,true]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == candies.length\n\t2 &lt;= n &lt;= 100\n\t1 &lt;= candies[i] &lt;= 100\n\t1 &lt;= extraCandies &lt;= 50\n\n",
        "solution_py": "class Solution:\n    def kidsWithCandies(self, candy, extra):\n        #create an array(res) with all values as True and it's lenght is same as candies\n        res = [True]*len(candy)\n        #iterate over the elements in the array candy\n        for i in range(len(candy)):\n            #if the no. of canides at curr position + extra is greater than or equal to the maximum of candies then continue \n            if (candy[i] + extra) >= max(candy):\n                continue\n            #if not \n            else:\n                #change the value of that position in res as false\n                res[i] = False\n        #return the res list\n        return res   ",
        "solution_js": "var kidsWithCandies = function(candies, extraCandies) {\n    //First find out maximum number in array:->\n    let max=0, res=[]; \n    for(let i=0; i<candies.length; i++){\n        if(candies[i]>max) max=candies[i];\n    }\n    console.log(max)\n    \n    /*Now add extraCandies with every element in array and checks if\n\tthat sum is equals to or greater than max and return true and false otherwise; */\n    \n    for(let i=0; i<candies.length; i++){\n        let temp=candies[i]+extraCandies;\n        if(temp>=max) res.push(true);\n        else res.push(false);\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {\n        List<Boolean>result = new ArrayList<>(candies.length); // better practice since the length is known\n        int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1\n        for (int i = 1; i<candies.length; i++) {\n          theHighest = Math.max(theHighest,candies[i]); //returns the greatest value for us to compare later\n            }\n        //Since we are comparing with greatest value, we can use math logic to subtract extraCandies the other side\n        //(candies[i]+extraCandies >= theHighest) or (candies[i] >= theHighest-extraCandies)\n          int mathLogic = theHighest - extraCandies;\n        for (int i = 0; i<candies.length; i++) {\n           //logic: 6+5>=10 or 6 >=10-5\n               if (candies[i] >= mathLogic) {\n                   result.add(true);\n               } else {\n                    result.add(false);\n                    }\n            }\n        return result;\n        }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {\n        vector<bool> ans;\n        int i = 0, size, max = 0;\n        size = candies.size();\n        for(i = 0; i<size; i++){\n            if(candies[i]>max) max = candies[i];\n        }\n        for(i = 0; i<size;i++){\n            if(candies[i]+extraCandies >= max){\n                ans.push_back(true);\n            }\n            else ans.push_back(false);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "X of a Kind in a Deck of Cards",
        "algo_input": "In a deck of cards, each card has an integer written on it.\n\nReturn true if and only if you can choose X &gt;= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:\n\n\n\tEach group has exactly X cards.\n\tAll the cards in each group have the same integer.\n\n\n&nbsp;\nExample 1:\n\nInput: deck = [1,2,3,4,4,3,2,1]\nOutput: true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].\n\n\nExample 2:\n\nInput: deck = [1,1,1,2,2,2,3,3]\nOutput: false\nExplanation: No possible partition.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= deck.length &lt;= 104\n\t0 &lt;= deck[i] &lt; 104\n\n",
        "solution_py": "class Solution:\n    def hasGroupsSizeX(self, deck: List[int]) -> bool:\n        \n        \n        f=defaultdict(int)\n        \n        for j in deck:\n            f[j]+=1\n           \n        \n        import math\n        \n        u=list(f.values())\n        \n        g=u[0]\n        \n        for j in range(1,len(u)):\n            g=math.gcd(g,u[j])\n        return g!=1\n      \n        ",
        "solution_js": "var hasGroupsSizeX = function(deck) {\n    let unique = [...new Set(deck)], three = 0, two = 0, five = 0, size = 0, same = 0, s = 0;\n\n    for(let i = 0; i<unique.length; i++){\n        for(let y=0; y<deck.length; y++){\n            if(unique[i] === deck[y]){\n                size++;\n            }\n        }\n        if(size<2) return false;\n        if(size%2===0) two++;\n        if(size%3===0) three++;\n        if(size%5===0) five++;\n        if(s === size) same++;\n        s = size;\n        size = 0;\n    }\n\n    if(Math.max(two,three,five) !== unique.length && same !== unique.length-1) return false;\n    return true;\n};",
        "solution_java": "// X of a Kind in a Deck of Cards\n// Leetcode problem : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/\n\nclass Solution {\n    public boolean hasGroupsSizeX(int[] deck) {\n        int[] count = new int[10000];\n        for(int i : deck)\n            count[i]++;\n        int gcd = 0;\n        for(int i : count)\n            if(i != 0)\n                gcd = gcd == 0 ? i : gcd(gcd, i);\n        return gcd >= 2;       \n    }\n    private int gcd(int a, int b) {\n        return b == 0 ? a : gcd(b, a % b);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int gcd(int a,int b)\n    {\n        while(a>0 && b>0)\n        {\n            if(a>b) a=a%b;\n            else b=b%a;\n        }\n        return (a==0? b:a);\n    }\n    bool hasGroupsSizeX(vector<int>& deck) {\n        unordered_map<int,int> mp;\n        vector<int> v;\n        for(auto i:deck)\n        {\n            mp[i]++;\n        }\n        for(auto it:mp)\n        {\n            v.push_back(it.second);\n        }\n        int g=-1;\n        for(int i=0;i<v.size();i++)\n        {\n            if(g==-1)\n                g=v[i];\n            else \n                g=gcd(g,v[i]);\n        }\n        return g>1;\n    }\n};"
    },
    {
        "title": "Reverse Pairs",
        "algo_input": "Given an integer array nums, return the number of reverse pairs in the array.\n\nA reverse pair is a pair (i, j) where 0 &lt;= i &lt; j &lt; nums.length and nums[i] &gt; 2 * nums[j].\n\n&nbsp;\nExample 1:\nInput: nums = [1,3,2,3,1]\nOutput: 2\nExample 2:\nInput: nums = [2,4,3,5,1]\nOutput: 3\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n",
        "solution_py": "from sortedcontainers import SortedList\nclass Solution:\n    \"\"\"\n    For each sub array nums[0, i]\n    We sum the reverse pairs count\n    of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1 \n    Using a BST(sortedList) to get logN insert and lookup time.\n    Time: O(NlogN)\n    Space: O(N)\n    \"\"\"\n    def reversePairs(self, nums: List[int]) -> int:\n        res = 0\n        bst = SortedList()\n        for e in nums:\n            res += len(bst) - bst.bisect_left(2 * e + 1) # the count is the N - index\n            bst.add(e) # add the the bst\n        return res",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar reversePairs = function(nums) {\n  \n    let ans = mergeSort(nums,0,nums.length-1);\n    return ans;\n  \n    \n};\n\nvar mergeSort = function(nums,l,h){\n    if(l>=h){\n        return 0;\n    }\n    let m = Math.floor((l+h)/2);\n    let inv = mergeSort(nums,l,m);\n    inv = inv + mergeSort(nums,m+1,h);\n    inv = inv + merge(nums,l,m,h);\n    return inv;\n}\n\nvar merge = function (nums,l,m,h){\n    let cnt = 0;\n    let j=m+1;\n    for(let i=l;i<=m;i++){\n        while(j<=h && nums[i]> 2*nums[j]){\n            j++;\n        }\n        cnt = cnt+(j-(m+1));\n    }\n    \n    let left = l, right=m+1,temp=[];\n    while(left<=m && right<=h){\n        if(nums[left]<=nums[right]){\n            temp.push(nums[left]);\n            left++;\n        }\n        else{\n            temp.push(nums[right]);\n            right++;\n        }\n    }\n    while(left<=m){\n        temp.push(nums[left]);\n        left++;\n    }\n    while(right<=h){\n        temp.push(nums[right]);\n        right++;\n    }\n    for(let i=l;i<=h;i++){\n        nums[i]=temp[i-l];\n    }\n    return cnt;\n    \n}",
        "solution_java": "class Solution {\n    int cnt;\n    public int reversePairs(int[] nums) {\n        int n = nums.length;\n        cnt = 0;\n        sort(0 , n - 1 , nums);\n        return cnt;\n    }\n    void sort(int l , int r , int nums[]){\n        if(l == r){\n            return;\n        }\n        int mid = l + (r - l) / 2;\n        sort(l , mid , nums);\n        sort(mid + 1 , r , nums);\n        merge(l , mid , r , nums);\n    }\n    void merge(int l , int mid , int r , int nums[]){\n        int n1 = mid - l + 1;\n        int n2 = r - mid;\n        int a[] = new int[n1];\n        int b[] = new int[n2];\n        for(int i = 0; i < n1; i++){\n            a[i] = nums[l + i];\n        }\n        for(int j = 0; j < n2; j++){\n            b[j] = nums[mid + 1 + j];\n            int idx = upperBound(a , 0 , n1 - 1 , 2L * (long)b[j]);\n            if(idx <= n1) {\n                cnt += n1 - idx;\n            }\n        }\n        int i = 0;\n        int j = 0;\n        int k = l;\n        while(i < n1 && j < n2){\n            if(b[j] <= a[i]){\n                nums[k++] = b[j++];\n            }\n            else{\n                nums[k++] = a[i++];\n            }\n        }\n        while(i < n1){\n            nums[k++] = a[i++];\n        }\n        while(j < n2){\n            nums[k++] = b[j++];\n        }\n    }\n    int upperBound(int a[] , int l , int r , long x){\n        int ans = r + 1;\n        while(l <= r){\n            int mid = l + (r - l) / 2;\n            if((long)a[mid] > x){\n                ans = mid;\n                r = mid - 1;\n            }\n            else{\n                l = mid + 1;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int merge_count(vector<int> &nums,int s,int e){\n        int i;\n        int mid = (s+e)/2;\n        int j=mid+1;\n        long long int count=0;\n        for(i=s;i<=mid;i++){\n            while((j<=e)&&((double)nums[i]/2.0)>nums[j]){\n                j++;\n            }\n            count += j-(mid+1);\n        }\n        i=s;j=mid+1;\n        vector<int> ans;\n        while((i<=mid)&&(j<=e)){\n            if(nums[i]<=nums[j]){\n                ans.push_back(nums[i]);\n                i++;\n            }\n            else{\n                ans.push_back(nums[j]);\n                j++;\n            }\n        }\n        while(i<=mid){\n            ans.push_back(nums[i]);\n            i++;\n        }\n        while(j<=e){\n            ans.push_back(nums[j]);\n            j++;\n        }\n        for(int k=s;k<=e;k++){\n            nums[k]=ans[k-s];\n        }\n        return count;\n    }\n\n    int reverse_count(vector<int> &nums,int s,int e){\n        if(s>=e){\n            return 0;\n        }\n        int mid = (s+e)/2;\n        int l_count = reverse_count(nums,s,mid);\n        int r_count = reverse_count(nums,mid+1,e);\n        int s_count = merge_count(nums,s,e);\n        return (l_count+r_count+s_count);\n    }\n\n    int reversePairs(vector<int>& nums) {\n        int res = reverse_count(nums,0,nums.size()-1);\n        return res;\n    }\n};"
    },
    {
        "title": "Balance a Binary Search Tree",
        "algo_input": "Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.\n\nA binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,2,null,3,null,4,null,null]\nOutput: [2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\n\n\nExample 2:\n\nInput: root = [2,1,3]\nOutput: [2,1,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode(object):\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution(object):\n    def balanceBST(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: TreeNode\n        \"\"\"\n        arr = []\n        self.flatTree(root, arr)\n        return self.createTree(arr, 0, len(arr))\n    \n    def flatTree(self, root, arr):\n        if not root:\n            return\n        self.flatTree(root.left, arr)\n        arr.append(root)\n        self.flatTree(root.right, arr)\n    \n    def createTree(self, arr, start, length):\n        if length == 0:\n            return None\n        root = arr[start + length / 2]\n        root.left = self.createTree(arr, start, length / 2)\n        root.right = self.createTree(arr, start + length / 2 + 1, length - length / 2 - 1)\n        return root",
        "solution_js": "var balanceBST = function(root) {\nlet arr = [];//store sorted value in array\nlet InOrder = (node) => {//inorder helper to traverse and store sorted values in array\n    if(!node)\n        return;\n    InOrder(node.left);\n    arr.push(node.val);\n    InOrder(node.right);\n}\nInOrder(root);\nlet BalancedFromSortedArray = (arr, start, end) => {//create Balanced tree from sorted array\n    if(start>end)\n        return null;\n    let mid = Math.floor((start+end)/2);\n    let newNode = new TreeNode(arr[mid]);\n    newNode.left = BalancedFromSortedArray(arr,start,mid-1);\n    newNode.right = BalancedFromSortedArray(arr,mid+1,end);\n    return newNode;\n}\nlet Balanced = BalancedFromSortedArray(arr,0,arr.length-1);\nreturn Balanced;\n};",
        "solution_java": "class Solution {\n    public TreeNode balanceBST(TreeNode root) {\n        List<Integer> arr = new ArrayList();\n        InOrder( root,  arr);\n        return sortedArrayToBST( arr, 0, arr.size()-1);\n    }\n    \n    public void InOrder(TreeNode node, List<Integer> arr){\n        if(node != null){\n            InOrder( node.left, arr);\n            arr.add(node.val);\n            InOrder( node.right, arr);\n        }\n    }\n    \n    public TreeNode sortedArrayToBST(List<Integer> arr, int start, int end) {\n\n        if (start > end) {\n            return null;\n        }\n \n        int mid = (start + end) / 2;\n        \n        TreeNode node = new TreeNode(arr.get(mid));\n        node.left = sortedArrayToBST(arr, start, mid - 1);\n        node.right = sortedArrayToBST(arr, mid + 1, end);\n         \n        return node;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nums ;\n    void traverse(TreeNode * root){\n        if(!root) return ;\n        traverse(root->left) ;\n        nums.push_back(root->val) ;\n        traverse(root->right) ;\n        return ;\n    }\n\n    TreeNode * makeTree(int s , int e){\n        if(s > e) return nullptr ;\n        int m = (s + e) / 2 ;\n        TreeNode * root = new TreeNode(nums[m]) ;\n\n        root->left = makeTree(s,m - 1) ;\n        root->right = makeTree(m + 1,e) ;\n\n        return root ;\n    }\n\n    TreeNode* balanceBST(TreeNode* root) {\n        traverse(root) ;\n        return makeTree(0,size(nums) - 1) ;\n    }\n};"
    },
    {
        "title": "Bitwise ORs of Subarrays",
        "algo_input": "We have an array arr of non-negative integers.\n\nFor every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i &lt;= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j].\n\nReturn the number of possible results. Results that occur more than once are only counted once in the final answer\n\n&nbsp;\nExample 1:\n\nInput: arr = [0]\nOutput: 1\nExplanation: There is only one possible result: 0.\n\n\nExample 2:\n\nInput: arr = [1,1,2]\nOutput: 3\nExplanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.\n\n\nExample 3:\n\nInput: arr = [1,2,4]\nOutput: 6\nExplanation: The possible results are 1, 2, 3, 4, 6, and 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t0 &lt;= nums[i]&nbsp;&lt;= 109\n\n",
        "solution_py": "class Solution:\n    def subarrayBitwiseORs(self, arr: List[int]) -> int:\n        \n        \n        ans=set(arr)\n        \n        # each element is a subarry\n        \n        \n        one = set()\n        \n        # to get the ans for the subarray of  size >1\n        # starting from 0th element to the ending element\n        \n        \n        one.add(arr[0])\n        \n        for i in  range(1,len(arr)):\n            \n            two=set()\n            \n            for j in one:\n                \n                two.add(j |  arr[i])\n                \n                # subarray from the element in one set to the current ele(i th one)\n                \n                ans.add(j| arr[i])\n                \n            \n            two.add(arr[i])\n            \n            # adding curr element to set two so that from next iteration we can take sub array starting from curr element \n            \n            one = two\n            \n        return len(ans)\n        ",
        "solution_js": "/** https://leetcode.com/problems/bitwise-ors-of-subarrays/\n * @param {number[]} arr\n * @return {number}\n */\nvar subarrayBitwiseORs = function(arr) {\n  // Hashset to store the unique bitwise\n  this.uniqueBw = new Set();\n  \n  // Dynamic programming\n  dp(arr, arr.length - 1);\n  \n  return this.uniqueBw.size;\n};\n\nvar dp = function(arr, currIdx) {\n  // Base, reach beginning of the array\n  if (currIdx === 0) {\n    // Store the value to unique bitwise, since it's only single number, we store the actual value\n    this.uniqueBw.add(arr[0]);\n    \n    // Return array\n    return [arr[0]];\n  }\n  \n  // DP to previous index\n  let prev = dp(arr, currIdx - 1);\n  \n  // Number at current index\n  let firstBw = arr[currIdx];\n  \n  // Add number at current index to hashset, since it's only single number, we store the actual value\n  this.uniqueBw.add(firstBw);\n  \n  // Another hashset to store the result of bitwise operation between number at current index with result from previous index\n  let currRes = new Set();\n  currRes.add(firstBw);\n  \n  // Loop through result form previous index\n  for (let i = 0; i < prev.length; i++) {\n    // Perform bitwise operation OR\n    let curr = arr[currIdx] | prev[i];\n    \n    // Add to unique bitwise collection\n    this.uniqueBw.add(curr);\n    \n    // Add to current result\n    currRes.add(curr);\n  }\n\n  // Return current result as an array\n  return [...currRes];\n};",
        "solution_java": "class Solution {\n    public int subarrayBitwiseORs(int[] arr) {\n        int n = arr.length;\n        Set<Integer> s = new HashSet();\n        LinkedList<Integer> queue = new LinkedList();\n        for(int i = 0; i< n; i++){\n            int size = queue.size();\n            if(!queue.contains(arr[i])){\n                queue.offer(arr[i]);\n                s.add(arr[i]);\n            }\n            int j = 0;\n            while(j<size){\n                int tmp = queue.poll()|arr[i];\n                if(!queue.contains(tmp)){\n                    queue.offer(tmp);\n                    s.add(tmp);\n                }\n                j++;\n            }\n        }\n        return s.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int subarrayBitwiseORs(vector<int>& arr) {\n        vector<int>s;\n        int l=0;\n        for(int a:arr) {\n            int r=s.size();\n            s.push_back(a);\n            for(int i=l;i<r;i++)\n              if(s.back()!=(s[i]|a))\n                s.push_back(s[i] | a);\n              l=r;\n            }\n    return unordered_set<int>(begin(s), end(s)).size();\n    }\n};"
    },
    {
        "title": "Find Resultant Array After Removing Anagrams",
        "algo_input": "You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.\n\nIn one operation, select any index i such that 0 &lt; i &lt; words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.\n\nReturn words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, \"dacb\" is an anagram of \"abdc\".\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]\nOutput: [\"abba\",\"cd\"]\nExplanation:\nOne of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = \"bbaa\" and words[1] = \"baba\" are anagrams, we choose index 2 and delete words[2].\n  Now words = [\"abba\",\"baba\",\"cd\",\"cd\"].\n- Since words[1] = \"baba\" and words[0] = \"abba\" are anagrams, we choose index 1 and delete words[1].\n  Now words = [\"abba\",\"cd\",\"cd\"].\n- Since words[2] = \"cd\" and words[1] = \"cd\" are anagrams, we choose index 2 and delete words[2].\n  Now words = [\"abba\",\"cd\"].\nWe can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.\n\nExample 2:\n\nInput: words = [\"a\",\"b\",\"c\",\"d\",\"e\"]\nOutput: [\"a\",\"b\",\"c\",\"d\",\"e\"]\nExplanation:\nNo two adjacent strings in words are anagrams of each other, so no operations are performed.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 10\n\twords[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def removeAnagrams(self, words: List[str]) -> List[str]:\n        i = 0\n        while i < len(words) - 1:\n            if sorted(words[i]) == sorted(words[i + 1]):\n                words.remove(words[i + 1])\n                continue\n            i += 1\n        return words",
        "solution_js": "var removeAnagrams = function(words) {\n    let n = words.length;\n    \n    for(let i=0; i<n-1; i++){\n        if(isAnagram(words[i], words[i+1])){\n            words.splice(i+1, 1);\n            i--\n            n--\n        }\n    }\n    return words\n};\n\nfunction isAnagram(a, b){\n    \n    let freqArr = new Array(26).fill(0);\n    if(a.length != b.length) return false\n    \n    for(let i=0; i<a.length; i++){\n        let idx1 = a[i].charCodeAt(0) - \"a\".charCodeAt(0);\n        freqArr[idx1]++;\n        let idx2 = b[i].charCodeAt(0) - \"a\".charCodeAt(0);\n        freqArr[idx2]--\n    }\n\n    \n    for(let i=0; i<26; i++){\n        if(freqArr[i] > 0){\n            return false\n        }\n    }\n    return true\n}",
        "solution_java": "class Solution {\n    public List<String> removeAnagrams(String[] words) {\n        String prev =\"\";\n        List<String> li=new ArrayList<>();\n        for(int i=0;i<words.length;i++){\n            char[] ch=words[i].toCharArray();\n            Arrays.sort(ch);\n            String curr=String.valueOf(ch);\n            if(!curr.equals(prev)){\n                li.add(words[i]);\n                prev=curr;\n            }\n        }\n        return li;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> removeAnagrams(vector<string>& words) {\n        for(int i = 1;i<words.size();i++){\n            string x = words[i];\n            sort(x.begin(),x.end());\n            string y = words[i-1];\n            sort(y.begin(),y.end());\n            if(x == y){\n                words.erase(words.begin() + i);\n                i--;\n            }\n        }\n        return words;\n    }\n};"
    },
    {
        "title": "Max Difference You Can Get From Changing an Integer",
        "algo_input": "You are given an integer num. You will apply the following steps exactly two times:\n\n\n\tPick a digit x (0 &lt;= x &lt;= 9).\n\tPick another digit y (0 &lt;= y &lt;= 9). The digit y can be equal to x.\n\tReplace all the occurrences of x in the decimal representation of num by y.\n\tThe new integer cannot have any leading zeros, also the new integer cannot be 0.\n\n\nLet a and b be the results of applying the operations to num the first and second times, respectively.\n\nReturn the max difference between a and b.\n\n&nbsp;\nExample 1:\n\nInput: num = 555\nOutput: 888\nExplanation: The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888\n\n\nExample 2:\n\nInput: num = 9\nOutput: 8\nExplanation: The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def maxDiff(self, num: int) -> int:\n        i=0\n        while i<len(str(num)):\n            change = (str(num)[i])\n            if change!='9':\n                break\n            i+=1\n        \n        i=0\n        flag = False\n        while i<len(str(num)):\n            sc = (str(num)[i])\n            if sc!='1' and sc!='0':\n                if i>0:\n                    flag =True\n                break\n            i+=1\n        small = str(num)\n        num = str(num)\n        m=''\n        for i in range(len(str(num))):\n            if num[i]==change:\n                m+='9'\n            else:\n                m+=num[i]\n        m = int(m)\n        s =''\n        for i in range(len(num)):\n            if small[i]==sc:\n                if flag:\n                    s+='0'\n                else:\n                    if small[i]==\"0\":\n                        s+='0'\n                    else:\n                        s+='1'\n            else:\n                s+=small[i]\n        small = int(s)\n        return m - small",
        "solution_js": "var maxDiff = function(num) {\n    let occur = undefined;\n    let max = num.toString().split(\"\");\n    let min = num.toString().split(\"\");\n    for(i=0;i<max.length;i++){\n        if(max[i]<9&&!occur){\n            occur = max[i];\n            max[i] = 9;\n        }\n        if(max[i]===occur) max[i] = 9;\n    }\n    occur = undefined;\n    let zerone;\n     for(i=0;i<min.length;i++){\n        if(!occur&&min[i]>1){\n            occur = min[i];\n            if(i===0) zerone = 1;\n            else zerone = 0;\n            min[i] = zerone;      \n        }    \n        if(min[i]===occur) min[i] = zerone;\n    }\n    return +max.join(\"\")-+min.join(\"\");\n};",
        "solution_java": "class Solution {\n    public int maxDiff(int num) {\n        int[] arr = new int[String.valueOf(num).length()];\n        for (int i = arr.length - 1; i >= 0; i--){\n            arr[i] = num % 10;\n            num /= 10;\n        }\n        return max(arr.clone()) - min(arr);\n    }\n\n    private int max(int[] arr){ // find max\n        for (int i = 0, t = -1; i < arr.length; i++){\n            if (t == -1 && arr[i] != 9){\n                t = arr[i];\n            }\n            if (t == arr[i]){\n                arr[i] = 9;\n            }\n        }\n        return parse(arr);\n    }\n\n    private int min(int[] arr){ // find min\n        int re = arr[0] == 1? 0 : 1;\n        int t = arr[0] == 1? -1 : arr[0];\n        for (int i = 0; i < arr.length; i++){\n            if (t == -1 && arr[i] != 0 && arr[i] != arr[0]){\n                t = arr[i];\n            }\n            if (t == arr[i]){\n                arr[i] = re;\n            }\n        }\n        return parse(arr);\n    }\n\n    private int parse(int[] arr){\n        int ans = 0;\n        for (int i = 0; i < arr.length; i++){\n            ans = 10 * ans + arr[i];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int power10(int n)\n    {\n        int total=1;\n        for(int i=0;i<n;i++)\n        {\n            total*=10;\n        }\n        return total;\n    }\n \n    int maxDiff(int num) {\n    vector<int> v;\n    vector<int> w;\n    int n = num;\n    while (n > 0)\n    {\n        v.push_back(n % 10);\n        w.push_back(n % 10);\n        n /= 10;\n    }\n        \n    //Finding maximum number\n    int d = v.size();\n    int j = d - 1;\n    for (int i = d - 1; i >= 0; i--)\n    {\n        if (v[i] != 9)\n        {\n            j = i;\n            break;\n        }\n    }\n    \n\n    for (int i = 0; i <= j; i++)\n    {\n        if (v[i] == v[j])\n        {\n            v[i] = 9;\n        }\n    }\n    long long int res = 0;\n    for (int i = d - 1; i >= 0; i--)\n    {\n        res += (v[i] * power10(i));\n    }\n\n    //Finding minimum number   \n    int t = w.size();\n    if (w[t - 1] == 1)\n    {\n        int l = -1;\n        for (int i = t - 2; i >= 0; i--)\n        {\n            if (w[i] != 0 && w[i]!=1)\n            {\n                l = i;\n                break;\n            }\n        }\n        for (int i = 0; i <= l; i++)\n        {\n            if (w[i] == w[l])\n            {\n                w[i] = 0;\n            }\n        }\n    }\n    else\n    {\n        for (int i = 0; i < t; i++)\n        {\n            if (w[i] == w[t - 1])\n            {\n                w[i] = 1;\n            }\n        }\n    }\n    long long int res2 = 0;\n    for (int i = t - 1; i >= 0; i--)\n    {\n        res2 += (power10(i) * w[i]);\n    }\n    return res-res2;\n    }\n};"
    },
    {
        "title": "Keys and Rooms",
        "algo_input": "There are n rooms labeled from 0 to n - 1&nbsp;and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.\n\nWhen you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.\n\nGiven an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: rooms = [[1],[2],[3],[]]\nOutput: true\nExplanation: \nWe visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.\n\n\nExample 2:\n\nInput: rooms = [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == rooms.length\n\t2 &lt;= n &lt;= 1000\n\t0 &lt;= rooms[i].length &lt;= 1000\n\t1 &lt;= sum(rooms[i].length) &lt;= 3000\n\t0 &lt;= rooms[i][j] &lt; n\n\tAll the values of rooms[i] are unique.\n\n",
        "solution_py": "class Solution:\n    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n        # Create a set of for rooms visited\n        visited_rooms = set()\n        \n        # Create a queue to do a breadth first search visiting rooms\n        # Append the first room, 0, to the queue to begin the search\n        queue = collections.deque()\n        queue.append(0)\n        \n        # Perform the breadth first search with the queue\n        while queue:\n            for _ in range(0, len(queue)):\n                # Search the room\n                room_number = queue.popleft()\n                \n                # If we haven't visited the room, get the keys from the room\n                if room_number not in visited_rooms:\n                \n                    # Collect the keys from the room\n                    found_keys = rooms[room_number]\n                    \n                    # Add the keys to the queue so they can be tested\n                    for key in found_keys:\n                        queue.append(key)\n                        \n                    # Add the current room to the visited set\n                    visited_rooms.add(room_number)\n        \n        # If we visited all of the rooms, then the number of visited rooms should be\n        # equal to the number of total rooms\n        if len(visited_rooms) == len(rooms):\n            return True\n        \n        return False",
        "solution_js": "function dfs(current,all,visited){\n    if(visited.size==all.length){\n        return true;\n    }\n    for(let i=0;i<all[current].length;i++){\n        if(!visited.has(all[current][i])){\n            visited.add(all[current][i]);\n            if(dfs(all[current][i],all,visited))\n                return true;\n        }\n\n    }\n    return false;\n\n}\nvar canVisitAllRooms = function(rooms) {\n    let visited=new Set();\n    visited.add(0);\n    if (dfs(0,rooms,visited)) return true;\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean canVisitAllRooms(List<List<Integer>> rooms) {\n    \t\t boolean[] visited = new boolean[rooms.size()];\n    \t\t visited[0]= true;\n    \t\t for(int a:rooms.get(0))\n    \t\t {\n    \t\t\t if(!visited[a])\n    \t\t\t {\n    \t\t\t\t bfs(a, visited, rooms.size()-1, rooms);\n    \t\t\t\t \n    \t\t\t }\n    \t\t }\n    \t\t //System.out.println(\"arr -->>\"+Arrays.toString(visited));\n    \t\tfor(boolean a:visited)\n    \t\t{\n    \t\t\tif(!a)\n    \t\t\t\treturn false;\n    \t\t}\n    \t      return true;\n    \t        \n    \t    }\n    \t public void bfs(int key, boolean[] vivsted, int target,List<List<Integer>> rooms)\n    \t {\n    \t\t\n    \t\t\n    \t\t vivsted[key] = true;\n    \t\t for(int a:rooms.get(key))\n    \t\t {\n    \t\t\t if(!vivsted[a])\n    \t\t\t {\n    \t\t\t\t bfs(a, vivsted, target, rooms);\n    \t\t\t }\n    \t\t }\n    \t\t \n    \t\t \n    \t\t\n    \t }\n       \n}",
        "solution_c": "class Solution {\npublic:\n    void dfs(int node, vector<vector<int>>& rooms,vector<int> &visited){\n        visited[node]=1;\n        \n        for(auto it: rooms[node]){\n            if(visited[it]==0)\n                dfs(it, rooms, visited);\n            else continue;\n        }\n        return;\n    }\n    \n    bool canVisitAllRooms(vector<vector<int>>& rooms) {\n        int n=rooms.size();\n        vector<int> visited(n,0);\n        \n        dfs(0,rooms,visited);\n        \n        for(int i=0;i<n;i++){\n            if(visited[i]==0) return false;\n        }    \n        return true;\n    }\n};"
    },
    {
        "title": "Minimum Numbers of Function Calls to Make Target Array",
        "algo_input": "You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:\n\nYou want to use the modify function to covert arr to nums using the minimum number of calls.\n\nReturn the minimum number of function calls to make nums from arr.\n\nThe test cases are generated so that the answer fits in a 32-bit signed integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,5]\nOutput: 5\nExplanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -&gt; [0, 2] -&gt; [0, 4] (2 operations).\nIncrement by 1 (both elements)  [0, 4] -&gt; [1, 4] -&gt; [1, 5] (2 operations).\nTotal of operations: 1 + 2 + 2 = 5.\n\n\nExample 2:\n\nInput: nums = [2,2]\nOutput: 3\nExplanation: Increment by 1 (both elements) [0, 0] -&gt; [0, 1] -&gt; [1, 1] (2 operations).\nDouble all the elements: [1, 1] -&gt; [2, 2] (1 operation).\nTotal of operations: 2 + 1 = 3.\n\n\nExample 3:\n\nInput: nums = [4,2,5]\nOutput: 6\nExplanation: (initial)[0,0,0] -&gt; [1,0,0] -&gt; [1,0,1] -&gt; [2,0,2] -&gt; [2,1,2] -&gt; [4,2,4] -&gt; [4,2,5](nums).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "# Observe that:\n#   +1  places a 1 to the end of the int's binary representation\n#       (assuming a 0 there previously)\n#   x2  is a bitshift left\n# So you basically just need to count all the ones in the binary representations\n# and find how many shifts are required (largest bit length minus one).\n\nclass Solution:\n    def minOperations(self, nums: List[int]) -> int:\n        if max(nums) == 0:\n            return 0\n        \n        return sum([x.bit_count() for x in nums]) + max([x.bit_length() for x in nums]) - 1",
        "solution_js": "var minOperations = function(nums) {\n    let maxpow = 0, ans = 0, pow, val\n    for (let i = 0; i < nums.length; i++) {\n        for (val = nums[i], pow = 0; val > 0; ans++)\n            if (val % 2) val--\n            else pow++, val /= 2\n        ans -= pow\n        if (pow > maxpow) maxpow = pow\n    }\n    return ans + maxpow\n};",
        "solution_java": "class Solution {\n    public int minOperations(int[] nums) {\n        int odd = 0, even = 0;\n        Map<Integer, Integer> map = new HashMap<>();\n        for (int n : nums){\n            int res = dfs(n, map);\n            odd += res >> 5;\n            even = Math.max(res & 0b11111, even);\n        }\n\n        return odd + even;\n    }\n\n    private int dfs(int n, Map<Integer, Integer> map){\n        if (n == 0) return 0;\n        if (map.containsKey(n)) return map.get(n);\n\n        int res = n % 2 << 5;\n        res += dfs(n / 2, map) + (n > 1? 1 : 0);\n\n        map.put(n, res);\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minOperations(vector<int>& nums) {\n        int ans = 0;\n        int t = 33;\n        while(t--){\n            int flag = false;\n            for(int i = 0; i<nums.size(); i++){\n                if(nums[i]%2) ans++;\n                nums[i]/=2;\n                if(nums[i]!=0) flag = true;\n            }\n\t\t\t\n            if(!flag) break;\n            ans++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Population Year",
        "algo_input": "You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.\n\nThe population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.\n\nReturn the earliest year with the maximum population.\n\n&nbsp;\nExample 1:\n\nInput: logs = [[1993,1999],[2000,2010]]\nOutput: 1993\nExplanation: The maximum population is 1, and 1993 is the earliest year with this population.\n\n\nExample 2:\n\nInput: logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput: 1960\nExplanation: \nThe maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= logs.length &lt;= 100\n\t1950 &lt;= birthi &lt; deathi &lt;= 2050\n\n",
        "solution_py": "class Solution:\n    def maximumPopulation(self, logs: List[List[int]]) -> int:\n        logs.sort(key=lambda x: x[0])\n        print(logs)\n        living = 0\n        max_living = 0\n        year = 0\n\n        for ind, (start, stop) in enumerate(logs):\n            born = ind+1\n            dead = 0\n            for i in range(ind):\n                if logs[i][1] <= start:\n                    dead += 1\n            \n            living = born - dead\n            # print(born, dead, living, max_living)\n            if living > max_living:\n                max_living = living\n                year = start\n\n        \n        \n        return year",
        "solution_js": "var maximumPopulation = function(logs) {\n    const count = new Array(101).fill(0);\n    \n    for (const [birth, death] of logs) {\n        count[birth - 1950]++;\n        count[death - 1950]--;\n    }\n    \n    let max = 0;\n    \n    for (let i = 1; i < 101; i++) {\n        count[i] += count[i - 1];\n        \n        if (count[i] > count[max]) max = i;\n     }\n    \n     return 1950 + max;\n };",
        "solution_java": "class Solution {\n    public int maximumPopulation(int[][] logs) {\n\n        int[] year = new int[2051];\n\n        // O(n) -> n is log.length\n\n        for(int[] log : logs){\n\n            year[log[0]] += 1;\n            year[log[1]] -= 1;\n        }\n\n        int maxNum = year[1950], maxYear = 1950;\n\n        // O(100) -> 2050 - 1950 = 100\n\n        for(int i = 1951; i < year.length; i++){\n            year[i] += year[i - 1]; // Generating Prefix Sum\n\n            if(year[i] > maxNum){\n                maxNum = year[i];\n                maxYear = i;\n            }\n        }\n\n        return maxYear;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumPopulation(vector<vector<int>>& logs) {\n        int arr[101]={0};\n        for(vector<int> log : logs){\n            arr[log[0]-1950]++;\n            arr[log[1]-1950]--;\n        }\n        int max=0,year,cnt=0;\n        for(int i=0;i<101;i++){\n            cnt+=arr[i];\n            if(cnt>max)\n                max=cnt,year=i;\n        }\n        return year+1950;\n    }\n};"
    },
    {
        "title": "Remove Element",
        "algo_input": "Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.\n\nSince it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.\n\nReturn k after placing the final result in the first k slots of nums.\n\nDo not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n\nCustom Judge:\n\nThe judge will test your solution with the following code:\n\nint[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n                            // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i &lt; actualLength; i++) {\n    assert nums[i] == expectedNums[i];\n}\n\n\nIf all assertions pass, then your solution will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,2,2,3], val = 3\nOutput: 2, nums = [2,2,_,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\nExample 2:\n\nInput: nums = [0,1,2,2,3,0,4,2], val = 2\nOutput: 5, nums = [0,1,4,0,3,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 50\n\t0 &lt;= val &lt;= 100\n\n",
        "solution_py": "class Solution(object):\n    def removeElement(self, nums, val):\n        \"\"\"\n        :type nums: List[int]\n        :type val: int\n        :rtype: int\n        \"\"\"\n        step = 0\n        while step < len(nums):\n            if nums[step] == val:\n                nums.pop(step)\n                continue\n            step+=1\n        return len(nums)",
        "solution_js": "var removeElement = function(nums, val) {\n    for(let i = 0; i < nums.length; i++){\n        if(nums[i] === val){\n            nums.splice(i, 1);\n            i--;\n        }\n    }\n    return nums.length;\n};",
        "solution_java": "class Solution {\n    public int removeElement(int[] nums, int val) {\n        int ind = 0;\n        for(int i=0; i<nums.length; i++){\n            if(nums[i] != val){\n                nums[ind++] = nums[i];\n            }\n        }\n        return ind;\n    }\n}",
        "solution_c": "// two pointer\nclass Solution {\npublic:\n    int removeElement(vector<int>& nums, int val) {\n        int left = 0;\n        int right = nums.size() - 1;\n        while (left <= right) {\n              if (nums[left] != val) {\n                 ++left;\n              }\n              else if (nums[right] == val) {\n                 --right;\n              }\n              else if (left < right) {\n                 nums[left++] = nums[right--];\n              }\n        }\n        return left;\n    }\n};"
    },
    {
        "title": "Longest Word in Dictionary through Deleting",
        "algo_input": "Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]\nOutput: \"apple\"\n\n\nExample 2:\n\nInput: s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]\nOutput: \"a\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\t1 &lt;= dictionary.length &lt;= 1000\n\t1 &lt;= dictionary[i].length &lt;= 1000\n\ts and dictionary[i] consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findLongestWord(self, s: str, dictionary: list[str]) -> str:\n        solution = \"\"\n        for word in dictionary:\n            j = 0\n            for i in range(len(s)):\n                if s[i] == word[j]:\n                    j+=1\n                if j == len(word):\n                    solution = word if len(word) > len(solution) or len(word) == len(solution) and word < solution  else solution\n                    break\n        return solution",
        "solution_js": "/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\nvar findLongestWord = function(s, dictionary) {\n    const getLen = (s1, s2) => {\n        let i = 0, j = 0;\n        while(i < s1.length && j < s2.length) {\n            if(s1[i] == s2[j]) { i++, j++; }\n            else i++;\n        }\n        if(j != s2.length) return 0;\n        return s2.length;\n    }\n    let ans = '', ml = 0;\n    for(let word of dictionary) {\n        const len = getLen(s, word);\n        if(len > ml) {\n            ans = word;\n            ml = len;\n        }\n        else if(len == ml && ans > word) {\n            ans = word;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public String findLongestWord(String s, List<String> dictionary) {\n        \n        int[] fre=new int[26];\n       \n        \n        String ans=\"\";\n        int flag=0;\n        int[] fff=new int[26];\n         char[] ch = s.toCharArray();\n        for(char c : ch)\n            fre[c-'a']+=1;\n        \n        for(String s1 : dictionary)\n        { \n             fff=fre.clone();\n             int[] fre1=new int[26];\n             char[] ch1 = s1.toCharArray();\n            for(char c : ch1)\n            {\n               \n                fre1[c-'a']+=1;\n            }\n            \n            for(char c : ch1)\n            {\n                if(fre1[c-'a'] <= fff[c-'a'])\n                { flag=0;\n                  fff[c-'a']-=1; \n                 fre1[c-'a']-=1;\n                }\n                else\n                {flag=1;\n                  break;}                \n            }\n            if(flag==0)\n            {\n                if(ans != \"\")\n                {\n                  if(ans.length() <s1.length())\n                  {\n                      \n                      ans=s1;\n                  }else\n                  {\n                      if(ans.length() ==s1.length())\n                      {\n                          int f=0;\n                         for(int m=0;m<ans.length();m++)\n                         {\n                             if(ans.charAt(m)>s1.charAt(m))\n                             {\n                                 f=1;\n                                 break;\n                             }\n                                 \n                         }\n                          if(f==1)\n                              ans=s1;\n                      }\n                  }\n                }\n                else\n                    ans =s1;\n            }\n            else\n            {\n                flag=0;\n            }\n        }\n        \n        return ans;\n        \n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    //checks whether the string word is a subsequence of s\n    bool isSubSeq(string &s,string &word){\n        int start=0;\n        for(int i=0;i<s.size();i++){\n            if(s[i]==word[start]){\n                //every character of word occurs in s, therefore we return true\n                if(++start==word.size()){\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\npublic:\n    string findLongestWord(string s, vector<string>& dictionary) {\n        string ans=\"\";\n        for(string word:dictionary){\n            if(word.size()>=ans.size() and isSubSeq(s,word)){\n                if(word.size()>ans.size()){\n                    ans=word;\n                } else if(word.size()==ans.size() and word<ans){\n                    ans=word;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Sort List",
        "algo_input": "Given the head of a linked list, return the list after sorting it in ascending order.\n\n&nbsp;\nExample 1:\n\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\n\n\nExample 2:\n\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n\n\nExample 3:\n\nInput: head = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 5 * 104].\n\t-105 &lt;= Node.val &lt;= 105\n\n\n&nbsp;\nFollow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?\n",
        "solution_py": "class Solution:\n    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        store = []\n        curr = head\n        while curr:\n            store.append(curr.val)\n            curr = curr.next\n        store.sort()\n        dummyNode = ListNode(0)\n        temp = dummyNode\n        \n        for i in store:\n            x = ListNode(val = i)\n            temp.next = x\n            temp = x\n        return dummyNode.next",
        "solution_js": "function getListSize(head) {\n    let curr = head;\n    let size = 0;\n\n    while(curr !== null) {\n        size += 1;\n\n        curr = curr.next;\n    }\n\n    return size;\n}\n\nfunction splitInHalf(head, n) {\n    let node1 = head;\n    let curr = head;\n\n    for (let i = 0; i < Math.floor(n / 2) - 1; i++) {\n        curr = curr.next;\n    }\n\n    const node2 = curr.next;\n    curr.next = null;\n\n    return [\n        node1,\n        Math.floor(n / 2),\n        node2,\n        n - Math.floor(n / 2),\n    ]\n}\n\nfunction merge(head1, head2) {\n    if (head1.val > head2.val) {\n        return merge(head2, head1)\n    }\n\n    const head = head1;\n    let curr = head1;\n\n    let runner1 = curr.next;\n    let runner2 = head2;\n\n    while (runner1 !== null || runner2 !== null) {\n        const runner1Value = runner1 ? runner1.val : Infinity;\n        const runner2Value = runner2 ? runner2.val : Infinity;\n\n        if (runner1Value < runner2Value) {\n            curr.next = runner1;\n            runner1 = runner1.next;\n        } else {\n            curr.next = runner2;\n            runner2 = runner2.next;\n        }\n\n        curr = curr.next;\n    }\n\n    curr.next = null;\n    return head;\n}\n\nvar sortList = function(head) {\n    const size = getListSize(head);\n\n    function mergeSort(node, n) {\n        if (n <= 1) {\n            return node;\n        }\n\n        const [node1, n1, node2, n2] = splitInHalf(node, n);\n        const [merged1, merged2] = [mergeSort(node1, n1), mergeSort(node2, n2)];\n\n        return merge(merged1, merged2);\n    }\n\n    return mergeSort(head, size);\n};",
        "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public ListNode sortList(ListNode head) {\n        if (head == null || head.next == null) {\n            return head;\n        }\n\n        ListNode mid = middle(head);\n\n        ListNode left = sortList(head);\n        ListNode right = sortList(mid);\n\n        return mergeTwoLists(left, right);\n    }\n    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n        ListNode head = new ListNode();\n        ListNode tail = head;\n        while (list1 != null && list2 != null) {\n            if (list1.val < list2.val) {\n                tail.next = list1;\n                list1 = list1.next;\n                tail = tail.next;\n            } else {\n                tail.next = list2;\n                list2 = list2.next;\n                tail = tail.next;\n            }\n        }\n\n        tail.next = (list1 != null) ? list1 : list2;\n\n        return head.next;\n    }\n\n    public ListNode middle(ListNode head) {\n        ListNode midprev = null;\n        while (head != null && head.next != null) {\n            midprev = (midprev == null) ? head : midprev.next;\n            head = head.next.next;\n        }\n        ListNode mid = midprev.next;\n        midprev.next = null;\n        return mid;\n    }\n}",
        "solution_c": "                            // Please upvote if it helps\nclass Solution {\npublic:\n    ListNode* sortList(ListNode* head) {\n        //If List Contain a Single or 0 Node\n        if(head == NULL || head ->next == NULL)\n            return head;\n\n        ListNode *temp = NULL;\n        ListNode *slow = head;\n        ListNode *fast = head;\n\n        // 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)\n        while(fast != NULL && fast -> next != NULL)\n        {\n            temp = slow;\n            slow = slow->next; //slow increment by 1\n            fast = fast ->next ->next; //fast incremented by 2\n\n        }\n        temp -> next = NULL; //end of first left half\n\n        ListNode* l1 = sortList(head); //left half recursive call\n        ListNode* l2 = sortList(slow); //right half recursive call\n\n        return mergelist(l1, l2); //mergelist Function call\n\n    }\n\n    //MergeSort Function O(n*logn)\n    ListNode* mergelist(ListNode *l1, ListNode *l2)\n    {\n        ListNode *ptr = new ListNode(0);\n        ListNode *curr = ptr;\n\n        while(l1 != NULL && l2 != NULL)\n        {\n            if(l1->val <= l2->val)\n            {\n                curr -> next = l1;\n                l1 = l1 -> next;\n            }\n            else\n            {\n                curr -> next = l2;\n                l2 = l2 -> next;\n            }\n\n        curr = curr ->next;\n\n        }\n\n        //for unqual length linked list\n\n        if(l1 != NULL)\n        {\n            curr -> next = l1;\n            l1 = l1->next;\n        }\n\n        if(l2 != NULL)\n        {\n            curr -> next = l2;\n            l2 = l2 ->next;\n        }\n\n        return ptr->next;\n    }\n};"
    },
    {
        "title": "Maximum Candies Allocated to K Children",
        "algo_input": "You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.\n\nYou are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.\n\nReturn the maximum number of candies each child can get.\n&nbsp;\nExample 1:\n\nInput: candies = [5,8,6], k = 3\nOutput: 5\nExplanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.\n\n\nExample 2:\n\nInput: candies = [2,5], k = 11\nOutput: 0\nExplanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= candies.length &lt;= 105\n\t1 &lt;= candies[i] &lt;= 107\n\t1 &lt;= k &lt;= 1012\n\n",
        "solution_py": "def canSplit(candies, mid, k):\n    split = 0\n    for i in candies:\n        split += i//mid\n    if split >= k:\n        return True\n    else:\n        return False\n\nclass Solution:\n    def maximumCandies(self, candies: List[int], k: int) -> int:\n        end = sum(candies)//k\n        start = 1\n        ans = 0\n        while start <= end:\n            mid = (start + end)//2\n            if canSplit(candies, mid, k):\n                start = mid + 1\n                ans = mid\n            else:\n                end = mid - 1\n        return ans",
        "solution_js": "var maximumCandies = function(candies, k) {\n    const n = candies.length;\n    \n    let left = 1;\n    let right = 1e7 + 1;\n    \n    while (left < right) {\n        const mid = (left + right) >> 1;\n        const pilesAvail = divideIntoPiles(mid);\n\n        if (pilesAvail < k) right = mid;\n        else left = mid + 1;\n    }\n    \n    return right - 1;\n    \n    \n    function divideIntoPiles(pileSize) {\n        let piles = 0;\n        \n        for (let i = 0; i < n; ++i) {\n            const count = candies[i];\n            \n            piles += Math.floor(count / pileSize);\n        }\n        \n        return piles;\n    }\n};",
        "solution_java": "class Solution {\n    public boolean canSplit(int[] candies, long k, long mid) {\n        long split = 0;\n        for(int i = 0; i < candies.length; ++i) {\n            split += candies[i]/mid;\n        }   \n        if(split >= k)\n            return true;\n        else\n            return false;\n    }\n    \n    public int maximumCandies(int[] candies, long k) {\n        long sum = 0;\n        for(int i = 0; i < candies.length; ++i) {\n            sum += candies[i];\n        }\n        long start = 1, end = sum;\n        long ans = 0;\n        while(start <= end) {\n            long mid = (start + end)/2;\n            if(canSplit(candies, k, mid)) {\n                ans = mid;\n                start = mid + 1;\n            } else {\n                end = mid-1;\n            }\n        }\n        return (int)ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canSplit(vector<int>& candies, long long k, long long mid) {\n        long long split = 0;\n        for(int i = 0; i < candies.size(); ++i) {\n            split += candies[i]/mid;\n        }   \n        if(split >= k)\n            return true;\n        else\n            return false;\n    }\n    \n    int maximumCandies(vector<int>& candies, long long k) {\n        long long sum = 0;\n        for(int i = 0; i < candies.size(); ++i) {\n            sum += candies[i];\n        }\n        long long start = 1, end = sum/k;\n        long long ans = 0;\n        while(start <= end) {\n            long long mid = (start + end)/2;\n            if(canSplit(candies, k, mid)) {\n                ans = mid;\n                start = mid + 1;\n            } else {\n                end = mid-1;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Steps to Reduce a Number to Zero",
        "algo_input": "Given an integer num, return the number of steps to reduce it to zero.\n\nIn one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.\n\n&nbsp;\nExample 1:\n\nInput: num = 14\nOutput: 6\nExplanation:&nbsp;\nStep 1) 14 is even; divide by 2 and obtain 7.&nbsp;\nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3.&nbsp;\nStep 4) 3 is odd; subtract 1 and obtain 2.&nbsp;\nStep 5) 2 is even; divide by 2 and obtain 1.&nbsp;\nStep 6) 1 is odd; subtract 1 and obtain 0.\n\n\nExample 2:\n\nInput: num = 8\nOutput: 4\nExplanation:&nbsp;\nStep 1) 8 is even; divide by 2 and obtain 4.&nbsp;\nStep 2) 4 is even; divide by 2 and obtain 2.&nbsp;\nStep 3) 2 is even; divide by 2 and obtain 1.&nbsp;\nStep 4) 1 is odd; subtract 1 and obtain 0.\n\n\nExample 3:\n\nInput: num = 123\nOutput: 12\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def numberOfSteps(self, num: int) -> int:\n        count=0\n        while num:\n            if num%2:\n                num=num-1\n            else:\n                num=num//2\n            count+=1\n        return count",
        "solution_js": "var numberOfSteps = function(num) {\n    let steps = 0\n    while (num > 0) {\n        if (num % 2 === 0) {\n            num = num/2\n            steps++\n        }\n\n        if (num % 2 === 1) {\n            num--\n            steps++\n        }\n    }\n\n    return steps\n\n};",
        "solution_java": "class Solution {\n    public int numberOfSteps(int num) {\n        return helper(num,0);\n    }\n    public int helper(int n,int c){\n        if(n==0) return c;\n        if(n%2==0){              //check for even no.\n            return helper(n/2,c+1);\n        }\n        \n        return helper(n-1,c+1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfSteps(int num) {\n        int count = 0;\n        while (num > 0)\n        {\n            if (num % 2==0)\n            {\n                num = num/2;\n                count++;\n            }\n            else\n            {\n                if(num > 1)\n                {\n                    num -= 1;\n                    count++;\n                }\n                else\n                {\n                    count++;\n                    break;\n                }\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Number of Flowers in Full Bloom",
        "algo_input": "You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.\n\nReturn an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.\n\n&nbsp;\nExample 1:\n\nInput: flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]\nOutput: [1,2,2,2]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\nExample 2:\n\nInput: flowers = [[1,10],[3,3]], persons = [3,3,2]\nOutput: [2,2,1]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= flowers.length &lt;= 5 * 104\n\tflowers[i].length == 2\n\t1 &lt;= starti &lt;= endi &lt;= 109\n\t1 &lt;= persons.length &lt;= 5 * 104\n\t1 &lt;= persons[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n        #we ADD flowers in the order in which they start, but we remove them in the order they \n        #end.  For this reason, we sort the flowers by starting time but put them in a heap, \n        #in which we remove them by ending time\n        starts = sorted(flowers) #keep flowers untouched in case array should be constant\n        blooming = [] #heap of active flowers\n        answer = [-1] * len(people) #output array\n        hours = [(people[i], i) for i in range(len(people))] #the people, ordered and indexed by their time\n        hours.sort()\n\n        i = 0 #going through starts\n        for hour, person in hours:\n            #add all flowers that have started\n            while i < len(starts) and starts[i][0] <= hour:\n                heappush(blooming, (starts[i][1], starts[i][0]))\n                i += 1\n            #now remove all flowers that have ended.  Note that we only care about the absolute smallest, \n            #and in python minheaps, that is always the first element - even if no other element's order \n            #is guaranteed\n            while blooming and blooming[0][0] < hour: #as long as the soonest to end blooming flower hasn't already stopped\n                heappop(blooming)\n            answer[person] = len(blooming)\n        \n        return answer",
        "solution_js": "/**\n * @param {number[][]} flowers\n * @param {number[]} persons\n * @return {number[]}\n */\nvar fullBloomFlowers = function(flowers, persons) {\n    // *** IDEATION *** //\n    // key observation:\n    // total number of flowers see on day i =\n    // number of flowers has already bloomed so far on day i - number of flowers already ended (\"died\") prior to day i\n\n    // find number of flowers already bloomed on day i\n    // each flower has a start day\n    // start array = [1, 3, 9, 4] for example\n    // on day 8, there are 3 flowers bloomed:\n    // equivalent to find the number of elements in the \"start\" array which is less than or equal to 8\n\n    // find number of flowers already ended on day i\n    // each flower has an end day\n    // end array = [6, 7, 12, 13] for example\n    // on day 8, there are 2 flowers already ended:\n    // equivalent to find the number of elements in the \"end\" array which is less than 8\n    // equivalent to find the number of elements in the \"end\" array which is less than or equal to 7\n\n    // both process above can be solved efficiently with binary search on a sorted array\n    // hence we need to first build 2 array \"start\" and \"end\" and sorted it\n    // then apply the formula at the beginning to return the required answer\n\n    // *** IMPLEMENTATION *** //\n    // step 1: build the \"start\" and \"end\" array\n    let start = [];\n    let end = [];\n\n    for (let i = 0; i < flowers.length; i++) {\n        start[i] = flowers[i][0];\n        end[i] = flowers[i][1];\n    }\n\n    // step 2: sort the \"start\" and \"end\" array\n    start.sort((a, b) => a - b);\n    end.sort((a, b) => a - b);\n\n    // step 3: apply the observation formula using a binarySearch function\n    let res = [];\n    for (let j = 0; j < persons.length; j++) {\n        res[j] = binarySearch(start, persons[j]) - binarySearch(end, persons[j] - 1);\n    }\n    return res;\n\n    // step 4: implement the binarySearch function (variant from standard binarySearch)\n    function binarySearch(array, k) {\n        // array is sorted;\n        // obj is to find the number of elements in array which is less than or equal to \"k\"\n        let left = 0;\n        let right = array.length - 1;\n        let index = -1;\n\n        while (left <= right) {\n            let mid = left + Math.floor((right - left) / 2);\n            if (k < array[mid]) {\n                right = mid - 1;\n            } else {\n                index = Math.max(index, mid); // record the index whenever k >= array[mid]\n                left = mid + 1;\n            }\n        }\n\n        // all elements with in array from position '0' to position 'index' will be less than or equal to k\n        return index + 1;\n    }\n};",
        "solution_java": "class Solution {\npublic int[] fullBloomFlowers(int[][] flowers, int[] persons) {\n        int n = persons.length;\n        int[] result = new int[n];\n\n        TreeMap<Integer, Integer> treeMap = new TreeMap<>();\n        // See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clean-Code\n        for (int[] flower : flowers) {\n            treeMap.put(flower[0], treeMap.getOrDefault(flower[0], 0) + 1);\n            // use end + 1 instead of end\n            treeMap.put(flower[1] + 1, treeMap.getOrDefault(flower[1] + 1, 0) - 1);\n        }\n\n        TreeMap<Integer, Integer> sum = new TreeMap<>();\n        int prev = 0;\n        for (Map.Entry<Integer, Integer> entry : treeMap.entrySet()) {\n            prev += entry.getValue();\n            sum.put(entry.getKey(), prev);\n        }\n\n        for (int i = 0; i < n; i++) {\n            Map.Entry<Integer, Integer> entry = sum.floorEntry(persons[i]);\n            // if entry is null then result[i] = 0\n            if (entry != null) result[i] = entry.getValue();\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) {\n        vector<vector<int>> line; \n        for (auto& f : flowers) {\n            line.push_back({f[0], +1}); \n            line.push_back({f[1]+1, -1}); \n        }\n        sort(line.begin(), line.end()); \n        int prefix = 0; \n        vector<int> time, vals; \n        for (auto& l : line) {\n            time.push_back(l[0]); \n            vals.push_back(prefix += l[1]); \n        }\n        vector<int> ans; \n        for (auto& p : persons) {\n            auto it = upper_bound(time.begin(), time.end(), p); \n            if (it == time.begin()) ans.push_back(0); \n            else ans.push_back(vals[it - time.begin() - 1]); \n        }\n        return ans; \n    }\n};"
    },
    {
        "title": "H-Index",
        "algo_input": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.\n\nAccording to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.\n\nIf there are several possible values for h, the maximum one is taken as the h-index.\n\n&nbsp;\nExample 1:\n\nInput: citations = [3,0,6,1,5]\nOutput: 3\nExplanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\nExample 2:\n\nInput: citations = [1,3,1]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tn == citations.length\n\t1 &lt;= n &lt;= 5000\n\t0 &lt;= citations[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def hIndex(self, citations: List[int]) -> int:\n        num = sorted(citations)\n        h = 0\n        j = len(num)-1\n        for i in range(len(num)):\n            if i+1 <=num[i] and j-i+1>=num[i]:\n                h =max(num[i],h)\n            elif i+1 <= num[i] and j-i+1<num[i]:\n                h = max(h,j-i+1)\n            elif i+1 > num[i] and j-i+1 >=num[i]:\n                h = max(h, num[i])\n            \n        return h",
        "solution_js": "var hIndex = function(citations) {\n    citations.sort((a,b)=>b-a)\n    let i=0\n    while(citations[i]>i) i++\n\n    return i\n};",
        "solution_java": "class Solution {\n    public int hIndex(int[] citations) {\n        int n = citations.length;\n        Arrays.sort(citations);\n        for(int i = 0; i < n; i++) {\n            int hlen = (n-1) - i + 1;\n            if(citations[i] >= hlen) {\n                return hlen;\n            }\n        }\n        return 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int hIndex(vector<int>& citations) {\n        sort(citations.begin(),citations.end(),greater<int>());\n        int ans=0;\n        for(int i=0;i<citations.size();i++){\n            if(citations[i]>=i+1) ans=i+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Binary Tree Level Order Traversal II",
        "algo_input": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[15,7],[9,20],[3]]\n\n\nExample 2:\n\nInput: root = [1]\nOutput: [[1]]\n\n\nExample 3:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 2000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:\n        def dfs(node, level, result):\n            if not node:\n                return\n            if level >= len(result):\n                result.append([])\n            result[level].append(node.val)\n            dfs(node.left, level+1, result)\n            dfs(node.right, level+1, result)\n        result = []\n        dfs(root, 0, result)\n        return result[::-1]",
        "solution_js": "var levelOrderBottom = function(root) {\n    let solution = []\n    function dfs(node, level) {\n        if(!node) return null\n\n        if(!solution[level]) solution[level] = []\n        solution[level].push(node.val)\n\n        dfs(node.left, level + 1)\n        dfs(node.right, level + 1)\n    }\n    dfs(root, 0)\n    return solution.reverse()\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public List<List<Integer>> levelOrderBottom(TreeNode root) {\n        Queue<TreeNode> al=new LinkedList<>();\n        List<List<Integer>> fal=new LinkedList<>();\n        if(root==null) return fal;\n        al.offer(root);\n        while(!al.isEmpty()){\n            List<Integer> aal=new LinkedList<>();\n            int num=al.size();\n            for(int i=0;i<num;i++){\n                if(al.peek().left != null){\n                    al.offer(al.peek().left);\n                }\n                if( al.peek().right != null){\n                    al.offer(al.peek().right);\n                }\n                aal.add(al.poll().val);\n            }\n            fal.add(0,aal);\n        }\n        return fal;\n    }\n}",
        "solution_c": "class Solution {\n    void dft(TreeNode* root, int level, map<int,vector<int>,std::greater<int>>& levelVals)\n    {\n        if (root == nullptr)\n            return;\n        \n        if (levelVals.find(level) == levelVals.end())\n            levelVals[level] = {root->val};\n        else\n            levelVals[level].push_back(root->val);\n        \n        dft(root->left,level+1,levelVals);\n        dft(root->right,level+1,levelVals);\n    }\npublic:\n    vector<vector<int>> levelOrderBottom(TreeNode* root) {\n        map<int,vector<int>,std::greater<int>> levelVals;\n        dft(root,0,levelVals);\n        \n        vector<vector<int>> res;\n        for (const auto& [level,vals] : levelVals)\n            res.push_back(vals);\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Count Good Nodes in Binary Tree",
        "algo_input": "Given a binary tree root, a node X in the tree is named&nbsp;good if in the path from root to X there are no nodes with a value greater than X.\n\nReturn the number of good nodes in the binary tree.\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [3,1,4,3,null,1,5]\nOutput: 4\nExplanation: Nodes in blue are good.\nRoot Node (3) is always a good node.\nNode 4 -&gt; (3,4) is the maximum value in the path starting from the root.\nNode 5 -&gt; (3,4,5) is the maximum value in the path\nNode 3 -&gt; (3,1,3) is the maximum value in the path.\n\nExample 2:\n\n\n\nInput: root = [3,3,null,4,2]\nOutput: 3\nExplanation: Node 2 -&gt; (3, 3, 2) is not good, because \"3\" is higher than it.\n\nExample 3:\n\nInput: root = [1]\nOutput: 1\nExplanation: Root is considered as good.\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the binary tree is in the range&nbsp;[1, 10^5].\n\tEach node's value is between [-10^4, 10^4].\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def goodNodes(self, root: TreeNode) -> int:\n        \n        def dfs(node,maxVal):\n            if not node:\n                return 0\n            res=1 if node.val>=maxVal else 0\n            maxVal=max(maxVal,node.val)\n            res+=dfs(node.left,maxVal)\n            res+=dfs(node.right,maxVal)\n            return res\n        return dfs(root,root.val)",
        "solution_js": "var goodNodes = function(root) {\n    let ans = 0;\n    const traverse = (r = root, mx = root.val) => {\n        if(!r) return;\n        if(r.val >= mx) {\n            ans++;\n        }\n        let childMax = Math.max(mx, r.val);\n        traverse(r.left, childMax);\n        traverse(r.right, childMax);\n    }\n    traverse();\n    return ans;\n};",
        "solution_java": "class Solution {\n    int ans = 0;\n    public int goodNodes(TreeNode root) {\n        if (root == null) return 0;\n        dfs(root, root.val);\n        return ans;\n    }\n\n    void dfs(TreeNode root, int mx) {\n        if (root == null) return;\n\n        mx = Math.max(mx, root.val);\n        if(mx <= root.val) ans++;\n\n        dfs(root.left, mx);\n        dfs(root.right, mx);\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int count=0;\n    void sol(TreeNode* root,int gr){\n        if(!root)return;  // base condition \n       \n        if(gr<=root->val){  //check point max element increase count\n            gr=max(gr,root->val);\n            count++;\n        }\n        \n        if(root->left) sol(root->left,gr);\n        if(root->right) sol(root->right,gr);\n        \n    }\n    int goodNodes(TreeNode* root) {\n        \n        if(!root->left && !root->right) return 1; //check for if there is one node\n        int gr=root->val;\n        sol(root,gr);\n        return count;\n        \n    }\n};"
    },
    {
        "title": "Cheapest Flights Within K Stops",
        "algo_input": "There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.\n\nYou are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\nOutput: 700\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\n\n\nExample 2:\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput: 200\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\n\n\nExample 3:\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput: 500\nExplanation:\nThe graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\t0 &lt;= flights.length &lt;= (n * (n - 1) / 2)\n\tflights[i].length == 3\n\t0 &lt;= fromi, toi &lt; n\n\tfromi != toi\n\t1 &lt;= pricei &lt;= 104\n\tThere will not be any multiple flights between two cities.\n\t0 &lt;= src, dst, k &lt; n\n\tsrc != dst\n\n",
        "solution_py": "class Solution:\n\tdef findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n\t\tgraph = defaultdict(list)\n\t\tfor u,v,w in flights: graph[u].append((v,w))\n\n\t\tpq = [(0,src,0)]\n\t\tdis = [float('inf')]*n\n\n\t\twhile pq:\n\t\t\tc,n,l = heappop(pq)\n\t\t\tif n==dst: return c\n\t\t\tif l > k or l>= dis[n]: continue\n\t\t\tdis[n] = l\n\t\t\tfor v,w in graph[n]:\n\t\t\t\theappush(pq,(c+w,v,l+1))\n\t\treturn -1",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} flights\n * @param {number} src\n * @param {number} dst\n * @param {number} k\n * @return {number}\n */\nconst MAX_PRICE=Math.pow(10,8);\nvar findCheapestPrice = function(n, flights, src, dst, k) {\n    let prev=[];\n    let step=0;\n    let curr=[];\n    for(let i=0;i<n;i++){\n        prev[i]=MAX_PRICE;\n    }\n    prev[src]=0;\n    while(step-1<k){\n      curr=[...prev];\n        let isAnyChange=false;\n        for(let i=0;i<flights.length;i++){\n            let [src,dst,p]=flights[i];\n            if(prev[src]>=MAX_PRICE)continue;\n            let totalCostToReachDst=prev[src]+p;\n            curr[dst]=Math.min(curr[dst],totalCostToReachDst);\n        }\n        step++;\n        prev=curr;\n        \n    }\n    return prev[dst]>=MAX_PRICE?-1:prev[dst];\n    \n};",
        "solution_java": "class Solution {\n    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n       // Initialize Prices arr with infinity & src 0\n        int[] prices = new int[n];\n        for(int i = 0; i < n; i++)\n            prices[i] = Integer.MAX_VALUE;\n        prices[src] = 0;\n        \n        // Build Adj list {key: src | val: dst+price}\n        Map<Integer, List<int[]>> flightsMap = new HashMap<>();\n        for(int[] flight : flights){\n            int flightSrc = flight[0];\n            int flightDst = flight[1];\n            int flightPrice = flight[2];\n            \n            List<int[]> flightsList = flightsMap.getOrDefault(flightSrc, new ArrayList<>());\n            flightsList.add(new int[]{flightDst, flightPrice});\n            flightsMap.put(flightSrc, flightsList);\n        }\n        \n        // Start Bellman ford Algo\n        Queue<Integer> q = new LinkedList<>();\n        q.offer(src);\n        while(k >= 0 && !q.isEmpty()){\n            int[] tempPrices = new int[n];                  // Temporary Prices Arr\n            for(int i = 0; i < n; i++)\n                tempPrices[i] = prices[i];\n            \n            int size = q.size();\n            for(int i = 0; i < size; i++){\n                int curSrc = q.poll();\n                int curPrice = prices[curSrc];\n                List<int[]> curFlightsList = flightsMap.getOrDefault(curSrc, new ArrayList<>());\n                for(int[] flight : curFlightsList){\n                    int flightDst = flight[0];\n                    int flightPrice = flight[1];\n                    int newPrice = curPrice + flightPrice;\n                    if(newPrice < tempPrices[flightDst]){\n                        tempPrices[flightDst] = newPrice;\n                        q.offer(flightDst);\n                    }\n                }\n            }\n            for(int i = 0; i < n; i++)                    // Copy Temp Prices to Original Price Arr\n                prices[i] = tempPrices[i];\n            k--;\n        }\n        int totalPrice = prices[dst];\n        return totalPrice == Integer.MAX_VALUE? -1 : totalPrice;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    #define f first\n    #define s second\n    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k){\n        priority_queue< array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;\n        unordered_map<int, vector<pair<int,int>>> g;\n\n        for(auto& f : flights){\n            g[f[0]].push_back({f[1],f[2]});\n        }\n        vector<int> dis(n,INT_MAX);\n        pq.push({0,src,0});\n        while(!pq.empty()){\n            int c = pq.top()[0];\n            int cur = pq.top()[1];\n            int lvl = pq.top()[2];\n            pq.pop();\n            if(cur==dst) return c;\n            if(lvl > k || lvl >= dis[cur]) continue;\n            dis[cur] = lvl;\n            for(auto& nei : g[cur]){\n                pq.push({c+nei.s, nei.f, lvl+1});\n            }\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Restore IP Addresses",
        "algo_input": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.\n\n\n\tFor example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\", \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses.\n\n\nGiven a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.\n\n&nbsp;\nExample 1:\n\nInput: s = \"25525511135\"\nOutput: [\"255.255.11.135\",\"255.255.111.35\"]\n\n\nExample 2:\n\nInput: s = \"0000\"\nOutput: [\"0.0.0.0\"]\n\n\nExample 3:\n\nInput: s = \"101023\"\nOutput: [\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 20\n\ts consists of digits only.\n\n",
        "solution_py": "class Solution:\n    def restoreIpAddresses(self, s: str):\n        def isValid(st):\n            if(len(st)!=len(str(int(st)))):\n                return False\n            st = int(st)\n            if(st>255 or st<0):\n                return False\n            return True\n        \n        validIps = []\n        for i in range(1,4):\n            s1 = s[:i]\n            if(not isValid(s1)):\n                continue\n            for j in range(i+1, min(len(s), i+4)):\n                s2 = s[i:j]\n                if(not isValid(s2)):\n                    continue\n                for k in range(j+1,min(len(s), j+4)):\n                    s3 = s[j:k]\n                    if(not isValid(s3)):\n                        continue\n                    s4 = s[k:]\n                    if(not isValid(s4)):\n                        continue\n                    currentIp = s1+\".\"+s2+\".\"+s3+\".\"+s4\n                    validIps.append(currentIp)\n        return validIps",
        "solution_js": "var restoreIpAddresses = function(s) {\n    const results = [];\n\n    const go = (str, arr) => {\n        // if we used every character and have 4 sections, it's a good IP!\n        if (str.length === 0 && arr.length === 4) {\n            results.push(arr.join('.'));\n            return;\n        }\n        // we already have too many in the array, let's just stop\n        if (arr.length >= 4) {\n            return;\n        }\n        // chop off next 3 characters and continue recursing\n        if (str.length > 2 && +str.substring(0, 3) < 256 && +str.substring(0, 3) > 0 && str[0] !== '0') {\n            go(str.slice(3), [...arr, str.substring(0, 3)]);\n        }\n        // chop off next 2 characters and continue recursing\n        if (str.length > 1 && +str.substring(0, 2) > 0 && str[0] !== '0') {\n            go(str.slice(2), [...arr, str.substring(0, 2)]);\n        }\n        // chop off next 1 character and continue recursing, in this case, starting with 0 is OK\n        if (str.length > 0 && +str.substring(0, 1) >= 0) {\n            go(str.slice(1), [...arr, str.substring(0, 1)]);\n        }\n        return;\n    }\n\n    go(s, []);\n\n    return results;\n};",
        "solution_java": "class Solution {\n    public List<String> restoreIpAddresses(String s) {\n        List<String> ans = new ArrayList<>();\n\n        int len = s.length();\n        for(int i = 1; i < 4 && i < len-2 ; i++ ){\n            for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){\n                for(int k = j+1 ; k < j + 4 && k < len ; k++){\n                  String s1 = s.substring(0,i);\n                  String s2 = s.substring(i,j);\n                  String s3 = s.substring(j,k);\n                  String s4 = s.substring(k,len);\n                  if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))\n                      ans.add(s1+\".\"+s2+\".\"+s3+\".\"+s4);\n                }\n            }\n        }\n        return ans;\n    }\n    boolean isValid(String s){\n        if(s.length() > 3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s) > 255)\n           return false;\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> res;\n    void dfs(string s,int idx,string curr_ip,int cnt)\n    {\n        if(cnt>4)\n            return;\n        if(cnt==4&&idx==s.size())\n        {\n            res.push_back(curr_ip);\n           // return;\n        }\n        for(int i=1;i<4;i++)\n        {\n            if(idx+i>s.size())\n                break;\n            string str=s.substr(idx,i);\n            if((str[0]=='0'&&str.size()>1)||(i==3&&stoi(str)>=256))\n                continue;\n            dfs(s,idx+i,curr_ip+str+(cnt==3?\"\":\".\"),cnt+1);\n        }\n    }\n    vector<string> restoreIpAddresses(string s)\n    {\n        dfs(s,0,\"\",0);\n        return res;\n        \n        \n    }\n};"
    },
    {
        "title": "Split Array into Consecutive Subsequences",
        "algo_input": "You are given an integer array nums that is sorted in non-decreasing order.\n\nDetermine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:\n\n\n\tEach subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).\n\tAll subsequences have a length of 3 or more.\n\n\nReturn true if you can split nums according to the above conditions, or false otherwise.\n\nA subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,3,4,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,5] --&gt; 1, 2, 3\n[1,2,3,3,4,5] --&gt; 3, 4, 5\n\n\nExample 2:\n\nInput: nums = [1,2,3,3,4,4,5,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --&gt; 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --&gt; 3, 4, 5\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,4,5]\nOutput: false\nExplanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-1000 &lt;= nums[i] &lt;= 1000\n\tnums is sorted in non-decreasing order.\n\n",
        "solution_py": "class Solution:\n\n    from collections import defaultdict\n\n    def isPossible(self, nums):\n        # If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.\n        if len(nums) < 3:\n            return False\n\n        # 'count' dictionary stores the frequency of each number in the input array.\n        count = defaultdict(int)\n\n        # 'tails' dictionary stores the number of subsequences that end at a certain number.\n        tails = defaultdict(int)\n\n        # Populate the 'count' dictionary with the frequency of each number.\n        for num in nums:\n            count[num] += 1\n\n        # Iterate through the input array.\n        for num in nums:\n            # If the count of the current number is 0, it means this number has already been used in a subsequence.\n            if count[num] == 0:\n                continue\n            # If there is a subsequence that ends with the current number minus 1,\n            # it means we can extend that subsequence by adding the current number.\n            elif tails[num - 1] > 0:\n                tails[num - 1] -= 1  # Decrease the count of the tails that end with the current number minus 1.\n                tails[num] += 1  # Increase the count of the tails that end with the current number.\n            # If there are enough numbers after the current number to form a subsequence,\n            # create a new subsequence starting with the current number.\n            elif count[num + 1] > 0 and count[num + 2] > 0:\n                count[num + 1] -= 1  # Decrease the count of the next number.\n                count[num + 2] -= 1  # Decrease the count of the number after the next number.\n                tails[num + 2] += 1  # Increase the count of the tails that end with the number after the next number.\n            else:\n                # If we can't extend an existing subsequence or start a new one, return False.\n                return False\n\n            # Decrease the count of the current number since it's used in a subsequence.\n            count[num] -= 1\n\n        # If the function successfully iterates through the entire array, return True.\n        return True",
        "solution_js": "var isPossible = function(nums) {\n\tconst need = new Map();\n\tconst hash = nums.reduce((map, num) => {\n\t\tconst count = map.get(num) ?? 0;\n\t\tmap.set(num, count + 1);\n\t\treturn map;\n\t}, new Map());\n\n\tfor (const num of nums) {\n\t\tconst current = hash.get(num);\n\t\tif (current === 0) continue;\n\n\t\tconst currentNeed = need.get(num);\n\t\tconst next1 = hash.get(num + 1);\n\t\tconst next2 = hash.get(num + 2);\n\t\tif (currentNeed > 0) {\n\t\t\tconst need1 = need.get(num + 1) ?? 0;\n\t\t\tneed.set(num, currentNeed - 1);\n\t\t\tneed.set(num + 1, need1 + 1);\n\t\t} else if (next1 > 0 && next2 > 0) {\n\t\t\tconst need3 = need.get(num + 3) ?? 0;\n\t\t\thash.set(num + 1, next1 - 1);\n\t\t\thash.set(num + 2, next2 - 1);\n\t\t\tneed.set(num + 3, need3 + 1);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\thash.set(num, current - 1);\n\t}\n\treturn true;\n};",
        "solution_java": "class Solution {\n  public boolean isPossible(int[] nums) {\n    int[] freq = new int[2002], subEnd = new int[2002];\n    for (int i : nums) {\n      int num = i + 1001;\n      freq[num]++;\n    }\n    for (int i : nums) {\n      int num = i + 1001;\n      if (freq[num] == 0) continue; // Num already in use\n      freq[num]--;\n      if (subEnd[num - 1] > 0) { // Put into existing subsequence\n        subEnd[num - 1]--;\n        subEnd[num]++;\n      }\n      // New subsequence of size 3 is possible\n      else if (freq[num + 1] > 0 && freq[num + 2] > 0) {\n        freq[num + 1]--;\n        freq[num + 2]--;\n        subEnd[num + 2]++; // New subsequence\n      } else return false;\n    }\n    return true;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPossible(vector<int>& nums) {\n        priority_queue<int, vector<int>, greater<int>> pq;\n        unordered_map<int, int> um;\n        for(int &num : nums)\n        {\n            pq.push(num);\n            um[num]++;\n        }\n        queue<int> q;\n        int count = 0, prev;\n        while(!pq.empty())\n        {\n            if(count == 0)\n            {\n                prev = pq.top();\n                pq.pop();\n                count++;\n            }\n            else if(pq.top() == prev+1)\n            {\n                if(um[pq.top()] >= um[prev])\n                {\n                    um[prev]--;\n                    pq.pop();\n                    prev += 1;\n                    count++;\n                }\n                else if(um[pq.top()] < um[prev])\n                {\n                    um[prev]--;\n                    if(count <= 2) return false;\n                    while(!q.empty())\n                    {\n                        pq.push(q.front());\n                        q.pop();\n                    }\n                    count = 0;\n                }\n            }\n            else if(pq.top() == prev)\n            {\n                q.push(pq.top());\n                pq.pop();\n                if(pq.empty())\n                {\n                    if(count <= 2) return false;\n                    while(!q.empty())\n                    {\n                        pq.push(q.front());\n                        q.pop();\n                    }\n                    count = 0;\n                }\n            }\n            else if(pq.top() > prev+1)\n            {\n                if(count <= 2) return false;\n\n                while(!q.empty())\n                {\n                    pq.push(q.front());\n                    q.pop();\n                }\n                count = 0;\n            }\n        }\n        if(count > 0 && count <= 2) return false;\n        return true;\n    }\n};"
    },
    {
        "title": "Equal Sum Arrays With Minimum Number of Operations",
        "algo_input": "You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.\n\nReturn the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n\n\nExample 2:\n\nInput: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput: -1\nExplanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\n\n\nExample 3:\n\nInput: nums1 = [6,6], nums2 = [1]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 105\n\t1 &lt;= nums1[i], nums2[i] &lt;= 6\n\n",
        "solution_py": "class Solution:\n    def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n        \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n        sum1 = sum(nums1)\n        sum2 = sum(nums2)\n        \n        if sum1==sum2:\n            return 0\n        elif sum1>sum2:\n            larger_sum_nums = nums1\n            smaller_sum_nums = nums2\n        else:\n            larger_sum_nums = nums2\n            smaller_sum_nums = nums1\n\t\t\n        sum_diff = abs(sum1-sum2)\n            \n        # step2. calculate the max \"gain\" at each position (how much difference we can reduce if operating on that position)    \n        gains_in_larger_array = [num-1 for num in larger_sum_nums]\n        gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n        \n\t\t# step3. sort the \"gain\" and check the least number of steps to reduce the difference to 0\n        gains = gains_in_larger_array + gains_in_smaller_array\n        gains.sort(reverse = True)\n        \n        count = 0\n        target_diff = sum_diff\n        \n        for i in range(len(gains)):\n            target_diff -= gains[i]\n            count += 1\n            \n            if target_diff <= 0:\n                return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n        return -1",
        "solution_js": "var minOperations = function(nums1, nums2) {\n    /*\n    Two impossible cases:\n    min1...max1 ... min2...max2 -> we can't make them equal\n    min2...max2 ... min1...max1 -> we can't make them equal\n    */\n    let min1 = nums1.length * 1;\n    let max1 = nums1.length * 6;\n    let min2 = nums2.length * 1;\n    let max2 = nums2.length * 6;\n    if (min2 > max1 || min1 > max2) {\n        return -1;\n    }\n    let sum1 = nums1.reduce((acc,cur) => acc + cur);\n    let sum2 = nums2.reduce((acc,cur) => acc + cur);\n    if (sum1 === sum2) return 0;\n    if (sum1 < sum2) {\n        return helper(nums1, nums2, sum1, sum2);\n    } else {\n        return helper(nums2, nums1, sum2, sum1);\n    }\n    // T.C: O(M + N), M = # of nums1, N = # of nums2\n    // S.C: O(1)\n};\n\n// Condition: sum of A < sum of B\n// the idea is to add the maximum possible value to sumA and\n// subtract the maximum possible value from sumB so that\n// we make sumA >= sumB as soon as possible\nfunction helper(A, B, sumA, sumB) {\n    let freqA = new Array(7).fill(0);\n    let freqB = new Array(7).fill(0);\n    for (let i = 0; i < A.length; i++) {\n        freqA[A[i]]++;\n    }\n    for (let i = 0; i < B.length; i++) {\n        freqB[B[i]]++;\n    }\n    let count = 0;\n    for (let i = 1; i <= 6; i++) {\n        // increase sumA\n        while (freqA[i] > 0 && sumA < sumB) {\n            sumA += 6-i;\n            freqA[i]--;\n            count++;\n        }\n        let j = 7-i;\n        // decrease sumB\n        while (freqB[j] > 0 && sumA < sumB) {\n            sumB -= j-1;\n            freqB[j]--;\n            count++;\n        }\n        if (sumA >= sumB) break;\n    }\n    return count;\n}",
        "solution_java": "class Solution {\n    public int minOperations(int[] nums1, int[] nums2) {\n        int m = nums1.length, n = nums2.length;\n        if (m > 6 * n || n > 6 * m) return -1;\n\n        int sum1 = 0, sum2 = 0;\n        for (int i : nums1) sum1 += i;\n        for (int i : nums2) sum2 += i;\n\n        int diff = sum1 - sum2;\n        if (diff == 0) return 0;\n\n        return (diff > 0 ? helper(nums1, nums2, diff)\n                         : helper(nums2, nums1, -diff));\n    }\n\n    private int helper(int[] nums1, int[] nums2, int diff) {\n        // count[i] : frequency of numbers that can reduce the diff by i\n        int[] count = new int[6];\n        for (int num : nums1) count[num - 1]++;\n        for (int num : nums2) count[6 - num]++;\n\n        int res = 0;\n        for (int i = 5; i > 0; i--) {\n            int c = Math.min(count[i], diff / i + (diff % i == 0 ? 0 : 1));\n\n            res += c;\n            diff -= c * i;\n\n            if (diff <= 0) break;\n        }\n        return res;\n    }\n}",
        "solution_c": "/**\n * @brief\n * Given two array, return the minimum numbers we have to change the values to make two arrays sum equal\n *\n * [Observation]\n * Since the value is from 1 ~ 6\n *\n * Min sum of the array = len(arr)\n * Max sum of the array = 6 len(arr)\n *\n * When to arrays range cannot overlap -> no answer\n *\n * If there is a answer -> sum s, value will be between s1 and s2\n * So, let's say if s1 is smaller, we would like to increase s1's element and decrease s2's element\n * -> We only have to design for s1 is smaller than s2.\n *\n * [Key] Which element's should we increase and decrease?\n * To minimize the changing elements, we change the number who can mostly decrease the differences.\n * So, we compare the smallest element in num1 and largest in num2.\n * -> sorting\n *\n * @algo sorting + greedy\n * Time O(NlogN) for sorting\n * Space O(1)\n */\nclass Solution {\npublic:\n    int minOperations(vector<int>& nums1, vector<int>& nums2) {\n        int l1 = nums1.size(); // l1 ~ 6l1\n        int l2 = nums2.size(); // l2 ~ 6l2\n\n        if(6*l1 < l2 || 6*l2 < l1) {\n            return -1;\n        }\n\n        int sum1 = accumulate(nums1.begin(), nums1.end(), 0);\n        int sum2 = accumulate(nums2.begin(), nums2.end(), 0);\n        if(sum1 > sum2) return minOperations(nums2, nums1);\n\n        sort(nums1.begin(), nums1.end());\n        sort(nums2.begin(), nums2.end(), greater<int>());\n        // let us design the way where sum1 <= sum2\n        int ans = 0, ptr1 = 0, ptr2 = 0;\n        int diff = sum2 - sum1;\n\n        while(diff > 0) {\n            if(ptr2 == l2 || ptr1 < l1 && (6 - nums1[ptr1]) >= (nums2[ptr2] - 1)) {\n                diff -= (6 - nums1[ptr1]);\n                ans++;\n                ptr1++;\n            }\n            else {\n                diff -= (nums2[ptr2] - 1);\n                ans++;\n                ptr2++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Arithmetic Subsequence of Given Difference",
        "algo_input": "Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.\n\nA subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,4], difference = 1\nOutput: 4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].\n\nExample 2:\n\nInput: arr = [1,3,5,7], difference = 1\nOutput: 1\nExplanation: The longest arithmetic subsequence is any single element.\n\n\nExample 3:\n\nInput: arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput: 4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t-104 &lt;= arr[i], difference &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def longestSubsequence(self, arr: List[int], difference: int) -> int:\n        d = defaultdict(int)\n        for num in arr:\n            if num - difference in d:\n                d[num] = d[num - difference] + 1\n            else:\n                d[num] = 1\n        return max((d[x] for x in d))",
        "solution_js": "var longestSubsequence = function(arr, difference) {\n    const map = new Map()\n    let max = 0\n    for(let num of arr) {\n        const prev = map.has(num - difference) ? map.get(num -difference) : 0\n        const val = prev + 1\n        map.set(num, val)\n        max = Math.max(max, val)\n    }\n    return max\n};",
        "solution_java": "class Solution {\n    public int longestSubsequence(int[] arr, int difference) {\n        int max = 1;\n        Map<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < arr.length; i++) {\n            // find the target element using the current element and the given difference\n            int target = arr[i] - difference;\n            // find if an AP for the target element exists in map and its length (else default to 1 - each element is an AP)\n            int currAns = map.getOrDefault(target, 0) + 1;\n            // add the current answer to the map\n            // the amswer will override any previous answers with the same key (with an equal or greater answer)\n            // for eg, in this case: .......X.....X\n            // here X is the same number but the 2nd X will have an equal or larger AP sequence (logically)\n            map.put(arr[i], currAns);\n            // get max answer\n            max = Math.max(max, currAns);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestSubsequence(vector<int>& arr, int difference) {\n        \n        int n = arr.size();\n        \n        unordered_map<int,int>mp;\n        multiset<int>s;\n        int ans = 1;\n        \n        for(int i=0;i<n;i++)\n        {\n            int req = arr[i] - difference;\n            auto it = s.find(req);\n            s.insert(arr[i]);\n            \n            if(it == s.end())\n            {\n                continue;    \n            }\n            else\n            {\n                mp[arr[i]] = mp[req] + 1;\n                ans = max(ans,mp[arr[i]] + 1);\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Check If Array Pairs Are Divisible by k",
        "algo_input": "Given an array of integers arr of even length n and an integer k.\n\nWe want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.\n\nReturn true If you can find a way to do that or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput: true\nExplanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).\n\n\nExample 2:\n\nInput: arr = [1,2,3,4,5,6], k = 7\nOutput: true\nExplanation: Pairs are (1,6),(2,5) and(3,4).\n\n\nExample 3:\n\nInput: arr = [1,2,3,4,5,6], k = 10\nOutput: false\nExplanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.\n\n\n&nbsp;\nConstraints:\n\n\n\tarr.length == n\n\t1 &lt;= n &lt;= 105\n\tn is even.\n\t-109 &lt;= arr[i] &lt;= 109\n\t1 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def canArrange(self, arr: List[int], k: int) -> bool:\n        #The idea is to count the residues\n        \n        #If every residue has the counter residue\n        #such that x+y == k,then we found a pair\n        \n        count = [0]*k\n        for num in arr:\n            count[num%k] +=1\n        \n        #Now since we have 0,1,2,.....k-1 as residues\n        #If count[1] == count[k-1],pairs+=count[1]\n        #since we have odd number of complimenting residues,\n        #we should also care about residue=0 and residue=k//2\n        \n        i,j =1,k-1\n        pairs  = 0\n        while i<j :\n            if count[i]!=count[j]:\n                return False\n            pairs += count[i]\n            i+=1\n            j-=1\n        if pairs>0 and i==j:\n            pairs+=count[i]/2\n        pairs+= count[0]/2\n        n = len(arr)\n        return pairs == n//2",
        "solution_js": "var canArrange = function(arr, k) {\n    let map = new Map();\n    let index = 0;\n    for(let i = 0; i < arr.length; i++){\n        let val = arr[i] % k;\n        if(val<0) val+=k;\n        if(map.get(k-val)) map.set(k-val, map.get(k-val) - 1), index--;\n        else if(map.get(-val)) map.set(-val, map.get(-val) - 1), index--;\n        else map.set(val, map.get(val) + 1 || 1), index++;\n    }\n    return !index;\n};",
        "solution_java": "class Solution {\n    public boolean canArrange(int[] arr, int k) {\n        int[] frequency = new int[k];\n        for(int num : arr){\n            num %= k;\n            if(num < 0) num += k;\n            frequency[num]++;\n        }\n        if(frequency[0]%2 != 0) return false;\n        \n        for(int i = 1; i <= k/2; i++)\n            if(frequency[i] != frequency[k-i]) return false;\n\t\t\t\n        return true;\n    }\n}",
        "solution_c": "//ask the interviewer\n//can we have negative values?\n\nclass Solution {\npublic:\n    bool canArrange(vector<int>& arr, int k)\n    {\n        unordered_map<int,int>memo;//remainder : occurence\n\n        //we are storing the frequency of curr%k\n        //i.e. the frequency of the remainder\n        for(auto curr : arr)\n        {\n            int remainder = ((curr%k)+k)%k;\n            memo[remainder]++;\n        }\n\n        for(int i =1; i<=k/2; i++)\n        {\n            if(memo[i] != memo[k-i])\n                return false;\n        }\n        if(memo[0]%2 != 0)\n            return false;\n        return true;\n    }\n};"
    },
    {
        "title": "Power of Four",
        "algo_input": "Given an integer n, return true if it is a power of four. Otherwise, return false.\n\nAn integer n is a power of four, if there exists an integer x such that n == 4x.\n\n&nbsp;\nExample 1:\nInput: n = 16\nOutput: true\nExample 2:\nInput: n = 5\nOutput: false\nExample 3:\nInput: n = 1\nOutput: true\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?",
        "solution_py": "import math \nclass Solution:\n    def isPowerOfFour(self, n: int) -> bool:\n\n        if n <= 0:\n            return False\n        return math.log(n, 4).is_integer()",
        "solution_js": "var isPowerOfFour = function(n) {\n    if(n==1){\n        return true\n    }\n    let a=1;\n    for(let i=2;i<=30;i++){\n        a=a*4\n        if(a===n){\n            return true\n        }\n    }\n    return false\n};",
        "solution_java": "class Solution {\n    public boolean isPowerOfFour(int n) {\n        return (Math.log10(n)/Math.log10(4))%1==0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPowerOfFour(int n) {\n        if(n==1)\n            return true;\n        long long p=1;\n        for(int i=1;i<n;i++)\n        {\n            p=p*4;\n            if(p==n)\n                return true;\n            if(p>n)\n                return false;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Diagonal Traverse II",
        "algo_input": "Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.\n\n&nbsp;\nExample 1:\n\nInput: nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,4,2,7,5,3,8,6,9]\n\n\nExample 2:\n\nInput: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i].length &lt;= 105\n\t1 &lt;= sum(nums[i].length) &lt;= 105\n\t1 &lt;= nums[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t# sort the index of element\n        heap = list()\n        n = len(nums)\n        for i in range(n):\n            m = len(nums[i])\n            for j in range(m):\n                heapq.heappush(heap,[i+j,j,i])\n\t\t\t\t\n\t\t# append the element one by one\n        ans = []\n        while heap:\n            temp = heapq.heappop(heap)\n            ans.append(nums[temp[2]][temp[1]])\n        return ans",
        "solution_js": "var findDiagonalOrder = function(nums) {\n  let vals = []; // [row, diagonal value, actual value]\n  for (let i = 0; i < nums.length; i++) {\n    for (let j = 0; j < nums[i].length; j++) {\n      vals.push([i, i + j, nums[i][j]]);\n    }\n  }\n  vals.sort((a, b) => {\n    if (a[1] === b[1]) return b[0] - a[0];\n    return a[1] - b[1];\n  })\n  return vals.map(val => val[2]);\n};",
        "solution_java": "\tclass Solution {\npublic int[] findDiagonalOrder(List<List<Integer>> nums) {\n    HashMap<Integer , Stack<Integer>> map = new HashMap();\n    \n    for(int i = 0 ; i < nums.size() ; i++){\n        for(int j = 0 ; j < nums.get(i).size() ; j++){\n            int z = i + j;\n            if(map.containsKey(z)){\n                map.get(z).add(nums.get(i).get(j));\n            }else{\n              Stack<Integer> stk = new Stack<>();\n                stk.push(nums.get(i).get(j));\n                map.put(z , stk);\n            }\n        }\n    }\n    ArrayList<Integer> arr = new ArrayList<>();\n    int k = 0;\n    while(true){\n        if(map.containsKey(k)){\n            int size = map.get(k).size();\n            while(size-- > 0){\n                arr.add(map.get(k).pop());\n            }\n            k++;\n        }else{\n            break;\n        }\n    }\n    int[] res = new int[arr.size()];\n    for(int i = 0 ; i < res.length ; i++){\n        res[i] = arr.get(i);\n    }\n    \n    return res;\n}}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n        int n = nums.size();\n        int m = 0;\n        for(vector<int> &v : nums)\n        {\n            int y = v.size();\n            m = max(m, y);\n        }\n        vector<int> D2[n+m-1];\n        for(int i = 0; i < n; i++)\n        {\n            for(int j = 0; j < nums[i].size(); j++)\n            {\n                D2[i+j].push_back(nums[i][j]);\n            }\n        }\n        vector<int> ans;\n        for(int i = 0; i < n+m-1; i++)\n        {\n            int x = D2[i].size();\n            while(x--)\n            {\n                ans.push_back(D2[i][x]);\n                D2[i].pop_back();\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Add Binary",
        "algo_input": "Given two binary strings a and b, return their sum as a binary string.\n\n&nbsp;\nExample 1:\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\nExample 2:\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a.length, b.length &lt;= 104\n\ta and b consist&nbsp;only of '0' or '1' characters.\n\tEach string does not contain leading zeros except for the zero itself.\n\n",
        "solution_py": "class Solution(object):\n    def addBinary(self, a, b):\n        \"\"\"\n        :type a: str\n        :type b: str\n        :rtype: str\n        \"\"\"\n\n        return str(bin(int(a, base = 2)+int(b, base = 2)))[2:]",
        "solution_js": "var addBinary = function(a, b) {\n    let i = a.length-1, j = b.length-1, carry = 0\n    let s =[]\n    while(i >= 0 || j >= 0){\n        let sum = carry\n        if(i >= 0)  sum += a[i--].charCodeAt() - 48\n        if(j >= 0)  sum += b[j--].charCodeAt() - 48\n        s.unshift(sum % 2)\n        carry = ~~(sum/2)\n    }\n    return carry > 0 ? \"1\" + s.join(\"\") : s.join(\"\")\n};",
        "solution_java": "class Solution {\n    public String addBinary(String a, String b) {\n        StringBuilder sb = new StringBuilder();\n        int carry = 0;\n        int i= a.length() -1;\n        int j= b.length() -1;\n        while(i>=0 || j>=0){\n            int sum = carry;\n            if(i>=0)\n                sum+=a.charAt(i--)-'0'; // -'0' is just to convert char in integer\n            if(j>=0)\n                sum+=b.charAt(j--)-'0';\n            sb.append(sum%2);   // If we have sum = 1  1  then = 2 % 2 = 0 and 0  1 = 1 % 2 = 1\n            carry = sum /2;\n        }\n        if(carry>0)\n            sb.append(carry);\n        return sb.reverse().toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string addBinary(string a, string b) {\n        string ans;\n        int i=a.length()-1,j=b.length()-1;\n        int carry=0;\n        while(carry||i>=0||j>=0){\n            if(i>=0){\n                carry+=a[i]-'0';\n                i--;\n            }\n            if(j>=0){\n                carry+=b[j]-'0';\n                j--;\n            }\n            ans+=carry%2+'0';\n            carry=carry/2;\n        }\n        reverse(ans.begin(),ans.end());\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Uncommon Subsequence I",
        "algo_input": "Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1.\n\nAn uncommon subsequence between two strings is a string that is a subsequence of one but not the other.\n\nA subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n\n\n\tFor example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"aebdc\" to get \"abc\". Other subsequences of \"aebdc\" include \"aebdc\", \"aeb\", and \"\" (empty string).\n\n\n&nbsp;\nExample 1:\n\nInput: a = \"aba\", b = \"cdc\"\nOutput: 3\nExplanation: One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.\n\n\nExample 2:\n\nInput: a = \"aaa\", b = \"bbb\"\nOutput: 3\nExplanation:&nbsp;The longest uncommon subsequences are \"aaa\" and \"bbb\".\n\n\nExample 3:\n\nInput: a = \"aaa\", b = \"aaa\"\nOutput: -1\nExplanation:&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a.length, b.length &lt;= 100\n\ta and b consist of lower-case English letters.\n\n",
        "solution_py": "class Solution:\n    def findLUSlength(self, a: str, b: str) -> int:\n        if a == b:\n            return -1\n\n        else:\n            return max(len(a), len(b))",
        "solution_js": "var findLUSlength = function(a, b) {\n    if (a===b) return -1\n    return Math.max(a.length,b.length)\n\n};",
        "solution_java": "class Solution {\n    public int findLUSlength(String a, String b) {\n        if(a.equals(b)) return -1;\n        return Math.max(a.length(),b.length());\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLUSlength(string a, string b) {\n        if(a==b){\n            return -1;\n        }\n        if(a.size()>=b.size()){\n            return a.size();\n        }\n        return b.size();\n    }\n};"
    },
    {
        "title": "Queue Reconstruction by Height",
        "algo_input": "You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.\n\nReconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).\n\n&nbsp;\nExample 1:\n\nInput: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:\nPerson 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\n\n\nExample 2:\n\nInput: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= people.length &lt;= 2000\n\t0 &lt;= hi &lt;= 106\n\t0 &lt;= ki &lt; people.length\n\tIt is guaranteed that the queue can be reconstructed.\n\n",
        "solution_py": "class Solution:\n\tdef reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n\t\tn = len(people)\n\t\tpeople.sort()\n\t\tans = [[]]*n\n\t\ti = 0\n\t\twhile people:\n\t\t\th,p = people.pop(0)\n\t\t\tcount= p\n\t\t\tfor i in range(n):\n\t\t\t\tif count== 0 and ans[i] == []:\n\t\t\t\t\tans[i] = [h,p]\n\t\t\t\t\tbreak\n\n\t\t\t\telif not ans[i] or (ans[i] and ans[i][0] >= h ):\n\t\t\t\t\tcount -= 1\n\t\treturn ans",
        "solution_js": "var reconstructQueue = function(people) {\n    var queue = new Array(people.length);\n    people = people.sort((a,b) => (a[0]-b[0]));\n    for(let i =0;i<people.length;i++){\n        let count = 0;\n        for(let j= 0;j<queue.length;j++){\n            if(!queue[j]){\n                if(count == people[i][1]){\n                    queue[j] = people[i];\n                    break;\n                }\n                count++;\n            }\n            else if( queue[j][0] >= people[i][0]){\n                count++;\n            }\n        }\n    }\n    return queue;\n};",
        "solution_java": "class Solution {\n    public int[][] reconstructQueue(int[][] people) {\n        List<int[]> result = new ArrayList<>(); //return value\n\n        Arrays.sort(people, (a, b) -> {\n            int x = Integer.compare(b[0], a[0]);\n            if(x == 0) return Integer.compare(a[1], b[1]);\n            else return x; });\n\n        for(int[] p: people)\n            result.add(p[1], p);\n\n        return result.toArray(new int[people.length][2]);\n    }\n}",
        "solution_c": "#include <bits/stdc++.h>\n\nusing namespace std;\nstruct node {\n  int h, k;\n  node *next;\n  node(int h, int k) : h(h), k(k), next(nullptr){}\n};\n\nbool cmp(vector<int>& p1, vector<int>& p2) {\n  return (p1[0] != p2[0]) ? (p1[0] > p2[0]) : (p1[1] < p2[1]);\n}\n\nvoid insert(vector<int>& p, node **target) {\n  node *new_p = new node(p[0], p[1]);\n  new_p->next = (*target)->next;\n  (*target)->next = new_p;\n}\n\nclass Solution {\n  public:\n    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {\n      sort(people.begin(), people.end(), cmp);\n      vector<int>& first = people[0];\n      node *head = new node(0, 0);//pseu\n      node **target;\n      int step;\n      for (int i = 0; i < people.size(); i++) {\n        vector<int>& p = people[i];\n        for (target = &head, step=p[1]; step > 0; target=&((*target)->next), step--);\n        insert(p, target);\n      }\n      vector<vector<int>> ans;\n      ans.resize(people.size());\n      int i = 0;\n      for(node *cur = head->next; cur != nullptr; cur = cur->next)\n        ans[i++] = vector<int>({cur->h, cur->k});\n      //formally, we should free the list later.\n      return ans;\n    }\n};"
    },
    {
        "title": "Longest Univalue Path",
        "algo_input": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.\n\nThe length of the path between two nodes is represented by the number of edges between them.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,4,5,1,1,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 5).\n\n\nExample 2:\n\nInput: root = [1,4,5,4,4,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 4).\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-1000 &lt;= Node.val &lt;= 1000\n\tThe depth of the tree will not exceed 1000.\n\n",
        "solution_py": "class Solution:\n\tmax_path=0\n\tdef longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n\t\tself.dfs(root);\n\t\treturn self.max_path\n\n\tdef dfs(self,root):\n\t\tif root is None:return 0\n\t\tleft=self.dfs(root.left)\n\t\tright=self.dfs(root.right)\n\n\t\tif root.left  and  root.left.val == root.val:\n\t\t\tleftPath=left+1\n\t\telse:\n\t\t\tleftPath=0\n\n\t\tif root.right and  root.right.val == root.val:\n\t\t\trightPath=right+1\n\t\telse:\n\t\t\trightPath=0\n\n\t\tself.max_path = max(self.max_path, leftPath + rightPath)\n\t\treturn max(leftPath, rightPath)",
        "solution_js": "var longestUnivaluePath = function(root) {\n\tlet max = 0;\n\tconst dfs = (node = root, parentVal) => {\n\t\tif (!node) return 0;\n\t\tconst { val, left, right } = node;\n\t\tconst leftPath = dfs(left, val);\n\t\tconst rightPath = dfs(right, val);\n\n\t\tmax = Math.max(max, leftPath + rightPath);\n\t\treturn val === parentVal \n\t\t\t? Math.max(leftPath, rightPath) + 1\n\t\t\t: 0;\n\t};\n\n\tdfs();\n\treturn max;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    int maxLen = 0;\n    public int longestUnivaluePath(TreeNode root) {\n        lup(root);\n        return maxLen;\n    }\n    public int lup(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n        int left = lup(root.left);\n        int right = lup(root.right);\n        int leftMax = 0;\n        int rightMax = 0;\n        if (root.left != null && root.val == root.left.val) {\n            leftMax = left + 1;\n        }\n        if (root.right != null && root.val == root.right.val) {\n            rightMax = right + 1;\n        }\n        maxLen = Math.max(maxLen, leftMax + rightMax);\n        return Math.max(leftMax, rightMax);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxlen=0;\n    pair<int,int> util(TreeNode* root,int val ){\n        if(!root)\n            return {0,-1001};\n\n        // in pair we will the first part will return the no nodes ,\n        //and in the second part we will return the value associated with it\n\n        pair<int,int> l=util(root->left,root->val);\n        pair<int,int> r=util(root->right,root->val);\n\n        /* now we will check whether the value coming from\n        the left subtree or(&) right subtree is equal to the\n        value of the current node\n\n         if equal to both the left && right subtree, then the length returned\n        will be max of the left & right subtree , becuase ATQ, we have to\n        return the longest path where each node in the path has the same\n        value , therefore from the current node we can travel to either the\n        left or right subtree , but the maxlength can be l.first+r.first+1 ,\n        because we can travel from the leftmost node through the current\n        node to the rightmost node , which will be a valid path , therefore\n        we will compare this with the maxlength\n\n        */\n        if(l.second==root->val && r.second==root->val){\n          maxlen=max(maxlen,l.first+r.first+1);\n          return {max(l.first,r.first)+1,root->val};\n\n        }\n\n        // now similary checking for all the other nodes:\n\n        else if(l.second==root->val){\n            maxlen=max(maxlen,l.first+1);\n            return {l.first+1,root->val};\n        }\n        else if(r.second==root->val){\n            maxlen=max(maxlen,r.first+1);\n            return {r.first+1,root->val};\n        }\n        else{\n            return {1,root->val};\n        }\n\n    }\n    int longestUnivaluePath(TreeNode* root) {\n        if(!root)\n            return 0;\n        util(root,root->val);\n        return max(maxlen-1,0);\n\n    }\n};"
    },
    {
        "title": "Form Largest Integer With Digits That Add up to Target",
        "algo_input": "Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:\n\n\n\tThe cost of painting a digit (i + 1) is given by cost[i] (0-indexed).\n\tThe total cost used must be equal to target.\n\tThe integer does not have 0 digits.\n\n\nSince the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\".\n\n&nbsp;\nExample 1:\n\nInput: cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput: \"7772\"\nExplanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\nDigit    cost\n  1  -&gt;   4\n  2  -&gt;   3\n  3  -&gt;   2\n  4  -&gt;   5\n  5  -&gt;   6\n  6  -&gt;   7\n  7  -&gt;   2\n  8  -&gt;   5\n  9  -&gt;   5\n\n\nExample 2:\n\nInput: cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput: \"85\"\nExplanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n\n\nExample 3:\n\nInput: cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput: \"0\"\nExplanation: It is impossible to paint any integer with total cost equal to target.\n\n\n&nbsp;\nConstraints:\n\n\n\tcost.length == 9\n\t1 &lt;= cost[i], target &lt;= 5000\n\n",
        "solution_py": "from functools import lru_cache\nclass Solution:\n    def largestNumber(self, cost: List[int], target: int) -> str:\n        @lru_cache(None)\n        def dfs(t):\n            if t == 0: return 0\n            res = float('-inf')\n            for digit in range(1,10):\n                if t - cost[digit-1] >= 0:\n                    res = max(res, dfs(t - cost[digit-1])*10+digit)\n            return res\n        res = dfs(target)\n        return \"0\" if res == float('-inf') else str(res)",
        "solution_js": "var largestNumber = function(cost, target) {\n    const arr = new Array(target+1).fill('#');\n    arr[0] = '';\n    \n    for (let i = 0; i < 9; i++) {\n        for (let j = cost[i]; j <= target; j++) {\n            if (arr[j-cost[i]] !== '#' && arr[j-cost[i]].length + 1 >= arr[j].length) {\n                arr[j] = (i+1).toString().concat(arr[j-cost[i]]);\n            }\n        }\n    }\n    \n    return arr[target] == '#' ? '0' : arr[target];\n};",
        "solution_java": "// Space Complexity = O(N*M) (N == length of cost array and M == target )\n// Time Complexity = O(N*M)\n\nclass Solution {\n    Map<String,String> map =  new HashMap<>();\n    String[][] memo;\n    public String largestNumber(int[] cost, int target) {\n        memo = new String[cost.length+1][target+1];\n        \n        for( int i = 0;i<=cost.length;i++ ){\n            for(int j = 0;j<=target;j++) memo[i][j] = \"0\";\n        }\n        \n        String res = helper(cost,cost.length-1,target);\n        \n        return res == \"-1\" ? \"0\" : res; \n        \n    }\n    \n    public String helper( int[] cost , int index , int target){\n        if(target == 0) {\n            return \"\";\n        }\n        \n        if(target < 0) return \"-1\";\n        \n        if(index < 0) return \"-1\";\n        \n        if( memo[index][target] != \"0\") return memo[index][target];\n        \n        String str1 = (index+1) + helper(cost,cost.length-1,target-cost[index]) ;\n        String str2 = helper(cost,index-1,target);\n        \n        String res = getBigger(str1,str2);\n        \n        memo[index][target] =  res;\n        \n        return res;\n    }\n    \n    public String getBigger(String num1 , String num2){\n        if( num1.contains(\"-1\") ) return num2;\n        if( num2.contains(\"-1\") ) return num1;\n        if( num1.length() > num2.length() ) return num1;\n        if( num2.length() > num1.length() ) return num2;\n        return Double.parseDouble( num1 ) < Double.parseDouble( num2 ) ? num2 : num1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<string>> dp ;\n    string largestNumber(vector<int>& cost, int target) {\n        dp.resize(10,vector<string>(target+1,\"-1\"));\n        return solve(cost,0,target) ;\n    }\n    \n    string solve(vector<int>& cost,int idx,int target){\n        if(!target) return \"\";\n        if(target < 0 || idx >= size(cost)) return \"0\"; \n        \n        if(dp[idx][target]!=\"-1\") return dp[idx][target];\n        \n        string a = to_string(idx+1) + solve(cost,0,target-cost[idx]);\n        string b = solve(cost,idx+1,target);\n        \n        return dp[idx][target] = a.back() == '0' ? b : b.back() == '0' ? a : size(a) == size(b) ? max(a,b) : size(a) > size(b) ? a : b ;\n    }\n};"
    },
    {
        "title": "Minimum Operations to Make the Array Increasing",
        "algo_input": "You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.\n\n\n\tFor example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].\n\n\nReturn the minimum number of operations needed to make nums strictly increasing.\n\nAn array nums is strictly increasing if nums[i] &lt; nums[i+1] for all 0 &lt;= i &lt; nums.length - 1. An array of length 1 is trivially strictly increasing.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].\n\n\nExample 2:\n\nInput: nums = [1,5,2,4,1]\nOutput: 14\n\n\nExample 3:\n\nInput: nums = [8]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t1 &lt;= nums[i] &lt;= 104\n",
        "solution_py": "class Solution:\n    def minOperations(self, nums: List[int]) -> int:\n        sol = 0\n        last = nums[0]\n\n        for i in range(len(nums) - 1):\n            if last >= nums[i + 1]:\n                sol += last - nums[i + 1] + 1\n                last = last + 1\n            else:\n                last = nums[i + 1]\n        \n        return sol",
        "solution_js": "var minOperations = function(nums) {\n    if(nums.length < 2) return 0;\n    let count = 0;\n    for(let i = 1; i<nums.length; i++) {\n       if(nums[i] <= nums[i-1]) {\n           let change = nums[i-1] - nums[i] + 1;\n           count += change;\n           nums[i] += change;\n       }\n    }\n    \n    return count;\n};",
        "solution_java": "class Solution {\n    public int minOperations(int[] nums) {\n        if (nums.length <= 1) {\n            return 0;\n        }\n\n        int count = 0;\n        int num = nums[0];\n        for (int i = 1; i < nums.length; i++) {\n            if (num == nums[i]) {\n                count++;\n                num++;\n            } else if (num > nums[i]) {\n                num++;\n                count += num - nums[i];\n            } else {\n                num = nums[i];\n            }\n        }\n        \n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minOperations(vector<int>& nums) {\n        int output=0;\n        for(int i=0;i<nums.size()-1;i++){\n            if(nums[i]<nums[i+1])\n                continue;\n            else{\n                output=output+(nums[i]+1-nums[i+1]);\n                nums[i+1]=nums[i]+1;\n            }\n        }\n        return output;\n    }\n};"
    },
    {
        "title": "Minimize the Difference Between Target and Chosen Elements",
        "algo_input": "You are given an m x n integer matrix mat and an integer target.\n\nChoose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.\n\nReturn the minimum absolute difference.\n\nThe absolute difference between two numbers a and b is the absolute value of a - b.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput: 0\nExplanation: One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.\n\n\nExample 2:\n\nInput: mat = [[1],[2],[3]], target = 100\nOutput: 94\nExplanation: The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.\n\n\nExample 3:\n\nInput: mat = [[1,2,9,8,7]], target = 6\nOutput: 1\nExplanation: The best choice is to choose 7 from the first row.\nThe absolute difference is 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 70\n\t1 &lt;= mat[i][j] &lt;= 70\n\t1 &lt;= target &lt;= 800\n\n",
        "solution_py": "class Solution:\n    def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n        min_possible = sum(min(row) for row in mat)\n        if min_possible >= target: return min_possible - target\n        curs = {0}\n        for row in mat:\n            curs = {x + y for x in row for y in curs if x + y <= 2*target}\n        return min(abs(target - x) for x in curs)",
        "solution_js": "var minimizeTheDifference = function(mat, target) {\n    const MAX = Number.MAX_SAFE_INTEGER;\n    \n    const m = mat.length;\n    const n = mat[0].length;\n    \n    const memo = [];\n    \n    for (let i = 0; i < m; ++i) {\n        memo[i] = new Array(4901).fill(MAX);\n    }\n    \n    return topDown(0, 0);\n    \n    function topDown(row, sum) {\n        if (row === m) return Math.abs(target - sum);\n        if (memo[row][sum] != MAX) return memo[row][sum];\n        \n        let min = MAX;\n        \n        mat[row].sort((a, b) => a - b); \n        \n        const set = new Set(mat[row]);\n       \n        for (const num of set) {\n           const res = topDown(row + 1, sum + num);\n            \n           if (res > min) break;\n           min = res;\n        }\n        \n        memo[row][sum] = min;\n        \n        return min;\n    }\n};",
        "solution_java": "class Solution {\n    public int minimizeTheDifference(int[][] mat, int target) {\n        Integer[][] dp = new Integer[mat.length][5001];\n        return minDiff(mat, 0, target,0, dp);\n    }\n\n    public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){\n        if(index == mat.length){\n            return Math.abs(val - target);\n        }\n        if(dp[index][val] != null){\n            return dp[index][val];\n        }\n\n        int res = Integer.MAX_VALUE;\n        for(int i = 0; i < mat[0].length; i++){\n            res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));\n        }\n\n        return dp[index][val] = res;\n    }\n}",
        "solution_c": "class Solution \n{\npublic:\n    int dp[8000][71];\n    int n,m;\n    int find(vector<vector<int>>&mat,int r,int sum,int &target)\n    {\n        if(r>=n)\n        {\n            return abs(sum-target);\n        }\n        if(dp[sum][r]!=-1)\n        {\n            return dp[sum][r];\n        }\n        int ans=INT_MAX;\n        for(int i=0;i<m;i++)\n        {\n            ans=min(ans,find(mat,r+1,sum+mat[r][i],target));\n            if(ans==0)\n            {\n                break;\n            }\n        }\n        return dp[sum][r]=ans;\n    }\n    int minimizeTheDifference(vector<vector<int>>& mat, int target) \n    {\n        memset(dp,-1,sizeof(dp));\n        n=mat.size();\n        m=mat[0].size();\n        return find(mat,0,0,target);\n    }\n};"
    },
    {
        "title": "Count Prefixes of a Given String",
        "algo_input": "You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.\n\nReturn the number of strings in words that are a prefix of s.\n\nA prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\nOutput: 3\nExplanation:\nThe strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.\n\nExample 2:\n\nInput: words = [\"a\",\"a\"], s = \"aa\"\nOutput: 2\nExplanation:\nBoth of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length, s.length &lt;= 10\n\twords[i] and s consist of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def countPrefixes(self, words: List[str], s: str) -> int:\n        return len([i for i in words if s.startswith(i)])",
        "solution_js": "var countPrefixes = function(words, s) {\n  \n    let cont = 0;\n    \n    for(i = 0; i < words.length; i++){\n        for(j = 1; j <= s.length; j++){\n            if(words[i] == s.slice(0, j)){\n                cont++;\n            }\n        }        \n    }\n     return cont;\n    \n};",
        "solution_java": "class Solution {\n    public int countPrefixes(String[] words, String s) {\n        int i = 0;\n        int j = 0;\n        int count = 0;\n        for(int k = 0; k < words.length; k++){\n            if(words[k].length() > s.length()){\n                continue;\n            }\n            \n            while(i < words[k].length() && words[k].charAt(i) == s.charAt(j)){\n                i++;\n                j++;\n            }\n            if(i == words[k].length()){\n                count++;\n            }\n            i = 0;\n            j = 0;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPrefixes(vector<string>& words, string s) {\n        int res = words.size();\n\n        for (auto && word : words) {\n            for (int i = 0; i < word.size(); i++) {\n                if (s[i] != word[i]) {\n                    res--;\n                    break;\n                }\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Strings That Appear as Substrings in Word",
        "algo_input": "Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\nOutput: 3\nExplanation:\n- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.\n\n\nExample 2:\n\nInput: patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\nOutput: 2\nExplanation:\n- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.\n\n\nExample 3:\n\nInput: patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\nOutput: 3\nExplanation: Each of the patterns appears as a substring in word \"ab\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= patterns.length &lt;= 100\n\t1 &lt;= patterns[i].length &lt;= 100\n\t1 &lt;= word.length &lt;= 100\n\tpatterns[i] and word consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numOfStrings(self, patterns: List[str], word: str) -> int:\n        return sum([pattern in word for pattern in patterns])\n\n        ",
        "solution_js": "/**\n * @param {string[]} patterns\n * @param {string} word\n * @return {number}\n */\nvar numOfStrings = function(patterns, word) {\n    let result = 0; \n    \n    for(let char of patterns){\n        if(word.includes(char)){\n            result++;\n           } else{\n               result += 0;\n           }\n    }\n    \n    return result;\n};",
        "solution_java": "class Solution {\n    public int numOfStrings(String[] patterns, String word) {\n        int count = 0;\n        for(int i=0;i<patterns.length;i++){\n            if(word.contains(patterns[i])){\n                count++;\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numOfStrings(vector<string>& patterns, string word) {\n        int count=0;\n        for(int i=0;i<patterns.size();i++)\n        {\n            if(word.find(patterns[i])!=string::npos)\n                count++;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Maximum Binary Tree",
        "algo_input": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:\n\n\n\tCreate a root node whose value is the maximum value in nums.\n\tRecursively build the left subtree on the subarray prefix to the left of the maximum value.\n\tRecursively build the right subtree on the subarray suffix to the right of the maximum value.\n\n\nReturn the maximum binary tree built from nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,2,1,6,0,5]\nOutput: [6,3,5,null,2,0,null,null,1]\nExplanation: The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n        - Empty array, so no child.\n        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n            - Empty array, so no child.\n            - Only one element, so child is a node with value 1.\n    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n        - Only one element, so child is a node with value 0.\n        - Empty array, so no child.\n\n\nExample 2:\n\nInput: nums = [3,2,1]\nOutput: [3,null,2,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 1000\n\tAll integers in nums are unique.\n\n",
        "solution_py": "class Solution:\n\tdef constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n\t\tif not nums:\n\t\t\treturn None\n\t\tm = max(nums)\n\t\tidx  = nums.index(m)\n\t\troot = TreeNode(m)\n\t\troot.left = self.constructMaximumBinaryTree(nums[:idx])\n\t\troot.right = self.constructMaximumBinaryTree(nums[idx+1:])\n\t\treturn root",
        "solution_js": "var constructMaximumBinaryTree = function(nums) {\n    if (nums.length === 0) return null;\n    let max = Math.max(...nums);\n    let index = nums.indexOf(max);\n    let left = nums.slice(0, index);\n    let right = nums.slice(index + 1);\n    let root = new TreeNode(max);\n    root.left = constructMaximumBinaryTree(left);\n    root.right = constructMaximumBinaryTree(right);\n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode constructMaximumBinaryTree(int[] nums) {\n        TreeNode root = construct(nums,0,nums.length-1);\n        return root;\n    }\n    \n    private TreeNode construct(int []nums, int start, int end) {\n        if(start > end)\n            return null;\n        if(start == end)\n            return new TreeNode(nums[start]);\n        \n        int maxIdx = findMax(nums,start,end);\n        TreeNode root = new TreeNode(nums[maxIdx]);\n        \n        root.left = construct(nums,start,maxIdx-1);\n        root.right = construct(nums,maxIdx+1,end);\n        \n        return root;\n    }\n    \n    private int findMax(int []arr, int low, int high) {\n        int idx = -1, max = Integer.MIN_VALUE;\n        for(int i=low;i<=high;++i) \n            if(arr[i]>max) {\n                max = arr[i];\n                idx = i;\n            }\n        return idx;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* constructMaximumBinaryTree(vector<int>& nums) \n    {\n        return recur(0, nums.size() - 1, nums);\n    }\n    \n    TreeNode* recur(int st, int en, vector<int> &ar)\n    {\n        if(st > en)\n        {\n            return NULL;\n        }\n        TreeNode* cur = new TreeNode();\n        int maxm = -1, ind;\n        for(int i = st; i <= en; i++)\n        {\n            if(maxm < ar[i])\n            {\n                maxm = ar[i];\n                ind = i;\n            }\n        }\n        \n        cur->val = ar[ind];\n        cur->left = recur(st, ind-1, ar);\n        cur->right = recur(ind+1, en, ar);\n        \n        return cur;\n    }\n};"
    },
    {
        "title": "Encode and Decode TinyURL",
        "algo_input": "Note: This is a companion problem to the System Design problem: Design TinyURL.\n\nTinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.\n\nThere is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.\n\nImplement the Solution class:\n\n\n\tSolution() Initializes the object of the system.\n\tString encode(String longUrl) Returns a tiny URL for the given longUrl.\n\tString decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.\n\n\n&nbsp;\nExample 1:\n\nInput: url = \"https://leetcode.com/problems/design-tinyurl\"\nOutput: \"https://leetcode.com/problems/design-tinyurl\"\n\nExplanation:\nSolution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= url.length &lt;= 104\n\turl is guranteed to be a valid URL.\n\n",
        "solution_py": "class Codec:\n\n    def encode(self, longUrl):\n        return longUrl\n\n    def decode(self, shortUrl):\n        return shortUrl",
        "solution_js": "let arr = new Array();\nlet size = 0;\n\nvar encode = function(longUrl) {\n    arr.push(longUrl)\n    let i = longUrl.indexOf('/',11);\n    longUrl.slice(i);\n    longUrl += this.size;\n    arr.push(longUrl);\n    size += 2;\n    return longUrl;\n};\n\nvar decode = function(shortUrl) {\n    let i = 0;\n    while(arr[i] !== shortUrl && i<size){\n        i++;\n    }\n    return arr[i-1];\n};",
        "solution_java": "public class Codec {\n\n    // Encodes a URL to a shortened URL.\n    public String encode(String longUrl) {\n        return longUrl;\n    }\n\n    // Decodes a shortened URL to its original URL.\n    public String decode(String shortUrl) {\n        return shortUrl;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    unordered_map<string, string> hash;\n    string server = \"http://tinyurl.com/\";\n    string all = \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\";\n\npublic:\n\n    // Encodes a URL to a shortened URL.\n    string encode(string longUrl) {\n        srand(time(NULL));\n        string add = \"\";\n        int ran = rand() % 10;\n        int strsize = all.size();\n        while(ran){\n            int index = rand() % strsize;\n            add += all[index];\n            ran--;\n        }\n\n        hash[(server+add)] = longUrl;\n\n        return (server + add);\n    }\n\n    // Decodes a shortened URL to its original URL.\n    string decode(string shortUrl) {\n        return hash[shortUrl];\n    }\n};\n\n// Your Solution object will be instantiated and called as such:\n// Solution solution;\n// solution.decode(solution.encode(url));"
    },
    {
        "title": "Symmetric Tree",
        "algo_input": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,2,3,4,4,3]\nOutput: true\n\n\nExample 2:\n\nInput: root = [1,2,2,null,3,null,3]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow up: Could you solve it both recursively and iteratively?",
        "solution_py": "class Solution:\n    def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n        return root is None or self.findSymmetric(root.left, root.right)\n\n    def findSymmetric(self, left, right):\n        if (left is None or right is None):\n            return left == right\n\n        if (left.val != right.val):\n            return False\n\n        return self.findSymmetric(left.left, right.right) and self.findSymmetric(left.right, right.left)",
        "solution_js": "var isSymmetric = function(root) {\n    return helper(root.left, root.right);\n\n    function helper(left, right){\n        if(!left && !right) return true;\n        if((!left && right) || (left && !right) || (left.val !== right.val)) return false;\n        return helper(left.left, right.right) && helper(left.right, right.left)\n    }\n};",
        "solution_java": "class Solution {\n    public boolean isSymmetric(TreeNode root) {\n        return isSymmetric(root.left,root.right);\n    }\n\n    public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) {\n        if(rootLeft == null && rootRight == null) {return true;}\n        if(rootLeft == null || rootRight == null) {return false;}\n        if (rootLeft.val != rootRight.val) {return false;}\n        else\n            return isSymmetric(rootLeft.right, rootRight.left) && isSymmetric(rootLeft.left, rootRight.right);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    bool mirror(TreeNode* root1, TreeNode* root2){\n        if(root1==NULL and root2==NULL) return true;\n        if(root1==NULL or root2==NULL) return false;\n\n        if(root1->val!=root2->val) return false;\n\n        return mirror(root1->left, root2->right) and mirror(root1->right,root2->left);\n    }\n\n    bool isSymmetric(TreeNode* root) {\n        if(root==NULL) return true;\n\n        return mirror(root->left,root->right);\n    }\n};"
    },
    {
        "title": "Find the Middle Index in Array",
        "algo_input": "Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).\n\nA middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].\n\nIf middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.\n\nReturn the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,-1,8,4]\nOutput: 3\nExplanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4\n\n\nExample 2:\n\nInput: nums = [1,-1,4]\nOutput: 2\nExplanation: The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\n\n\nExample 3:\n\nInput: nums = [2,5]\nOutput: -1\nExplanation: There is no valid middleIndex.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t-1000 &lt;= nums[i] &lt;= 1000\n\n\n&nbsp;\nNote: This question is the same as&nbsp;724:&nbsp;https://leetcode.com/problems/find-pivot-index/\n",
        "solution_py": "class Solution:\n    def findMiddleIndex(self, nums: List[int]) -> int:\n        A = [0] + list(accumulate(nums)) + [0]\n        total, n = sum(nums), len(nums)\n        for i in range(n):\n            if A[i] == total - A[i] - nums[i]:\n                return i\n        return -1   ",
        "solution_js": "var findMiddleIndex = function(nums) {\n    for (let i = 0; i < nums.length; i++) {\n        let leftNums = nums.slice(0, i).reduce((a, b) => a + b, 0);\n        let rightNums = nums.slice(i + 1).reduce((a, b) => a + b, 0);\n        if (leftNums === rightNums) {\n            return i;\n        }\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int findMiddleIndex(int[] nums) {\n\n        for(int i=0;i<nums.length;i++)\n        {\n            int rsum=0;\n            int lsum=0;\n\n            for(int k=0;k<i;k++) lsum+=nums[k];\n            for(int k=i+1;k<nums.length;k++) rsum+=nums[k];\n\n            if(lsum==rsum){\n                return i;\n            }\n        }\n\n        return -1;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n  \n    int findMiddleIndex(vector<int>& nums) \n    {\n        int n=nums.size();\n        int left_sum=0;\n        int right_sum=0;\n        for(int i=0;i<n;i++)\n        {\n            right_sum+=nums[i];\n        }\n        for(int i=0;i<n;i++)\n        {\n            right_sum-=nums[i];\n            if(left_sum==right_sum)\n            {\n                return i;\n            }\n            left_sum+=nums[i];\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Word Ladder",
        "algo_input": "A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -&gt; s1 -&gt; s2 -&gt; ... -&gt; sk such that:\n\n\n\tEvery adjacent pair of words differs by a single letter.\n\tEvery si for 1 &lt;= i &lt;= k is in wordList. Note that beginWord does not need to be in wordList.\n\tsk == endWord\n\n\nGiven two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.\n\n&nbsp;\nExample 1:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput: 5\nExplanation: One shortest transformation sequence is \"hit\" -&gt; \"hot\" -&gt; \"dot\" -&gt; \"dog\" -&gt; cog\", which is 5 words long.\n\n\nExample 2:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput: 0\nExplanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= beginWord.length &lt;= 10\n\tendWord.length == beginWord.length\n\t1 &lt;= wordList.length &lt;= 5000\n\twordList[i].length == beginWord.length\n\tbeginWord, endWord, and wordList[i] consist of lowercase English letters.\n\tbeginWord != endWord\n\tAll the words in wordList are unique.\n\n",
        "solution_py": "class Solution:\n    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n        e = defaultdict(list)\n        m = len(beginWord)\n        for word in wordList + [beginWord]:\n            for i in range(m):\n                w = word[:i] + \"*\" + word[i + 1:]\n                e[w].append(word)\n        q = deque([beginWord])\n        used = set([beginWord])\n        d = 0\n        while q:\n            d += 1\n            for _ in range(len(q)):\n                word = q.popleft()\n                for i in range(m):\n                    w = word[:i] + \"*\" + word[i + 1:]\n                    if w in e:\n                        for v in e[w]:\n                            if v == endWord:\n                                return d + 1\n                            if v not in used:\n                                q.append(v)\n                                used.add(v)\n                        e.pop(w)\n        return 0",
        "solution_js": "/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {number}\n */\n\n// Logic is same as One direction, just from both side tword mid, much faster.\n// One Direction solution is here ->\n// https://leetcode.com/problems/word-ladder/discuss/2372376/Easy-Fast-Simple-83.95-235-ms-50.4-MB-One-Direction\n\nvar ladderLength = function(beginWord, endWord, wordList) {\n    const charMap = buildCharMap()\n    const wordSet = new Set(wordList)\n    if (!wordSet.has(endWord)) return 0\n\n    let leftSet = new Set([beginWord]), rightSet = new Set([endWord]), level = 1\n    \n    const helper = (set1, set2) => {\n        const setArr = Array.from(set1)\n        for (let i = 0;  i < setArr.length; i++) {\n            const word = setArr[i]\n            for (let i = 0; i < word.length; i++) {\n                for (const c of charMap) {\n                    const newWord = word.slice(0, i) + c + word.slice(i + 1)\n\n                    if (set2.has(newWord)) return true\n                    if (wordSet.has(newWord)) { \n                        set1.add(newWord)\n                        wordSet.delete(newWord)\n                    }\n                }\n            }\n            set1.delete(word)\n        }\n    }\n    \n    while (leftSet.size && rightSet.size) {\n        level++\n        if (helper(leftSet, rightSet)) return level\n        \n        level++\n        if (helper(rightSet, leftSet)) return level\n    }\n        \n    return 0\n};\n\nconst buildCharMap = () => {\n    const map = []\n    \n    for (let i = 0; i < 26; i++) {\n        map.push(String.fromCharCode(i + 97))\n    }\n    \n    return map\n}",
        "solution_java": "class Solution {\n    public int ladderLength(String beginWord, String endWord, List<String> wordList) {\n        int count = 1;\n        Set<String> words = new HashSet<>(wordList);\n        Queue<String> q = new LinkedList<String>();\n        q.add(beginWord);\n        \n        while(!q.isEmpty()) {\n            int size = q.size();\n            \n            while(size-- > 0) {\n                String word = q.poll();\n                char[] chList = word.toCharArray();\n                \n                for(int i=0; i<word.length(); i++) {\n                    char tmp = chList[i];\n                    \n                    for(char c='a'; c<='z'; c++) {\n                        chList[i] = c;\n                        String newWord = new String(chList);\n                        \n                        if(words.contains(newWord)) {\n                            if(newWord.equals(endWord)) {\n                                return count + 1;\n                            }\n                            q.add(newWord);\n                            words.remove(newWord);\n                        }\n                    }\n                    \n                    chList[i] = tmp;\n                }\n            }\n            \n            count++;\n        }\n        \n        return 0;\n    }\n}",
        "solution_c": "// For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s\n\nclass Solution\n{\npublic:\n    int ladderLength(string beginWord, string endWord, vector<string>& wordList)\n    {\n        // 1. Create a set and insert all wordList to the set to have\n        // easy search of O(1)\n        unordered_set<string> wordSet;\n        bool isEndWordPresent = false;\n        for (string s:wordList)\n        {\n            // Check if the destination string even present in the wordList\n            // If not then there is no point in even trying to find the\n            // route from source string to destination string\n            if (!isEndWordPresent && s.compare(endWord) == 0)\n            {\n                isEndWordPresent = true;\n            }\n            wordSet.insert(s);\n        }\n\n        // 2. If endWord is not present in the wordList return\n        if (!isEndWordPresent)\n        {\n            return 0;\n        }\n\n        // 3. Create a queue for BST insert the elements of currentlevel to the queue\n        // currentLevel is defined as all the strings that can be reached from\n        // all the strings of the previous string by just replacing one character\n        // and the one-char-replaced-string is present in the wordSet / wordList\n        queue<string> q;\n        q.push(beginWord);\n        int level = 0; // every time all the strings at this level are processed increment it\n\n        // 4. Loop through all the elements in the queue\n        while (!q.empty())\n        {\n            level++;\n            int numStringsInCurLevel = q.size();\n            // loop through all the strings in this current level\n            // and find out if destination can be reached before\n            // jumping to the next level of strings added to the queue\n            while (numStringsInCurLevel--)\n            {\n                string curStr = q.front();\n                q.pop();\n\n                for (int i=0; i<curStr.length(); i++)\n                {\n                    string tempStr = curStr;\n                    // Now check if swappin one char in the curStr will\n                    // lead to any string in the wordSet\n                    for (char c='a'; c<='z'; c++)\n                    {\n                        tempStr[i] = c;\n                        if (tempStr.compare(curStr) == 0)\n                        {\n                            // Ignore the same string\n                            continue;\n                        }\n                        // Check if we reached the destination\n                        if (tempStr.compare(endWord) == 0)\n                        {\n                            return level+1;\n                        }\n                        if (wordSet.find(tempStr) != wordSet.end())\n                        {\n                            // this string is in the set so add it to the queue\n                            // and remove it from the set\n                            q.push(tempStr);\n                            wordSet.erase(tempStr);\n                        }\n                    }\n                }\n            }\n        }\n\n        // If we are here then we couldn't reach destination\n        // even though the destination string is present in the wordList\n        // there is no path from source to destination for the given rules\n        return 0;\n    }\n};"
    },
    {
        "title": "Steps to Make Array Non-decreasing",
        "algo_input": "You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] &gt; nums[i] for all 0 &lt; i &lt; nums.length.\n\nReturn the number of steps performed until nums becomes a non-decreasing array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,3,4,4,7,3,6,11,8,5,11]\nOutput: 3\nExplanation: The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.\n\n\nExample 2:\n\nInput: nums = [4,5,7,7,13]\nOutput: 0\nExplanation: nums is already a non-decreasing array. 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",
        "solution_py": "class Solution:\n    def totalSteps(self, nums: List[int]) -> int:\n        st = []\n        ans = 0\n        for i in nums:\n            t = 0\n            while st and st[-1][0] <= i:\n                t = max(t, st.pop()[1])\n            x = 0 \n            if st: \n                x = t+1 \n            st.append([i, x])\n            ans = max(ans, x)\n        return ans",
        "solution_js": "var totalSteps = function(nums) {\n    let stack = [],\n        dp = new Array(nums.length).fill(0),\n        max = 0\n\n    for (let i = nums.length - 1; i >= 0; i--) {\n        while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {\n            dp[i] = Math.max(++dp[i], dp[stack.pop()])\n            max = Math.max(dp[i], max)\n        }\n        stack.push(i)\n    }\n    return max\n};",
        "solution_java": "class Solution {\n    \n    \n    \n    public int totalSteps(int[] nums) {\n        \n        int n = nums.length;\n        int ans = 0;\n        \n        Stack<Pair<Integer,Integer>> st = new Stack();\n        \n        st.push(new Pair(nums[n-1],0));\n        \n        \n        for(int i=n-2;i>=0;i--)\n        {\n            int count = 0;\n            \n            while(!st.isEmpty() && nums[i] > st.peek().getKey())\n            {\n                count = Math.max(count+1 , st.peek().getValue() );\n                st.pop();\n            }\n            \n            ans = Math.max(ans , count);\n            st.push(new Pair(nums[i],count));\n        }\n        \n        return ans;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    using pi = pair<int, int>;\n    int totalSteps(vector<int>& nums) {\n        int N = nums.size();\n        map<int, int> mp;\n        vector<pi> del;    // stores pairs of (previous id, toDelete id)\n        for (int i = 0; i < N; ++i) {\n            mp[i] = nums[i];\n            if (i+1 < N && nums[i] > nums[i+1])\n                del.emplace_back(i, i+1);\n        }\n\n        int ans = 0;  // number of rounds\n        while (!del.empty()) {\n            ++ans;\n            vector<pi> nxt;  // pairs to delete in the next round\n            for (auto [i,j] : del) mp.erase(j);   // first, get rid of the required deletions\n            for (auto [i,j] : del) {\n                auto it = mp.find(i);\n                if ( it == end(mp) || next(it) == end(mp) )   // if it's not in the map anymore,\n                    continue;                   // OR if it's the last element, skip it\n                auto itn = next(it);            // now compare against next element in the ordering\n                if (it->second > itn->second)   \n                    nxt.emplace_back(it->first, itn->first);  // add the (current id, toDelete id)\n            }\n            swap(nxt, del);  // nxt is the new del\n        }\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Maximum Students Taking Exam",
        "algo_input": "Given a m&nbsp;* n&nbsp;matrix seats&nbsp;&nbsp;that represent seats distributions&nbsp;in a classroom.&nbsp;If a seat&nbsp;is&nbsp;broken, it is denoted by '#' character otherwise it is denoted by a '.' character.\n\nStudents can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting&nbsp;directly in front or behind him. Return the maximum number of students that can take the exam together&nbsp;without any cheating being possible..\n\nStudents must be placed in seats in good condition.\n\n&nbsp;\nExample 1:\n\nInput: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n&nbsp;               [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n&nbsp;               [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\nOutput: 4\nExplanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n\n\nExample 2:\n\nInput: seats = [[\".\",\"#\"],\n&nbsp;               [\"#\",\"#\"],\n&nbsp;               [\"#\",\".\"],\n&nbsp;               [\"#\",\"#\"],\n&nbsp;               [\".\",\"#\"]]\nOutput: 3\nExplanation: Place all students in available seats. \n\n\n\nExample 3:\n\nInput: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n&nbsp;               [\".\",\"#\",\".\",\"#\",\".\"],\n&nbsp;               [\".\",\".\",\"#\",\".\",\".\"],\n&nbsp;               [\".\",\"#\",\".\",\"#\",\".\"],\n&nbsp;               [\"#\",\".\",\".\",\".\",\"#\"]]\nOutput: 10\nExplanation: Place students in available seats in column 1, 3 and 5.\n\n\n&nbsp;\nConstraints:\n\n\n\tseats&nbsp;contains only characters&nbsp;'.'&nbsp;and'#'.\n\tm ==&nbsp;seats.length\n\tn ==&nbsp;seats[i].length\n\t1 &lt;= m &lt;= 8\n\t1 &lt;= n &lt;= 8\n\n",
        "solution_py": "class Solution:\n    def maxStudents(self, seats: List[List[str]]) -> int:\n        m, n = len(seats), len(seats[0])\n        match = [[-1]*n for _ in range(m)]\n        def dfs(i, j, visited):\n            for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]:\n                if 0 <= x < m and 0 <= y < n and seats[x][y] == \".\" and (x, y) not in visited:\n                    visited.add((x, y))\n                    if match[x][y] == -1 or dfs(*match[x][y], visited):\n                        match[x][y] = (i, j)\n                        match[i][j] = (x, y)\n                        return True\n            return False\n        def max_matching():\n            cnt = 0\n            for i in range(m):\n                for j in range(0,n,2):\n                    if seats[i][j] == '.' and match[i][j] == -1:\n                        visited = set()\n                        cnt += dfs(i, j, visited)\n            return cnt\n\t\t#returns the number of elements of the maximum independent set in the bipartite set\n        return sum(seats[i][j]=='.' for i in range(m) for j in range(n)) - max_matching()",
        "solution_js": "var maxStudents = function(seats) {\n    if (!seats.length) return 0;\n    \n\t// precalculate the seat that will be off the matrix\n    const lastPos = 1 << seats[0].length;\n\t// encode the classroom into binary where 1 will be an available seat and 0 will be a broken seat\n    const classroom = seats.map((row) => (\n        row.reduce((a,c,i) => c === '#' ? a : (a | (1 << i)), 0))\n    );\n\t\n\t// create a store to store the max seating for each row arrangment\n\t// each row will be off +1 of seats rows\n    const dp = new Array(seats.length + 1).fill(null).map(() => new Map());\n\t// since no one can sit at row=-1 set the max number of no one sitting on that row as 0\n    dp[0].set(0,0);    \n\t\n\t// iterate through every row in seats matrix\n\t// remember that dp's rows are +1 of seats rows\n    for (let row = 0; row < seats.length; row++) {\n\t\n\t    // start with no one sitting on the row\n        let queue = [0];\n\t\t// this will count the number of students sitting on this row\n\t\t// we will increment this up as we add students to the row\n        let numStudents = 0;\n\t\t\n        while (queue.length > 0) {\n            \n\t\t\t// this will store all the different arrangments possible when we add 1 more student from the previous\n            const next = [];\n\t\t\t\n\t\t\t// iterate through all the previous arrangements\n\t\t\t// calculate the maximum number of students that can sit on current and all previous rows\n\t\t\t// try adding a student to all possible available seats meeting the rules of the game\n            for (let arrangement of queue) {\n\t\t\t\n \t\t\t    // this calculates the maximum number of students that can sit with this row arrangment\n\t\t\t\t// if the arrangement doesn't allow any students to sit in the previous row this will be handled\n\t\t\t\t// by the 0 case in the previous row\n\t\t\t\t// *see helper function that checks to see if the arrangement conflicts with the previous arrangment\n                let max = 0;\n                for (let [prevArrang, count] of dp[row]) {\n                    if (conflicts(prevArrang, arrangement)) continue;  \n                    max = Math.max(max, count + numStudents);\n                }\n                dp[row + 1].set(arrangement, max);\n                \n\t\t\t\t// try adding an additional student to all elements in the row checking if it conflicts\n\t\t\t\t// arrangement | i  => adds the student to the arrangement\n                for (let i = 1; i < lastPos; i <<= 1) {\n                    if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i);\n                }\n            }            \n            \n            queue = next;\n            numStudents++;\n        }\n    }\n    \n\t// return the maximum value from the last row\n\t// the last row holds the maximum number of students for each arrangment\n    return Math.max(...dp[seats.length].values());\n};\n\n// this checks if the there are any students to the left or right of current arrangment\n// curr << 1 => checks if there are any students to the left\n// curr >> 1 => check if there are any students to the right\nfunction conflicts(prev, curr) {\n    return (prev & (curr << 1)) || (prev & (curr >> 1));\n}\n\n// this checks if we can place the new student in this spot\n// row & newStudent => checks if the classroom's row's seat is not broken\n// arrangment & newStudent => will return truthy if there is a student sitting in that position (so we ! it because we don't want anyone sitting there)\n// arrangement & (newStudent << 1) => will return truthy if there is a student sitting to the left of that position (so we ! it because we don't want anyone sitting there)\n// arrangement & (newStudent >> 1) => will return truthy if there is a student sitting to the right of that position (so we ! it because we don't want anyone sitting there)\nfunction canSit(row, arrangement, newStudent) {\n    return row & newStudent && !(arrangement & newStudent) && !(arrangement & (newStudent << 1)) && !(arrangement & (newStudent >> 1));\n}",
        "solution_java": "class Solution {\n    private Integer[][] f;\n    private int n;\n    private int[] ss;\n\n    public int maxStudents(char[][] seats) {\n        int m = seats.length;\n        n = seats[0].length;\n        ss = new int[m];\n        f = new Integer[1 << n][m];\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (seats[i][j] == '.') {\n                    ss[i] |= 1 << j;\n                }\n            }\n        }\n        return dfs(ss[0], 0);\n    }\n\n    private int dfs(int seat, int i) {\n        if (f[seat][i] != null) {\n            return f[seat][i];\n        }\n        int ans = 0;\n        for (int mask = 0; mask < 1 << n; ++mask) {\n            if ((seat | mask) != seat || (mask & (mask << 1)) != 0) {\n                continue;\n            }\n            int cnt = Integer.bitCount(mask);\n            if (i == ss.length - 1) {\n                ans = Math.max(ans, cnt);\n            } else {\n                int nxt = ss[i + 1];\n                nxt &= ~(mask << 1);\n                nxt &= ~(mask >> 1);\n                ans = Math.max(ans, cnt + dfs(nxt, i + 1));\n            }\n        }\n        return f[seat][i] = ans;\n    }\n}",
        "solution_c": "class Solution {\n public:\n  int dp[8][(1 << 8) - 1];\n  int maxStudents(vector<vector<char>>& seats) {\n    memset(dp, -1, sizeof(dp));\n    return helper(seats, 0, 0);\n  }\n  int helper(vector<vector<char>>& seats, int prevAllocation, int idx) {\n    if (idx == seats.size()) return 0;\n    int sz = seats[0].size(), masks = ((1 << sz) - 1), maxi = 0;\n      // masks is for iterating over all subsets\n    if (dp[idx][prevAllocation] != -1) return dp[idx][prevAllocation];\n    while (masks >= 0) {\n      int curAllocation = 0, cnt = 0;\n      for (int i = 0; i < sz; i++) {\n        if (seats[idx][i] != '#' && masks >> i & 1) {\n          int ul = i - 1, ur = i + 1;\n          bool canPlace = true;\n          if (ul >= 0)\n            if (prevAllocation >> ul & 1 || curAllocation >> ul & 1)\n              canPlace = false;\n          if (ur < sz)\n            if (prevAllocation >> ur & 1 || curAllocation >> ur & 1)\n              canPlace = false;\n          if (canPlace) {\n            curAllocation |= 1 << i;\n            cnt++;\n          }\n        }\n      }\n      maxi = max(maxi, cnt + helper(seats, curAllocation, idx + 1));\n      masks--;\n    }\n    dp[idx][prevAllocation] = maxi;\n    return maxi;\n  }\n};"
    },
    {
        "title": "Nth Digit",
        "algo_input": "Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 3\n\n\nExample 2:\n\nInput: n = 11\nOutput: 0\nExplanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def findNthDigit(self, n: int) -> int:\n        low, high = 1, 0\n        place = 1\n        \n        sum_ = 0\n        \n        while True:\n            high = 10**place -1\n            digits_sum = (high - low +1 ) * place\n            \n            if sum_<= n <= digits_sum + sum_:\n                break\n            else:\n                low = high+1\n                sum_+= digits_sum\n            place += 1\n        \n        remaining_digits = n - sum_\n        \n        position = (remaining_digits-1)//place \n        index_ =  remaining_digits - position*place -1\n        \n        \n        number = low + position\n        # return str(number)[index_]\n        count = 0\n        index_ = place - 1 - index_\n        l = []\n        # \n        while number:\n            if count == index_:\n                return number%10\n            number = number//10\n            count+=1",
        "solution_js": "var findNthDigit = function(n) {\n    var len = 1;\n    var range = 9;\n    var base = 1;\n    while(n>len*range)\n    {\n        n -= len *range;\n        range *= 10;\n        base *= 10;\n        len++;\n    }\n    // [100, 101, 102,...]\n    // 100 should have offset 0, use (n-1) to make the counting index from 0-based.\n    var num = base + Math.floor((n-1)/len);\n    var s = num.toString();\n    return parseInt(s[(n-1)%len]);\n};",
        "solution_java": "class Solution {\n    public int findNthDigit(int n) {\n\n        if(n < 10)\n            return n;\n\n        long currDigitIndex = 10;\n        int tillNextIncrease = 90;\n        int currNumberSize = 2;\n        int currNumber = 10;\n        int next = tillNextIncrease;\n\n        while(currDigitIndex < n) {\n\n            currNumber++;\n            currDigitIndex += currNumberSize;\n            next--;\n\n            if(next == 0) {\n                currNumberSize++;\n                tillNextIncrease *= 10;\n                next = tillNextIncrease;\n            }\n        }\n\n        int nthDigit = currNumber % 10;\n        if(currDigitIndex == n) {\n            while(currNumber != 0) {\n                nthDigit = currNumber % 10;\n                currNumber /= 10;\n            }\n        } else if(currDigitIndex > n) {\n\n            currNumber--;\n\n            while(currDigitIndex > n) {\n                currDigitIndex--;\n                nthDigit = currNumber % 10;\n                currNumber /= 10;\n            }\n        }\n\n        return nthDigit;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    #define ll long long \n    int findNthDigit(int n) {\n        if(n<=9) return n;\n        ll i=1;\n        ll sum=0;\n        while(true){\n            ll a=(9*pow(10,i-1))*i;\n            if(n-a<0){\n                break;\n            } \n            else{\n                sum+=9*pow(10,i-1);\n                n-=a;\n            }\n            i++;\n        }\n        \n        ll x=0;        \n        ll mod=n%i;\n        n=(n/i);\n        n+=sum;\n        if(mod==0) return n%10;\n        else{\n            n++;\n            ll x=i-mod;\n            while(x--){\n                n/=10;\n            }\n        }\n        return n%10;\n    }\n};"
    },
    {
        "title": "Nearest Exit from Entrance in Maze",
        "algo_input": "You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.\n\nIn one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.\n\nReturn the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.\n\n&nbsp;\nExample 1:\n\nInput: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\n\n\nExample 2:\n\nInput: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\n\n\nExample 3:\n\nInput: maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n\n\n&nbsp;\nConstraints:\n\n\n\tmaze.length == m\n\tmaze[i].length == n\n\t1 &lt;= m, n &lt;= 100\n\tmaze[i][j] is either '.' or '+'.\n\tentrance.length == 2\n\t0 &lt;= entrancerow &lt; m\n\t0 &lt;= entrancecol &lt; n\n\tentrance will always be an empty cell.\n\n",
        "solution_py": "class Solution:\n    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n        x, y = entrance\n        m, n, infi = len(maze), len(maze[0]), int(1e5)\n        reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)\n        @lru_cache(None)\n        def dfs(i, j):\n            if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':\n                return infi\n            if reached(i, j):\n                return 0\n            maze[i][j] = '+'\n            ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))\n            maze[i][j] = '.'\n            return ans\n        ans = dfs(x, y)\n        return -1 if ans>=infi else ans",
        "solution_js": "function nearestExit(maze, entrance) {\n  const queue = []; // queue for bfs\n  const empty = \".\";\n  const [height, width] = [maze.length, maze[0].length];\n  const tried = [...Array(height)].map(() => Array(width).fill(false));\n  const tryStep = (steps, row, col) => {\n    // don't reuse once it's already been tried\n    if (tried[row][col]) return;\n    tried[row][col] = true;\n    if (maze[row][col] !== empty) return; // blocked? i.e. can't step\n    queue.push([steps, row, col]);\n  };\n  const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };\n  const trySteppableDirs = (steps, row, col) => {\n    // try steppable directions\n    if (col < edges.right) tryStep(steps, row, col + 1);\n    if (row < edges.bottom) tryStep(steps, row + 1, col);\n    if (col > edges.left) tryStep(steps, row, col - 1);\n    if (row > edges.top) tryStep(steps, row - 1, col);\n  };\n  let steps = 1, [row, col] = entrance;\n  tried[row][col] = true; // don't reuse the entrance\n  trySteppableDirs(steps, row, col);\n  while (queue.length > 0) { // bfs\n    [steps, row, col] = queue.shift();\n    // path to the edge found?\n    if (col === edges.left || col === edges.right) return steps;\n    if (row === edges.top || row === edges.bottom) return steps;\n    trySteppableDirs(steps + 1, row, col);\n  }\n  // NO path to the edge found\n  return -1;\n}",
        "solution_java": "class Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int rows = maze.length, cols = maze[0].length, queueSize;\n        Queue<int[]> queue = new LinkedList<>();\n        boolean[][] visited = new boolean[rows][cols];\n        int[] curr;\n        int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n        int x, y, steps = 0;\n\n        queue.offer(entrance);\n        visited[entrance[0]][entrance[1]] = true;\n\n        while (!queue.isEmpty()) {\n            queueSize = queue.size();\n            steps++;\n\n            for (int i=0;i<queueSize;i++) {\n                curr = queue.poll();\n\n                for (int[] dir: dirs) {\n                    x = dir[0]+curr[0];\n                    y = dir[1]+curr[1];\n\n                    if (x<0||x>=rows||y<0||y>=cols) continue;\n                    if (visited[x][y] || maze[x][y] == '+') continue;\n\n                    // check if we have reached boundary\n                    if (x==0||x==rows-1||y==0||y==cols-1) return steps;\n\n                    queue.offer(new int[]{x, y});\n                    visited[x][y] = true;\n                }\n            }\n        }\n\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    //checks if the coordinates of the cell are that of an unvisited valid empty cell\n    bool isValid(int x,int y,int n,int m, vector<vector<char>>& maze,vector<vector<int>>& visited){\n        if(x>=0 && x<n && y>=0 && y< m && maze[x][y]!='+' && visited[x][y]!=1){\n            return true;\n        }\n        return false;\n    }\n\n    //checks if the cell is a valid exit point\n    bool isExit(int x,int y,int startX,int startY, vector<vector<char>>& maze,vector<vector<int>>& visited){\n        if(x==startX && y==startY) return false;\n        if( (x==0 || x==maze.size()-1 || y==0 || y==maze[0].size()-1)\n           && maze[x][y]!='+')\n        {\n            return true;\n        }\n        return false;\n    }\n\n    //main BFS function\n    int bfsHelper(vector<vector<char>>& maze,vector<vector<int>>& visited,int startX,int startY){\n        queue<vector<int>>Queue;\n        Queue.push({startX,startY,0});\n        while(!Queue.empty()){\n            int x = Queue.front()[0];\n            int y = Queue.front()[1];\n            int steps = Queue.front()[2];\n            Queue.pop();\n            //if you reach a valid exit, return the number of steps\n            if(isExit(x,y,startX,startY,maze,visited)) return steps;\n            int dx[4] = {0,-1,0,1};\n            int dy[4] = {-1,0,1,0};\n            //check in the 4 directions that you can travel\n            for(int i=0;i<4;i++){\n                int newX = x+dx[i] , newY = y+dy[i];\n                //if the coordinates of the cell are that of\n                //an unvisited valid empty cell, add it to the queue\n                //and mark it as visited.\n                if(isValid(newX,newY,maze.size(),maze[0].size(),maze,visited)){\n                    Queue.push({newX,newY,steps+1});\n                    visited[newX][newY] = 1;\n                }\n            }\n        }\n        //if you could not find a valid exit point, return -1\n        return -1;\n    }\n\n    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n        int n = maze.size();\n        int m = maze[0].size();\n        //create a 2d matrix and mark all the cells as -1,\n        //denoting that they have not been visited yet.\n        vector<vector<int>>visited(n,vector<int>(m,-1));\n        return bfsHelper(maze,visited,entrance[0],entrance[1]);\n    }\n};"
    },
    {
        "title": "Shuffle an Array",
        "algo_input": "Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.\n\nImplement the Solution class:\n\n\n\tSolution(int[] nums) Initializes the object with the integer array nums.\n\tint[] reset() Resets the array to its original configuration and returns it.\n\tint[] shuffle() Returns a random shuffling of the array.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n[[[1, 2, 3]], [], [], []]\nOutput\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle();    // Shuffle the array [1,2,3] and return its result.\n                       // Any permutation of [1,2,3] must be equally likely to be returned.\n                       // Example: return [3, 1, 2]\nsolution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 50\n\t-106 &lt;= nums[i] &lt;= 106\n\tAll the elements of nums are unique.\n\tAt most 104 calls in total will be made to reset and shuffle.\n\n",
        "solution_py": "import random \n\nclass Solution:\n\n    def __init__(self, nums: List[int]):\n        self.nums = nums\n\n    def reset(self) -> List[int]:  \n        return self.nums\n\n    def shuffle(self) -> List[int]:\n        shuffled_array = self.nums.copy()\n        # randomly generates the idx of the element that'll be the ith element of the array \n        for i in range(len(self.nums) - 1, 0, -1):\n            idx = random.randint(0, i)\n            shuffled_array[i], shuffled_array[idx] = shuffled_array[idx], shuffled_array[i]\n        return shuffled_array",
        "solution_js": "var Solution = function(nums) {\n    this.nums = nums;\n    this.resetArray = [...nums];\n};\n\nSolution.prototype.reset = function() {\n    return this.resetArray;\n};\n\nSolution.prototype.shuffle = function() {\n\n    const n = this.nums.length;\n    const numsArray = this.nums;\n\n    for (let i = 0; i < n; i++) {\n        const j = Math.floor(Math.random() * (n - i)) + i;\n        const tmp = numsArray[i];\n        numsArray[i] = numsArray[j];\n        numsArray[j] = tmp;\n    }\n\n    return numsArray;\n};",
        "solution_java": "class Solution {\n\n    int a[];\n    int b[];\n    public Solution(int[] nums) {\n        a=nums.clone();\n        b=nums.clone();\n    }\n\n    public int[] reset() {\n        a=b.clone();\n        return a;\n    }\n\n    public int[] shuffle() {\n\n        for(int i=0;i<a.length;i++){\n            int ren=(int)(Math.random()*a.length);\n            int temp= a[ren];\n             a[ren]=a[i];\n            a[i]=temp;\n        }\n        return a;\n    }\n}\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(nums);\n * int[] param_1 = obj.reset();\n * int[] param_2 = obj.shuffle();\n */",
        "solution_c": "class Solution {\npublic:\n    vector<int> ans;\n    vector<int> res;\n    Solution(vector<int>& nums) {\n        ans=nums;\n        res=nums;\n    }\n    \n    vector<int> reset() {\n        return res;\n    }\n    \n    vector<int> shuffle() {\n        next_permutation(ans.begin(),ans.end());\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximal Rectangle",
        "algo_input": "Given a rows x cols&nbsp;binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput: 6\nExplanation: The maximal rectangle is shown in the above picture.\n\n\nExample 2:\n\nInput: matrix = [[\"0\"]]\nOutput: 0\n\n\nExample 3:\n\nInput: matrix = [[\"1\"]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\trows == matrix.length\n\tcols == matrix[i].length\n\t1 &lt;= row, cols &lt;= 200\n\tmatrix[i][j] is '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def maxArea(self,arr: List[List[int]]) -> int:\n        maxA = 0 #local max variable to return max area of a 1D array\n        stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing\n        arr.append(-1) # value for stack index -1 and one extra iteration to empty the stack\n        for i in range(len(arr)): # traversing for stack from left to right\n            arr[i] = int(arr[i]) # we are getting str value from matrix\n            while stack and arr[stack[-1]] >= int(arr[i]): #stack is non empty and stack top is greater or equal to current element\n                index = stack.pop() #pop greater element from stack and finds its area\n                width = i - stack[-1] - 1 if stack else i # for empty stack width is len of 1D arr, and after poping if we have element in stack then it becomes left boundary and current index as right boundary\n                maxA = max(maxA, width * arr[index]) # geting max area (L * B)\n            stack.append(int(i)) # inserting each element in stack\n        return maxA # return the max area\n    \"\"\"Below is the code for adding each row one by one and passing it to above function to get the max area for each row\"\"\"\n    # r1 - 1 0 1 0 0\n    # r2 - 1 0 1 1 1\n    # r = 2 0 2 1 1 This is for else condition\n\n    # r1 - 1 1 1 0 1\n    # r2 - 1 0 1 1 0\n    # r = 2 0 2 1 0 This is for if condition\n\n    def maximalRectangle(self, matrix: List[List[str]]) -> int:\n        result = [0] * len(matrix[0])\n        maxReact = 0\n        maxReact = self.maxArea(result)\n        for i in range(len(matrix)):\n            for j in range(len(matrix[i])):\n                matrix[i][j] = int(matrix[i][j])\n                if matrix[i][j] == 0:\n                    result[j] = 0\n                else:\n                    result[j] = result[j] + matrix[i][j]\n            maxReact = max(maxReact,self.maxArea(result)) #after getting max area for 1D arr we are getting max value from those 1D arr for the 2D arr\n        return maxReact",
        "solution_js": "var maximalRectangle = function(matrix) {\n    const m = matrix.length;\n    const n = matrix[m - 1].length;\n\n    const prefixSum = new Array(m).fill().map(() => new Array(n).fill(0));\n    for(let i = 0; i < m; i += 1) {\n        for(let j = 0; j < n; j += 1) {\n            prefixSum[i][j] = parseInt(matrix[i][j]);\n            if(i > 0 && prefixSum[i][j] > 0) {\n                prefixSum[i][j] += prefixSum[i - 1][j];\n            }\n        }\n    }\n\n    const getArea = (currentRow) => {\n        let max = 0;\n        for(let i = 0; i < n; i += 1) {\n            const height = currentRow[i];\n\n            let leftBoundary = i;\n            while(leftBoundary >= 0 && currentRow[leftBoundary] >= currentRow[i]) {\n                leftBoundary -= 1;\n            }\n\n            let rightBoundary = i;\n            while(rightBoundary < n && currentRow[rightBoundary] >= currentRow[i]) {\n                rightBoundary += 1;\n            }\n\n            const width = rightBoundary - leftBoundary - 1;\n            max = Math.max(max, height * width);\n        }\n\n        return max;\n    }\n\n    let max = 0;\n    for(let i = 0; i < m; i += 1) {\n        max = Math.max(max, getArea(prefixSum[i]));\n    }\n\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maximalRectangle(char[][] matrix) {\n        ArrayList<Integer> list = new ArrayList<>();\n        int n = matrix[0].length;\n        for(int i=0; i<n; i++){\n            list.add(Character.getNumericValue(matrix[0][i]));\n        }\n\n        int maxArea = maximumArea(list);\n        int m = matrix.length;\n\n        for(int i=1; i<m; i++){\n            for(int j=0; j<n; j++){\n                if(matrix[i][j] == '1'){\n                    list.set(j, Character.getNumericValue(matrix[i][j]) + list.get(j));\n                }else\n                    list.set(j, 0);\n            }\n            maxArea = Math.max(maxArea, maximumArea(list));\n        }\n        return maxArea;\n    }\n    public int maximumArea(ArrayList<Integer> heights) {\n        Stack<Integer> stack1 = new Stack<>();\n        Stack<Integer> stack2 = new Stack<>();\n        int n = heights.size();\n        int[] left = new int[n];\n        int[] right = new int[n];\n        int[] width = new int[n];\n\n        for(int i=0; i<n; i++){\n            while(!stack1.isEmpty() && heights.get(stack1.peek()) >= heights.get(i))\n                stack1.pop();\n            if(!stack1.isEmpty())\n                left[i] = stack1.peek();\n            else\n                left[i] = -1;\n            stack1.push(i);\n        }\n\n        for(int i=n-1; i>=0; i--){\n            while(!stack2.isEmpty() && heights.get(stack2.peek()) >= heights.get(i))\n                stack2.pop();\n            if(!stack2.isEmpty())\n                right[i] = stack2.peek();\n            else\n                right[i] = n;\n            stack2.push(i);\n        }\n\n        for(int i=0; i<n; i++){\n            width[i] = right[i] - left[i] - 1;\n        }\n        int mxArea = 0;\n        for(int i=0; i<n; i++){\n            mxArea = Math.max(mxArea, width[i] * heights.get(i));\n        }\n        return mxArea;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    vector<int> nextSmallerElement(int *arr , int n){\n        stack<int> st;\n        st.push(-1);\n        vector<int> ans(n);\n        \n        for(int i = n - 1 ; i >= 0 ; i--){\n            int curr = arr[i];\n            \n            while(st.top() != -1 && arr[st.top()] >= curr){\n                st.pop();\n            }\n            \n            ans[i] = st.top();\n            st.push(i);\n        }\n        return ans;\n    }\n    \n    vector<int> prevSmallerElement(int *arr , int n){\n        stack<int> st;\n        st.push(-1);\n        vector<int> ans(n);\n        \n        for(int i = 0; i < n ; i++){\n            int curr = arr[i];\n            \n            while(st.top() != -1 && arr[st.top()] >= curr){\n                st.pop();\n            }\n            \n            ans[i] = st.top();\n            st.push(i);\n        }\n        return ans;\n    }\n    \n    int largestRectangleArea(int * heights , int n){\n        int area = INT_MIN;\n        \n        vector<int> next(n);\n        next = nextSmallerElement(heights , n);\n        \n        vector<int> prev(n);\n        prev = prevSmallerElement(heights , n);\n        \n        for(int i = 0 ; i < n ; i++){\n            int length = heights[i];\n            \n            if(next[i] == -1)\n                next[i] = n;\n            \n            int breadth = next[i] - prev[i] - 1;\n            int newArea = length * breadth;\n            area = max(area , newArea);\n        }\n        return area;\n    }\n    \npublic:\n    int maximalRectangle(vector<vector<char>>& matrix) {\n        \n        int n = matrix.size();\n        int m = matrix[0].size();\n        int M[n][m];\n        \n        for(int i = 0 ; i < n ; i++){\n            for(int j = 0 ; j < m ; j++){\n                M[i][j] = matrix[i][j] - '0';\n            }\n        }\n                \n        //step 1 : compute area of 1st row\n        int area = largestRectangleArea(M[0] , m);\n        \n        for(int i = 1 ; i < n ; i++){\n            for(int j = 0 ; j < m ; j++){\n                \n        //step 2 : add upar wala element if it is 1\n                if(M[i][j] != 0)\n                    M[i][j] = M[i][j] + M[i-1][j];\n                    \n                else\n                    M[i][j] = 0;\n            }\n            \n            area = max(area , largestRectangleArea(M[i] , m));\n        }\n        return area;\n    }\n};"
    },
    {
        "title": "Walking Robot Simulation II",
        "algo_input": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions (\"North\", \"East\", \"South\", and \"West\"). A robot is initially at cell (0, 0) facing direction \"East\".\n\nThe robot can be instructed to move for a specific number of steps. For each step, it does the following.\n\n\n\tAttempts to move forward one cell in the direction it is facing.\n\tIf the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.\n\n\nAfter the robot finishes moving the number of steps required, it stops and awaits the next instruction.\n\nImplement the Robot class:\n\n\n\tRobot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\".\n\tvoid step(int num) Instructs the robot to move forward num steps.\n\tint[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].\n\tString getDir() Returns the current direction of the robot, \"North\", \"East\", \"South\", or \"West\".\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]\nOutput\n[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]\n\nExplanation\nRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2);  // It moves two steps East to (2, 0), and faces East.\nrobot.step(2);  // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2);  // It moves one step East to (5, 0), and faces East.\n                // Moving the next step East would be out of bounds, so it turns and faces North.\n                // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1);  // It moves one step North to (5, 2), and faces North (not West).\nrobot.step(4);  // Moving the next step North would be out of bounds, so it turns and faces West.\n                // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"\n\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= width, height &lt;= 100\n\t1 &lt;= num &lt;= 105\n\tAt most 104 calls in total will be made to step, getPos, and getDir.\n\n",
        "solution_py": "class Robot:\n\n    def __init__(self, width: int, height: int):\n        self.perimeter = 2*width + 2*(height - 2)\n        self.pos = 0\n        self.atStart = True\n\n        self.bottomRight = width - 1\n        self.topRight = self.bottomRight + (height - 1)\n        self.topLeft = self.topRight + (width - 1)\n\n    def step(self, num: int) -> None:\n        self.atStart = False\n        self.pos = (self.pos + num) % self.perimeter\n\n    def getPos(self) -> List[int]:\n        if 0 <= self.pos <= self.bottomRight:\n            return [self.pos, 0]\n\n        if self.bottomRight < self.pos <= self.topRight:\n            return [self.bottomRight, self.pos - self.bottomRight]\n\n        if self.topRight < self.pos <= self.topLeft:\n            return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]\n        \n        return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]\n\n    def getDir(self) -> str:\n        if self.atStart or 0 < self.pos <= self.bottomRight:\n            return 'East'\n\n        if self.bottomRight < self.pos <= self.topRight:\n            return 'North'\n\n        if self.topRight < self.pos <= self.topLeft:\n            return 'West'\n        \n        return 'Sout",
        "solution_js": "const EAST = \"East\";\nconst NORTH = \"North\";\nconst WEST = \"West\";\nconst SOUTH = \"South\";\n\nconst DIRECTIONS = [EAST, NORTH, WEST, SOUTH];\nconst ORIGIN = [0,0];\n\n/**\n * @param {number} width\n * @param {number} height\n */\nvar Robot = function(width, height) {\n    this.width = width;\n    this.height = height;\n\n    this.path = []; // circular buffer of entire path of robot\n    this.dirAtSquare = []; // dir robot is facing at each square\n    this.currentPos = -1;\n\n    this.preprocess();\n};\n\n/**\n * Loop around the map once and store the path into a circular buffer.\n *\n * (0,0) is set to face SOUTH. The only time it is EAST is at the beginning\n * if the robot didn't move at all.\n *\n * @return {void}\n */\nRobot.prototype.preprocess = function() {\n    // go right\n    for (let i = 1; i < this.width; i++) {\n        this.path.push([i, 0]);\n        this.dirAtSquare.push(0);\n    }\n\n    // go up\n    const xMax = this.width - 1;\n    for (let i = 1; i < this.height; i++) {\n        this.path.push([xMax, i]);\n        this.dirAtSquare.push(1);\n    }\n\n    // go left\n    const yMax = this.height - 1;\n    for (let i = xMax - 1; i >= 0; i--) {\n        this.path.push([i, yMax]);\n        this.dirAtSquare.push(2);\n    }\n\n    // go down\n    const xMin = 0;\n    for (let i = yMax - 1; i >= 0; i--) {\n        this.path.push([xMin, i]);\n        this.dirAtSquare.push(3);\n    }\n}\n\n/**\n * @param {number} num\n * @return {void}\n */\nRobot.prototype.step = function(num) {\n    this.currentPos += num;\n};\n\n/**\n * @return {number[]}\n */\nRobot.prototype.getPos = function() {\n    return this.currentPos === -1\n        ? ORIGIN // we haven't moved\n        : this.path[this.currentPos % this.path.length];\n};\n\n/**\n * @return {string}\n */\nRobot.prototype.getDir = function() {\n    return this.currentPos === -1\n        ? DIRECTIONS[0] // we haven't moved\n        : DIRECTIONS[this.dirAtSquare[this.currentPos % this.dirAtSquare.length]];\n};\n\n/**\n * Your Robot object will be instantiated and called as such:\n * var obj = new Robot(width, height)\n * obj.step(num)\n * var param_2 = obj.getPos()\n * var param_3 = obj.getDir()\n */",
        "solution_java": "class Robot {\n\n    int p;\n    int w;\n    int h;\n    public Robot(int width, int height) {\n        w = width - 1;\n        h = height - 1;\n        p = 0;\n    }\n\n    public void step(int num) {\n        p += num;\n    }\n\n    public int[] getPos() {\n        int remain = p % (2 * (w + h));\n        if (remain <= w)\n            return new int[]{remain, 0};\n        remain -= w;\n        if (remain <= h)\n            return new int[]{w, remain};\n        remain -= h;\n        if (remain <= w)\n            return new int[]{w - remain, h};\n        remain -= w;\n        return new int[]{0, h - remain};\n    }\n\n    public String getDir() {\n        int[] pos = getPos();\n        if (p == 0 || pos[1] == 0 && pos[0] > 0)\n            return \"East\";\n        else if (pos[0] == w && pos[1] > 0)\n            return \"North\";\n        else if (pos[1] == h && pos[0] < w)\n            return \"West\";\n        else\n            return \"South\";\n    }\n}",
        "solution_c": "class Robot {\nprivate:\n    int width, height, perimeter;\n    int dir = 0;\n    int x = 0, y = 0;\n    map<int, string> mp = {{0, \"East\"}, {1, \"North\"}, {2, \"West\"}, {3, \"South\"}};\n\npublic:\n    Robot(int width, int height) {\n        this->width = width;\n        this->height = height;\n        this->perimeter = 2 * (height + width) - 4;\n    }\n    \n    void step(int num) {\n\t\tif(!num) return;\n        num = num % perimeter;\n        if(x == 0 && y == 0 && num == 0) dir = 3;\n        while(num--){\n            if(x == 0 && y == 0) dir = 0;\n            else if(x == width-1 && y == 0) dir = 1;\n            else if(x == width-1 && y == height-1) dir = 2;\n            else if(x == 0 && y == height-1) dir = 3;\n            \n            if(dir == 0) x += 1; \n            if(dir == 1) y += 1;\n            if(dir == 2) x -= 1;\n            if(dir == 3) y -= 1;\n        }\n        \n    }\n    \n    vector<int> getPos() {\n        return {x, y};\n    }\n    \n    string getDir() {\n        return mp[dir];\n    }\n};"
    },
    {
        "title": "Apply Discount Every n Orders",
        "algo_input": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].\n\nWhen a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product).\n\nThe supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100).\n\nImplement the Cashier class:\n\n\n\tCashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices.\n\tdouble getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]\nOutput\n[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]\nExplanation\nCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]);                        // return 500.0. 1st customer, no discount.\n                                                     // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]);                      // return 4000.0. 2nd customer, no discount.\n                                                     // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]);    // return 800.0. 3rd customer, 50% discount.\n                                                     // Original bill = 1600\n                                                     // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]);                           // return 4000.0. 4th customer, no discount.\ncashier.getBill([7,3],[10,10]);                      // return 4000.0. 5th customer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.\n                                                     // Original bill = 14700, but with\n                                                     // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]);                    // return 2500.0.  6th customer, no discount.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= discount &lt;= 100\n\t1 &lt;= products.length &lt;= 200\n\tprices.length == products.length\n\t1 &lt;= products[i] &lt;= 200\n\t1 &lt;= prices[i] &lt;= 1000\n\tThe elements in products are unique.\n\t1 &lt;= product.length &lt;= products.length\n\tamount.length == product.length\n\tproduct[j] exists in products.\n\t1 &lt;= amount[j] &lt;= 1000\n\tThe elements of product are unique.\n\tAt most 1000 calls will be made to getBill.\n\tAnswers within 10-5 of the actual value will be accepted.\n\n",
        "solution_py": "class Cashier:\n\n    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n        \n        self.n = n \n        self.discount = discount \n        self.price = { }\n        self.customer = 0 \n        \n        for i in range(len(products))  : \n            self.price[products[i]] = prices[i]\n\n    def getBill(self, product: List[int], amount: List[int]) -> float:\n        \n        self.customer += 1\n        \n        bill = 0 \n        \n        for i in range(len(product)) : \n            bill += amount[i] * self.price[product[i]]\n        \n        \n        if self.customer == self.n : \n            bill = bill * (1 - self.discount / 100)\n            self.customer = 0 \n            \n            \n        return bill\n            \n        \n\n\n# Your Cashier object will be instantiated and called as such:\n# obj = Cashier(n, discount, products, prices)\n# param_1 = obj.getBill(product,amount)",
        "solution_js": "var Cashier = function(n, discount, products, prices) {\n    this.n = n;\n    this.cc = 0;\n    this.discount = (100 - discount) / 100;\n    this.products = new Map();\n    const len = products.length;\n    for(let i = 0; i < len; i++) {\n        this.products.set(products[i], prices[i]);\n    }\n};\n\nCashier.prototype.getBill = function(product, amount) {\n    let total = 0, len = product.length;\n    for(let i = 0; i < len; i++) {\n        total += amount[i] * this.products.get(product[i]);\n    }\n    this.cc++;\n    if(this.cc % this.n == 0) {\n        total = total * this.discount;\n        this.cc = 0;\n    }\n    return total;\n};",
        "solution_java": "class Cashier {\n    private Map<Integer, Integer> catalogue;\n    \n    private int n;\n    private double discount;\n    private int orderNumber;\n    \n    public Cashier(int n, int discount, int[] products, int[] prices) {\n        this.catalogue = new HashMap<>();\n        \n        for (int i = 0; i < prices.length; i++) {\n            this.catalogue.put(products[i], prices[i]);\n        }\n        \n        this.n = n;\n        this.discount = ((double) 100 - discount)/100;\n        this.orderNumber = 0;\n    }\n    \n    public double getBill(int[] product, int[] amount) {\n        this.orderNumber++;\n        \n        double bill = 0.0;\n        for (int i = 0; i < amount.length; i++) {\n            int p = product[i];\n            int price = this.catalogue.get(p);\n            bill += price*amount[i];\n        }\n        \n        if (this.orderNumber % n == 0)\n            bill *= this.discount;\n        \n        return bill;\n    }\n}\n\n/**\n * Your Cashier object will be instantiated and called as such:\n * Cashier obj = new Cashier(n, discount, products, prices);\n * double param_1 = obj.getBill(product,amount);\n */",
        "solution_c": "class Cashier {\npublic:\n    int nn = 0;\n    double dis = 0;\n    vector<int> pro;\n    vector<int> pri;\n    int currCustomer = 0; //Declaring these variables here to use it in other fxns as well\n    \n    Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {\n        nn = n;\n        dis = discount;\n        pro = products;\n        pri = prices; //Assigning given values to our created variables\n    }\n    \n    double getBill(vector<int> product, vector<int> amount) {\n        currCustomer++; //Increasing customer count\n        double bill = 0; //Bill anount set to 0\n        for(int i = 0; i < product.size(); i++){ //Iterating over every product\n            int proId = 0; \n            \n            while(pro[proId] != product[i]) proId++; //Finding product ID index\n            \n            bill = bill + (amount[i]*pri[proId]); //Adding total amount to bill\n        }\n        \n        if(currCustomer == nn){ //Checking if the customer is eligible for discount\n            bill = bill * (1 - dis/100); //Giving discount\n            currCustomer = 0; //Setting customer count to 0 so next third person can have discount\n        }\n        return bill; //Returning final bill amount\n    }\n};"
    },
    {
        "title": "Combination Sum",
        "algo_input": "Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.\n\nThe same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.\n\nIt is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.\n\n&nbsp;\nExample 1:\n\nInput: candidates = [2,3,6,7], target = 7\nOutput: [[2,2,3],[7]]\nExplanation:\n2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.\n\n\nExample 2:\n\nInput: candidates = [2,3,5], target = 8\nOutput: [[2,2,2,2],[2,3,3],[3,5]]\n\n\nExample 3:\n\nInput: candidates = [2], target = 1\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= candidates.length &lt;= 30\n\t1 &lt;= candidates[i] &lt;= 200\n\tAll elements of candidates are distinct.\n\t1 &lt;= target &lt;= 500\n\n",
        "solution_py": "class Solution:\n    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n\n        path = []\n        answer = []\n        def dp(idx, total):\n            if total == target:\n                answer.append(path[:])\n                return\n            if total > target:\n                return\n\n            for i in range(idx, len(candidates)):\n                path.append(candidates[i])\n                dp(i, total + candidates[i])\n                path.pop()\n\n        dp(0, 0)\n        return answer",
        "solution_js": "function recursion(index, list, target, res, arr){\n    if(index == arr.length){\n        if(target == 0){\n            res.push([...list]);\n        }\n        return;\n    }\n\n    if(arr[index] <= target){\n\n         list.push(arr[index]);\n\n         recursion(index, list, target - arr[index], res, arr);\n\n         list.pop();\n\n    }\n\n    recursion(index + 1, list, target, res, arr);\n\n}\nvar combinationSum = function(candidates, target) {\n    let res = [];\n    recursion(0, [], target, res, candidates);\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> combinationSum(int[] candidates, int target) {\n        List<Integer> cur = new ArrayList<>();\n        List<List<Integer>> result = new ArrayList<>();\n        Arrays.sort(candidates);\n        dfs(0, candidates, target, 0, cur, result);\n        return result;\n    }\n    public void dfs(int start, int[] candidates, int target, int sum, List<Integer> cur, List<List<Integer>> result){\n        if(sum == target){\n            result.add(new ArrayList<>(cur));\n            return;\n        }\n        for(int i = start; i < candidates.length; i++) {\n            if(sum + candidates[i] <= target) {\n              cur.add(candidates[i]);\n              dfs(i, candidates, target, sum + candidates[i], cur, result);\n              cur.remove((cur.size()- 1));\n            }\n        }\n        return;\n    }\n}",
        "solution_c": "class Solution {\n    void combination(vector<int>& candidates, int target, vector<int> currComb, int currSum, int currIndex, vector<vector<int>>& ans){\n        if(currSum>target) return; //backtrack\n        if(currSum==target){\n            ans.push_back(currComb); //store the solution and backtrack\n            return;\n        }\n\n        for(int i=currIndex; i<candidates.size(); i++){ //try all possible options for the next level\n            currComb.push_back(candidates[i]); //put 1 option into the combination\n            currSum+=candidates[i];\n            combination(candidates, target, currComb, currSum, i, ans); //try with this combination, whether it gives a solution or not.\n            currComb.pop_back(); //when this option backtrack to here, remove this and go on to the next option.\n            currSum-=candidates[i];\n        }\n\n    }\npublic:\n    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {\n        vector<vector<int>> ans;\n        vector<int> currComb;\n        combination(candidates, target, currComb, 0, 0, ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Matrix Sum",
        "algo_input": "You are given an n x n integer matrix. You can do the following operation any number of times:\n\n\n\tChoose any two adjacent elements of matrix and multiply each of them by -1.\n\n\nTwo elements are considered adjacent if and only if they share a border.\n\nYour goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,-1],[-1,1]]\nOutput: 4\nExplanation: We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.\n\n\nExample 2:\n\nInput: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput: 16\nExplanation: We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t2 &lt;= n &lt;= 250\n\t-105 &lt;= matrix[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n        # count -'s\n        count = 0\n        for row in matrix:\n            for col_num in row:\n                if col_num < 0:\n                    count += 1\n        tot_sum = sum([sum([abs(x) for x in row])\n                       for row in matrix])\n        if count % 2 == 0:\n            return tot_sum\n        else:\n            min_val = min([min([abs(x) for x in row])\n                       for row in matrix])\n            return tot_sum - 2 * min_val",
        "solution_js": "var maxMatrixSum = function(matrix) {\n    const MAX= Number.MAX_SAFE_INTEGER;\n\n    const m = matrix.length;\n    const n = matrix[0].length;\n\n    let negs = 0;\n\n    let totAbsSum = 0;\n    let minAbsNum = MAX;\n\n    for (let i = 0; i < n; ++i) {\n        for (let j = 0; j < n; ++j) {\n            if (matrix[i][j] < 0) ++negs;\n\n            totAbsSum += Math.abs(matrix[i][j]);\n            minAbsNum = Math.min(minAbsNum, Math.abs(matrix[i][j]));\n        }\n    }\n\n    if (negs % 2 === 1) totAbsSum -= (2 * minAbsNum);\n\n    return totAbsSum;\n};",
        "solution_java": "class Solution {\n    public long maxMatrixSum(int[][] matrix) {\n        long ans = 0;\n        int neg = 0;\n        int min = Integer.MAX_VALUE;\n        for(int i = 0; i < matrix.length; i++){\n            for(int j = 0; j < matrix[0].length; j++){\n                if(matrix[i][j] < 0) {\n                    neg++;\n                }\n                ans += Math.abs(matrix[i][j]);\n                if(min > Math.abs(matrix[i][j]))\n                \tmin = Math.abs(matrix[i][j]);\n            }\n        }\n        if(neg % 2 == 0)\n        \treturn ans;\n        else\n        \treturn ans - 2*min;\n    }\n}",
        "solution_c": "/**\n * @author      : archit\n * @GitHub      : archit-1997\n * @Email       : architsingh456@gmail.com\n * @file        : maximumMatrixSum.cpp\n * @created     : Saturday Aug 21, 2021 20:11:56 IST\n */\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    long long maxMatrixSum(vector<vector<int>>& matrix) {\n        int r=matrix.size(),c=matrix[0].size();\n\n        //we need to find the min number in the matrix and also count of negative numbers in the matrix\n        int small=INT_MAX,count=0;\n        long long int sum=0;\n\n        for(int i=0;i<r;i++){\n            for(int j=0;j<c;j++){\n                int val=matrix[i][j];\n\t\t\t\t//finding the smallest absolute value in the matrix\n                small=min(small,abs(val));\n\t\t\t\t//counting the negative numbers\n                if(val<0)\n                    count++;\n\t\t\t\t//finding the sum of all the values\n                sum+=abs(val);\n            }\n        }\n\t\t//if even number of negatives, then just return sum\n        if(count%2==0)\n            return sum;\n        else\n\t\t//subtract the value of the min absolute element\n            return sum-2*small;\n    }\n};"
    },
    {
        "title": "As Far from Land as Possible",
        "algo_input": "Given an n x n grid&nbsp;containing only values 0 and 1, where&nbsp;0 represents water&nbsp;and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance.&nbsp;If no land or water exists in the grid, return -1.\n\nThe distance used in this problem is the Manhattan distance:&nbsp;the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,0,1],[0,0,0],[1,0,1]]\nOutput: 2\nExplanation: The cell (1, 1) is as far as possible from all the land with distance 2.\n\n\nExample 2:\n\nInput: grid = [[1,0,0],[0,0,0],[0,0,0]]\nOutput: 4\nExplanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 &lt;= n&nbsp;&lt;= 100\n\tgrid[i][j]&nbsp;is 0 or 1\n\n",
        "solution_py": "from collections import *\nclass Solution:\n    def maxDistance(self, grid) -> int:\n        m,n=len(grid),len(grid[0])\n        queue=deque([])\n        for i in range(m):\n            for j in range(n):\n                if grid[i][j]==1:\n                    queue.append((i,j))\n        c=-1\n        while queue:\n            # print(queue)\n            temp=len(queue)\n            for _ in range(temp):\n                (i,j)=queue.popleft()\n                for (x,y) in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):\n                    if x < 0 or x >= m or y < 0 or y >= n or grid[x][y]==1:\n                        continue\n                    grid[x][y]=1\n                    queue.append((x,y))\n            c+=1\n        return c if c!=0 else -1",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst DIR = [\n    [0,1],\n    [0,-1],\n    [1,0],\n    [-1,0]\n];\nvar maxDistance = function(grid) {\n    const ROWS = grid.length;\n    const COLS = grid[0].length;\n    const cost = new Array(ROWS).fill().map(()=>new Array(COLS).fill(Infinity));\n    const que = [];\n    for(let row=0; row<ROWS; row++) {\n        for(let col=0; col<COLS; col++) {\n            if(grid[row][col] === 1) {\n                que.push([row, col]);\n                cost[row][col] = 0;\n            }\n        }\n    }\n    if(que.length == 0 || que.length == ROWS * COLS) return -1;\n    while(que.length) {\n        const [row, col] = que.shift();\n        for(const dir of DIR) {\n            const newRow = row+dir[0];\n            const newCol = col+dir[1];\n            if(newRow < 0 || newCol < 0 || newRow >= ROWS || newCol >= COLS) continue;\n            if(cost[newRow][newCol] > cost[row][col] + 1) {\n                cost[newRow][newCol] = cost[row][col] + 1;\n                que.push([newRow, newCol]);\n            }\n        }\n    }\n    let max = 0;\n    for(const row of cost) {\n        max = Math.max(max, ...row);\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    class Point {\n        int x, y;\n        public Point(int x, int y){\n            this.x=x;\n            this.y=y;\n        }\n    }\n    int[][] dist;\n    int n,ans;\n    int[] dx={0, 0, +1, -1};\n    int[] dy={+1, -1, 0, 0};\n    public int maxDistance(int[][] grid) {\n        n=grid.length;\n        dist = new int[n][n];\n        Queue<Point> q = new LinkedList<>();\n        for (int i=0;i<n;i++){\n            for (int j=0;j<n;j++){\n                if (grid[i][j]==0) dist[i][j]=2*1000*1000*1000;\n                else {\n                    dist[i][j]=0;\n                    q.add(new Point(i, j)); // multisource on grid[i][j] = 1\n                }\n            }\n        }\n        ans=-1;\n        while(!q.isEmpty()){\n            Point p = q.poll();\n            int x = p.x;\n            int y = p.y;\n            for (int k = 0; k < 4; k++) {\n                int r=dx[k]+x;\n                int c=dy[k]+y;\n                if (valid(r,c)&&grid[r][c]==0&&dist[r][c]>dist[x][y]+1){\n                    dist[r][c]=dist[x][y]+1;\n                    Point newP = new Point(r,c);\n                    q.add(newP);\n                }\n            }\n        }\n        for (int i=0;i<n;i++){\n            for (int j=0;j<n;j++){\n                ans=Math.max(ans,dist[i][j]); // Manhattan distance is the same as the distance on the grid in general \n            }\n        }\n        if (ans==0||ans==2*1000*1000*1000) ans=-1;\n        return ans;\n    }\n    public boolean valid(int r, int c){\n        return r>=0&&c>=0&&r<n&&c<n;\n    }\n}",
        "solution_c": "class Solution {\n    vector<int> dr = {0,0,1,-1};\n    vector<int> dc = {1,-1,0,0};\npublic:\n    bool isPos(int r,int c,int n){\n        return ( r>=0 && c>=0 && r<n && c<n );\n    }\n\n    int maxDistance(vector<vector<int>>& grid) {\n        int n = grid.size();\n        vector< vector<int> > dist(n,vector<int>(n,-1));\n        queue< vector<int> > pq;\n        for(int i=0 ; i<n ; i++){\n            for(int j=0 ; j<n ; j++){\n                if( 1==grid[i][j] ){\n                    dist[i][j] = 0;\n                    pq.push({i,j});\n                }\n            }\n        }\n        int ans = 0;\n        while( !pq.empty() ){\n            vector<int> vect = pq.front();\n            pq.pop();\n            int r = vect[0];\n            int c = vect[1];\n            if( 0==grid[r][c] ){\n                ans = max(ans,dist[r][c]);\n            }\n            for(int i=0 ; i<4 ; i++){\n                int nr = r+dr[i];\n                int nc = c+dc[i];\n                if( isPos(nr,nc,n) && -1==dist[nr][nc] ){\n                    dist[nr][nc] = dist[r][c]+1;\n                    pq.push({nr,nc});\n                }\n            }\n        }\n        return (ans==0 ? -1 : ans);\n    }\n};"
    },
    {
        "title": "Grid Illumination",
        "algo_input": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.\n\nYou are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.\n\nWhen a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\n\nYou are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].\n\nReturn an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput: [1,0]\nExplanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th&nbsp;query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\nThe 1st&nbsp;query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n\n\n\nExample 2:\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput: [1,1]\n\n\nExample 3:\n\nInput: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput: [1,1,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\t0 &lt;= lamps.length &lt;= 20000\n\t0 &lt;= queries.length &lt;= 20000\n\tlamps[i].length == 2\n\t0 &lt;= rowi, coli &lt; n\n\tqueries[j].length == 2\n\t0 &lt;= rowj, colj &lt; n\n\n",
        "solution_py": "class Solution:\n    def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n        rows = collections.Counter()\n        cols = collections.Counter()\n        diags1 = collections.Counter()\n        diags2 = collections.Counter()\n        lamps = {tuple(lamp) for lamp in lamps}\n        \n        for i, j in lamps:\n            rows[i] += 1\n            cols[j] += 1\n            diags1[i + j] += 1\n            diags2[i - j] += 1\n        \n        ans = []\n        directions = ((-1, -1), (-1, 0), (-1, 1),\n                      (0, -1), (0, 0), (0, 1),\n                      (1, -1), (1, 0), (1, 1))\n        \n        for i, j in queries:\n            if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:\n                ans.append(1)\n            else:\n                ans.append(0)\n            \n            for di, dj in directions:\n                newI, newJ = i + di, j + dj\n                if (newI, newJ) not in lamps:\n                    continue\n                lamps.remove((newI, newJ))\n                rows[newI] -= 1\n                cols[newJ] -= 1\n                diags1[newI + newJ] -= 1\n                diags2[newI - newJ] -= 1\n        \n        return ans",
        "solution_js": "var gridIllumination = function(n, lamps, queries) {\n    const directions = [[0,0], [-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]];\n    const lampCoord = new Map();    \n    const rowHash = {}, colHash = {}, leftDiag = {}, rightDiag = {};\n    \n    // First, illuminate the lamps\n    for (let [r, c] of lamps) {\n        if (lampCoord.has(`${r}-${c}`)) continue;\n        lampCoord.set(`${r}-${c}`);\n        rowHash[r] = rowHash[r] + 1 || 1;\n        colHash[c] = colHash[c] + 1 || 1;\n        leftDiag[r + c] = leftDiag[r + c] + 1 || 1;\n        rightDiag[c - r] = rightDiag[c - r] + 1 || 1;\n    }\n    \n    // Second, query the lamps\n    let output = [];\n    for (let [row, col] of queries) query(row, col);\n    return output;\n\n    function query(row, col) {\n        if (rowHash[row] || colHash[col] || leftDiag[row + col] || rightDiag[col - row]) {\n            output.push(1);\n\t\t\t// Check 8 adjacent cells\n            for (let [r, c] of directions) {\n                let newR = row + r, newC = col + c;\n                if (newR < 0 || newC < 0 || newR >= n || newC >= n) continue;\n                // If the coordinate is a lamp, un-illuminate the lamp\n                if (lampCoord.has(`${newR}-${newC}`)) {\n                    rowHash[newR]--, colHash[newC]--, leftDiag[newR + newC]--, rightDiag[newC - newR]--;\n                    lampCoord.delete(`${newR}-${newC}`);\n                }\n            }        \n        } else output.push(0);\n    }    \n};",
        "solution_java": "class Solution {\n    public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {\n        //we take 5 hashmap\n        //1st hashmap for row\n        HashMap<Integer, Integer> row = new HashMap<>();\n        //2nd hashmap for column\n        HashMap<Integer, Integer> col = new HashMap<>();\n        //3rd hashmap for lower diagonal\n        HashMap<Integer, Integer> d1 = new HashMap<>();\n        //4th diagonal for upper diagonal\n        HashMap<Integer, Integer> d2 = new HashMap<>();\n        //5th diagonal for cell no meaning lamp is present at this spot\n        HashMap<Integer, Integer> cellno = new HashMap<>();\n        \n        for(int i = 0;i<lamps.length;i++){\n            //get row and column from lamps array\n            int row1 = lamps[i][0];\n            int col1 = lamps[i][1];\n            //place row in row hashmap\n            row.put(row1, row.getOrDefault(row1, 0) + 1);\n            //place column in col hashmap\n            col.put(col1, col.getOrDefault(col1, 0) + 1);\n            //place d1 dia in d1\n            d1.put((row1+col1), d1.getOrDefault((row1+col1), 0) + 1);\n            //place d2 diagonal\n            d2.put((row1-col1), d2.getOrDefault((row1-col1), 0) + 1);\n            //place cellno in cell no hashmap\n            int cell = row1*n+col1;\n            cellno.put(cell, cellno.getOrDefault(cell, 0) + 1);\n        }\n        //direction array which travels in 8 adjacent direction\n        int[][] dir = {{-1, 0},{-1, 1},{0, 1},{1, 1},{1, 0},{1, -1},{0, -1},{-1, -1}};\n        int[] ans = new int[queries.length];\n        //process all queries\n        for(int i = 0;i<queries.length;i++){\n            int row1 = queries[i][0];\n            int col1 = queries[i][1];\n            int cell = row1 * n + col1;\n            ans[i] = (row.containsKey(row1) || col.containsKey(col1) || d1.containsKey(row1 + col1) || d2.containsKey(row1-col1) || cellno.containsKey(cell))? 1:0;\n            //if query has a bulb\n            if(cellno.containsKey(cell)){\n                \n                    int val = cellno.get(cell);\n                    \n                        cellno.remove(cell);\n                    \n                    //for row \n                    if(row.containsKey(row1)){\n                        int rowval = row.get(row1);\n                        rowval-=val;\n                        if(rowval == 0){\n                            row.remove(row1);\n                        }else{\n                            row.put(row1, rowval);\n                        }    \n                    }\n                    \n                    //for col\n                    if(col.containsKey(col1)){\n                        int colval = col.get(col1);\n                        colval-=val;\n                        if(colval == 0){\n                            col.remove(col1);\n                        }else{\n                            col.put(col1, colval);\n                        }    \n                    }\n                    \n                    //for d1\n                    if(d1.containsKey(row1+col1)){\n                        int d1val = d1.get(row1+col1);\n                        d1val-=val;\n                        if(d1val == 0){\n                            d1.remove(row1+col1);\n                        }else{\n                            row.put((row1+col1), d1val);\n                        }    \n                    }\n                    \n                    //for d2\n                    if(d2.containsKey(row1 - col1)){\n                        int d2val = d2.get(row1-col1);\n                        d2val-=val;\n                        if(d2val == 0){\n                            d2.remove(row1-col1);\n                        }else{\n                            d2.put((row1-col1), d2val);\n                        }    \n                    }\n            }\n            //moves all 8 direction and remove the illumination \n            for(int j = 0;j<dir.length;j++){\n                int rowdash = row1 + dir[j][0];\n                int coldash = col1 + dir[j][1];\n                int cellno1 = rowdash * n + coldash;\n                if(cellno.containsKey(cellno1)){\n                    int val = cellno.get(cellno1);\n                    \n                        cellno.remove(cellno1);\n                    \n                    //for row\n                    if(row.containsKey(rowdash)){\n                        int rowval = row.get(rowdash);\n                        rowval -= val;\n                        if(rowval == 0){\n                            row.remove(rowdash);\n                        }else{\n                            row.put(rowdash, rowval);\n                        }    \n                    }\n                    \n                    //for col\n                    if(col.containsKey(coldash)){\n                        int colval = col.get(coldash);\n                        colval-=val;\n                        if(colval == 0){\n                            col.remove(coldash);\n                        }else{\n                            col.put(coldash, colval);\n                        }    \n                    }\n                    \n                    //for d1\n                    if(d1.containsKey(rowdash+coldash)){\n                        int d1val = d1.get(rowdash+coldash);\n                        d1val-=val;\n                        if(d1val == 0){\n                            d1.remove(rowdash+coldash);\n                        }else{\n                            row.put((rowdash+coldash), d1val);\n                        }    \n                    }\n                    \n                    //for d2\n                    if(d2.containsKey(rowdash - coldash)){\n                        int d2val = d2.get(rowdash-coldash);\n                        d2val-=val;\n                        if(d2val == 0){\n                            d2.remove(rowdash-coldash);\n                        }else{\n                            d2.put((rowdash-coldash), d2val);\n                        }    \n                    }\n                    \n                    \n                }\n            }\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // store info about rows , coulms and diagonal that is illuminated\n    // if (i,j) is lamp , then every cell (x,y) is illuminated if\n    // x==i (row) || y==j (column) || x+y == i+j (anti diagonal) || x-y == i-j (main diagonal)\n    vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {\n\n        vector<int>ans;\n        unordered_map<int,int>row,col,mainDiag,antiDiag;\n        set<pair<int,int>>s;\n\n        for(auto &l : lamps){\n            int x = l[0],y=l[1];\n            // Even if the same lamp is listed more than once, it is turned on.\n            // To prevent duplicate entries\n            if(s.find({x,y}) == s.end())\n            {\n                row[x]++;\n                col[y]++;\n                antiDiag[x+y]++;\n                mainDiag[x-y]++;\n                s.insert({x,y}); // This helps us to get the lamp in O(1)\n            }\n        }\n\n        for(auto &q : queries)\n        {\n            // For every query {x,y} do 2 things :\n            // 1. Check whether grid[x][y] is illuminated or not, accordingly set answer either to '1' OR '0'\n            // 2. if grid is illuminated, turn off the lamps at {x,y} and 8 adjacent lamps = 9 lamps\n\n            int x = q[0],y = q[1];\n            if(row[x]>0 or col[y]>0 or antiDiag[x+y]>0 or mainDiag[x-y]>0)\n            {\n                // illumination\n                ans.push_back(1);\n\n                // Turn off the 9 lamps = 1 center and 8 adjacent lamps\n                for(int i=-1;i<=1;i++){\n                    for(int j=-1;j<=1;j++){\n\n                        int nx = x+i;\n                        int ny = y+j;\n                        // NxN board, check boundaries condition\n                        if(nx >= 0 and nx < n and ny >=0 and ny < n and s.find({nx,ny})!=s.end())\n                        {\n                            row[nx]--;\n                            col[ny]--;\n                            antiDiag[nx+ny]--;\n                            mainDiag[nx-ny]--;\n                            s.erase({nx,ny});\n                        }\n                    }\n                }\n            }\n            else // No illumination\n                ans.push_back(0);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Gap",
        "algo_input": "Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.\n\nYou must write an algorithm that runs in linear time and uses linear extra space.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,6,9,1]\nOutput: 3\nExplanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n\n\nExample 2:\n\nInput: nums = [10]\nOutput: 0\nExplanation: The array contains less than 2 elements, therefore return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maximumGap(self, nums: List[int]) -> int:\n        if len(nums)<2: return 0\n        \n        #radix sort\n        #N = length of nums\n        #find number of digits in largest number - O(K) where K = length of largest number\n        longest = 0\n        for i in nums:\n            longest = max(longest,len(str(i)))\n            \n        #normalize so that all numbers have same number of digits by adding 0s at the start of shorter numbers - O(N*K)\n        for i in range(len(nums)):\n            if len(str(nums[i]))!=longest:\n                nums[i] = '0'*(longest-len(str(nums[i]))) + str(nums[i])\n            else:\n                nums[i] = str(nums[i])\n        \n        #apply counting sort starting with each digit from the end of the last digits - O(K*N)\n        for digit in range(longest-1,-1,-1):\n            vals = [[] for k in range(10)]\n            for num in nums:\n                vals[int(num[digit])] += [num]\n\t\t\t#join list sorted by that digit position together:\n            new = []\n            for i in vals:\n                new += i\n            nums = new.copy()\n        \n        #find the largest difference in the now sorted nums - O(N)\n        best_diff = 0\n        for i in range(1,len(nums)):\n            best_diff = max(best_diff,int(nums[i])-int(nums[i-1]))\n        return best_diff\n    \n#Overall complexity is O(N*K) but K is at most 10 so O(10*N) = O(N) so linear\n#Please correct me if I am wrong!",
        "solution_js": "/**\n * The buckets solution.\n *\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n *\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumGap = function(nums) {\n    const n = nums.length\n\n    if (n < 2) {\n        return 0\n    }\n\n    if (n < 3) {\n        return Math.abs(nums[0] - nums[1])\n    }\n\n    let maxNum = -Infinity\n    let minNum = +Infinity\n\n    for (let i = 0; i < n; i++) {\n        maxNum = Math.max(maxNum, nums[i])\n        minNum = Math.min(minNum, nums[i])\n    }\n\n    if (maxNum === minNum) {\n        return 0\n    }\n\n    const k = n - 1\n    const averageGap = (maxNum - minNum) / k\n\n    const minBuckets = new Array(k)\n    const maxBuckets = new Array(k)\n\n    minBuckets[0] = minNum\n    maxBuckets[0] = minNum\n\n    minBuckets[k - 1] = maxNum\n    maxBuckets[k - 1] = maxNum\n\n    for (let i = 0; i < n; i++) {\n        if (minNum === nums[i] || nums[i] === maxNum) {\n            continue\n        }\n\n        const j = Math.floor((nums[i] - minNum) / averageGap)\n\n        minBuckets[j] = minBuckets[j] ? Math.min(minBuckets[j], nums[i]) : nums[i]\n        maxBuckets[j] = maxBuckets[j] ? Math.max(maxBuckets[j], nums[i]) : nums[i]\n    }\n\n    let largestGap = 0\n    let prevMaxIndex = 0\n\n    for (let i = 1; i < n - 1; i++) {\n        if (minBuckets[i]) {\n            largestGap = Math.max(largestGap, minBuckets[i] - maxBuckets[prevMaxIndex])\n        }\n\n        if (maxBuckets[i]) {\n            prevMaxIndex = i\n        }\n    }\n\n    return largestGap\n}",
        "solution_java": "class Solution {\n    public int maximumGap(int[] nums) {\n        Arrays.sort(nums);\n        int res=0;\n        if(nums.length==0){\n            return 0;\n        }\n        for (int i =0;i<nums.length-1;i++){\n            res=Math.max(Math.abs(nums[i]-nums[i+1]),res);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumGap(vector<int>& nums) {\n        sort(nums.begin(),nums.end());\n        int res;\n        int maxx=INT_MIN;\n        map<int,int> m;\n        if(nums.size()==1)\n            return 0;\n        for(int i =0;i<nums.size()-1;i++)\n        {\n            m[i]=nums[i+1]-nums[i];\n        }\n        for(auto it: m)\n        {\n            if(it.second>maxx)\n            {\n                maxx=it.second;\n            }\n        }\n        return maxx;\n    }\n};"
    },
    {
        "title": "Minimum Rounds to Complete All Tasks",
        "algo_input": "You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.\n\nReturn the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.\n\n&nbsp;\nExample 1:\n\nInput: tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput: 4\nExplanation: To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4.  \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.\n\n\nExample 2:\n\nInput: tasks = [2,3,3]\nOutput: -1\nExplanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tasks.length &lt;= 105\n\t1 &lt;= tasks[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minimumRounds(self, tasks: List[int]) -> int:\n        dic={}\n        c=0\n        for i in tasks:\n            if i in dic.keys():\n                dic[i]+=1\n            else:\n                dic[i]=1\n        for i in dic.keys():\n            if dic[i]==1:\n                return -1\n            while dic[i]>=2:\n                if dic[i]-3>1:\n                    dic[i]-=3\n                    c+=1\n                else:\n                    dic[i]-=2\n                    c+=1\n        return c",
        "solution_js": "var minimumRounds = function(tasks) {\n    const hash = {};\n    let minRounds = 0;\n\n    for (const task of tasks) {\n        hash[task] = hash[task] + 1 || 1;\n    }\n\n    for (const count of Object.values(hash)) {\n        if (count < 2) return -1;\n        minRounds += Math.ceil(count / 3);\n    }\n\n    return minRounds;\n};",
        "solution_java": "/**\n\tEach round, we can complete either 2 or 3 tasks of the same difficulty level\n    Time: O(n)\n    Space: O(n)\n*/\nclass Solution {\n    public int minimumRounds(int[] tasks) {\n        int round = 0;\n        Map<Integer, Integer> taskMap = new HashMap<>(); // map of <task,  number of each task>\n        for (int i = 0; i < tasks.length; i++) {\n            taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);\n        }\n        \n        for (Map.Entry<Integer, Integer> entry : taskMap.entrySet()) {\n            if (entry.getValue() == 1) {\n                return -1; // we cannot complete if there is only 1 task\n            }\n\t\t\t// try to take as many 3's as possible\n            round += entry.getValue() / 3; \n\t\t\t\n            /*\n\t\t\t\tWe can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous\n\t\t\t\tex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]\n\t\t\t\tIn this example, treat the last [5,5,5], [5] as [5,5], [5,5]\n            */\n            if (entry.getValue() % 3 != 0) { \n                round++; \n            }\n        }\n        return round;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumRounds(vector<int>& tasks) {\n        map<int,int> hm;\n        for(int i=0;i<tasks.size();i++){\n            hm[tasks[i]]++;\n        }\n        int num,freq,ans=0;\n        for (auto i : hm){\n            freq = i.second;\n            if(freq==1)\n                return -1;\n            if(freq%3==0){\n                ans += freq/3;\n            }\n            else{\n                ans += freq/3 + 1;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Length of Longest Fibonacci Subsequence",
        "algo_input": "A sequence x1, x2, ..., xn is Fibonacci-like if:\n\n\n\tn &gt;= 3\n\txi + xi+1 == xi+2 for all i + 2 &lt;= n\n\n\nGiven a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.\n\nA subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,4,5,6,7,8]\nOutput: 5\nExplanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].\n\nExample 2:\n\nInput: arr = [1,3,7,11,12,14,18]\nOutput: 3\nExplanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 1000\n\t1 &lt;= arr[i] &lt; arr[i + 1] &lt;= 109\n\n",
        "solution_py": "class Solution(object): #DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A)\n    def lenLongestFibSubseq(self, A):\n        index = {Ai: i for i, Ai in enumerate(A)}\n        dp = collections.defaultdict(lambda: 2)\n        ans = 0\n        for k, Ak in enumerate(A): #Following IJK idiom here\n            for j in range(k-1,0,-1):            \n                i = index.get(Ak - A[j], None)\n                if Ak - A[j] >= A[j]: break #Pruning for illegal Ai\n                if i is not None and i < j:\n                    cur_len = dp[j, k] = dp[i, j] + 1\n                    ans = max(ans, cur_len)\n        \n        return ans # ans is either 0 or >=3 for SURE",
        "solution_js": "var lenLongestFibSubseq = function(arr) {\n    let ans = 2;\n    const set = new Set(arr);\n    const len = arr.length\n    for(let i = 0; i < len; i++) {\n        for(let j = i + 1; j < len; j++) {\n            let a = arr[i], b = arr[j], len = 2;\n            while(set.has(a + b)) {\n                len++;\n                let temp = a + b;\n                a = b;\n                b = temp;\n            }\n            ans = Math.max(len, ans);\n        }\n    }\n    return ans == 2 ? 0 : ans;\n};",
        "solution_java": "class Solution {\n    /*\n    * dp[i][j] is the max length of fibbonacci series whose last two elements\n    * are A[i] & A[j]\n    * for any integer A[k] we need to find two number A[i] & A[j] such that\n    * i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time\n    * complexity.\n    * if there exist i,j,k such that i < j < k and A[i] + A[j] == A[k] then\n    * dp[k][j] = dp[i][j] + 1 (A[k], A[j] are last two elements of fibbonacc series)\n    */\n    public int lenLongestFibSubseq(int[] A) {\n        int n = A.length;\n        int[][] dp = new int[n][n];\n        int result = 0;\n        for (int k = 2; k < n; k++) {\n            int i = 0, j = k-1;\n            while(i < j) {\n                int sum = A[i] + A[j] - A[k];\n                if (sum < 0) {\n                    i++;\n                } else if (sum > 0) {\n                    j--;\n                } else {\n                    // ith, jth kth element are fibbonaci sequence\n                    dp[j][k] = dp[i][j] + 1; // since numbers are unique\n                    result = Math.max(result, dp[j][k]);\n                    i++;\n                    j--;\n                }\n            }\n        }\n        return result + 2 >= 3? result + 2: 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int help(int i,int j, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp){\n\n        if(dp[i][j]!=-1)\n            return dp[i][j];\n\n        int x=nums[i]+nums[j];\n\n        if(mp.find(x)!=mp.end())\n        {\n            dp[i][j]=help(j,mp[x],mp,nums,dp);\n           return 1+dp[i][j];\n        }\n\n        return 1;\n    }\n\n   int solve(int idx ,int n, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp)\n    {\n        int maxi=INT_MIN;\n\n        for(int i=idx;i<n;i++)\n        {\n            for(int j=i+1;j<n;j++)\n            {\n\n                int x=nums[i]+nums[j];\n\n                if(mp.find(x)!=mp.end())\n                {\n                 maxi=max(maxi,2+help(j,mp[x],mp,nums,dp));\n                }\n            }\n        }\n        return (maxi==INT_MIN?0:maxi);\n    }\n    int lenLongestFibSubseq(vector<int>& arr) {\n\n        unordered_map<int,int> mp;\n        int n=arr.size();\n        vector<vector<int>> dp(n,vector<int> (n,-1));\n\n        for(int i=0;i<arr.size();i++)\n            mp[arr[i]]=i;\n\n       return solve(0,n,mp,arr,dp);\n\n    }\n};"
    },
    {
        "title": "Delete Characters to Make Fancy String",
        "algo_input": "A fancy string is a string where no three consecutive characters are equal.\n\nGiven a string s, delete the minimum possible number of characters from s to make it fancy.\n\nReturn the final string after the deletion. It can be shown that the answer will always be unique.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leeetcode\"\nOutput: \"leetcode\"\nExplanation:\nRemove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".\n\n\nExample 2:\n\nInput: s = \"aaabaaaa\"\nOutput: \"aabaa\"\nExplanation:\nRemove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".\n\n\nExample 3:\n\nInput: s = \"aab\"\nOutput: \"aab\"\nExplanation: No three consecutive characters are equal, so return \"aab\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def makeFancyString(self, s: str) -> str:\n        if len(s) < 3:\n            return s\n        ans = ''\n        ans += s[0]\n        ans += s[1]\n        for i in range(2,len(s)):\n            if s[i] != ans[-1] or s[i] != ans[-2]:\n                ans += s[i]\n        return ans",
        "solution_js": "var makeFancyString = function(s) {\n    let res = '';\n    let currCount = 0;\n    \n    for (let i = 0; i < s.length; i++) {\n        if (currCount === 2 && s[i] === s[i - 1]) continue;\n        \n        else if (s[i] === s[i - 1]) {\n            currCount++;\n            res += s[i];\n        }\n        \n        else {\n            currCount = 1;\n            res += s[i]\n        }\n    }\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    public String makeFancyString(String s) {\n        char prev = s.charAt (0);\n        int freq = 1;\n        StringBuilder res = new StringBuilder ();\n        res.append (s.charAt (0));\n        for (int i = 1; i < s.length (); i++) {\n            if (s.charAt (i) == prev)\n                freq++;\n            else {\n                prev = s.charAt (i);\n                freq = 1;\n            }\n            if (freq < 3)\n                res.append (s.charAt (i));\n        }\n        return res.toString ();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string makeFancyString(string s) {\n        int cnt=1;\n        string ans=\"\";    ans.push_back(s[0]);\n\t\t\n        for(int i=1;i<s.length();++i) {\n            cnt=s[i]==s[i-1]? cnt+1:1;\n\n            if(cnt<3) {\n                ans.push_back(s[i]);\n            }\n        }\n        return ans;\n\n    }\n};\n};"
    },
    {
        "title": "Check if Matrix Is X-Matrix",
        "algo_input": "A square matrix is said to be an X-Matrix if both of the following conditions hold:\n\n\n\tAll the elements in the diagonals of the matrix are non-zero.\n\tAll other elements are 0.\n\n\nGiven a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]\nOutput: true\nExplanation: Refer to the diagram above. \nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is an X-Matrix.\n\n\nExample 2:\n\nInput: grid = [[5,7,0],[0,3,1],[0,5,0]]\nOutput: false\nExplanation: Refer to the diagram above.\nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is not an X-Matrix.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t3 &lt;= n &lt;= 100\n\t0 &lt;= grid[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def checkXMatrix(self, grid: List[List[int]]) -> bool:\n        n = len(grid)\n        for i in range(n):\n            for j in range(n):\n                if i==j or (i+j) ==n-1:\n                    if grid[i][j] == 0:\n                        return False\n                elif grid[i][j] != 0: \n                    return False\n        return True;",
        "solution_js": "var checkXMatrix = function(grid) {\n    for (let i=0; i<grid.length; i++) {\n        for (let j=0; j<grid[i].length; j++) {\n            let leftDiagonal = grid[i].length - 1;\n            if (i === j && grid[i][j] !== 0 || j === leftDiagonal - i && grid[i][j] !== 0) {\n                continue;\n            }\n            if (i === j && grid[i][j] === 0 || j === leftDiagonal - i && grid[i][j] === 0) {\n                return false;\n            }\n            if (grid[i][j] !== 0) {\n                return false;\n            }\n        }\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean checkXMatrix(int[][] grid) {\n        \n        int n = grid.length;\n        for(int i=0; i<n; i++){\n            for(int j=0; j<n; j++ ){\n                if ( i == j  || i + j == n - 1 ) {\n                    if ( grid[i][j] == 0 ) return false;                    \n                }\n\t\t\t\telse if ( grid[i][j] != 0 ) return false;                                    \n            }\n        }       \n       return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkXMatrix(vector<vector<int>>& grid) {\n        int n = grid.size();\n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < n; j++){\n                if(i == j or i == n - j - 1){\n                    if(!grid[i][j])\n                        return false;\n                }else if(grid[i][j])\n                    return false;    \n            }\n        }\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Lowest Common Ancestor of a Binary Tree",
        "algo_input": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”\n\n&nbsp;\nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of nodes 5 and 1 is 3.\n\n\nExample 2:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n\n\nExample 3:\n\nInput: root = [1,2], p = 1, q = 2\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 105].\n\t-109 &lt;= Node.val &lt;= 109\n\tAll Node.val are unique.\n\tp != q\n\tp and q will exist in the tree.\n\n",
        "solution_py": "class Solution:\n    # @param {TreeNode} root\n    # @param {TreeNode} p\n    # @param {TreeNode} q\n    # @return {TreeNode}\n    def lowestCommonAncestor(self, root, p, q):\n        # escape condition\n        if (not root) or (root == p) or (root == q):\n            return root\n        # search left and right subtree\n        left = self.lowestCommonAncestor(root.left, p, q)\n        right = self.lowestCommonAncestor(root.right, p, q)\n        if left and right:\n            # both found, root is the LCA\n            return root\n        return left or right",
        "solution_js": "var lowestCommonAncestor = function(root, p, q) {\n    if(!root || root.val == p.val || root.val == q.val) return root;\n\n    let left = lowestCommonAncestor(root.left, p, q);\n    let right = lowestCommonAncestor(root.right, p, q);\n\n    return (left && right) ? root : left || right;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        List<TreeNode> path_to_p= new ArrayList<>();\n        List<TreeNode> path_to_q= new ArrayList<>();\n        getPath(root,p,path_to_p);\n        getPath(root,q,path_to_q);\n        int n=path_to_q.size()>path_to_p.size()?path_to_p.size():path_to_q.size();\n        TreeNode anscesstor=root;\n        for(int i=0;i<n;i++){\n            if(path_to_q.get(i)==path_to_p.get(i)) anscesstor=path_to_p.get(i);\n        }\n        return anscesstor;\n        \n        \n    }\n    \n    boolean getPath(TreeNode root, TreeNode target,List<TreeNode> list){\n        if(root==null) return false;\n        list.add(root);\n        if(root==target) return true;\n        if(getPath(root.left,target,list) || getPath(root.right,target,list)){\n            return true;\n        }\n        list.remove(list.size()-1);\n        return false;\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)\n    {\n        if(!root)\n        {\n            return NULL;\n        }\n        if(root==p or root == q)\n        {\n            return root;\n        }\n        TreeNode *left=lowestCommonAncestor(root->left,p,q);\n        TreeNode *right=lowestCommonAncestor(root->right,p,q);\n        if(left and right) return root;\n        if(left) return left;\n        else return right;\n\n    }\n};"
    },
    {
        "title": "Rings and Rods",
        "algo_input": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.\n\nYou are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:\n\n\n\tThe first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').\n\tThe second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').\n\n\nFor example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.\n\nReturn the number of rods that have all three colors of rings on them.\n\n&nbsp;\nExample 1:\n\nInput: rings = \"B0B6G0R6R0R6G9\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.\n\n\nExample 2:\n\nInput: rings = \"B0R0G0R9R0B0G0\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.\n\n\nExample 3:\n\nInput: rings = \"G4\"\nOutput: 0\nExplanation: \nOnly one ring is given. Thus, no rods have all three colors.\n\n\n&nbsp;\nConstraints:\n\n\n\trings.length == 2 * n\n\t1 &lt;= n &lt;= 100\n\trings[i] where i is even is either 'R', 'G', or 'B' (0-indexed).\n\trings[i] where i is odd is a digit from '0' to '9' (0-indexed).\n\n",
        "solution_py": "class Solution:\n    def countPoints(self, r: str) -> int:\n        ans = 0\n        for i in range(10):\n            i = str(i)\n            if 'R'+i in r and 'G'+i in r and 'B'+i in r:\n                ans += 1\n        return ans",
        "solution_js": "/**\n * @param {string} rings\n * @return {number}\n */\nvar countPoints = function(rings) {\n    let rods = Array(10).fill(\"\");\n    for(let i = 0; i < rings.length; i += 2){\n        if(!(rods[rings[i+1]].includes(rings[i]))) rods[rings[i+1]] += rings[i]\n    }\n    return rods.filter(rod => rod.length > 2).length\n};",
        "solution_java": "class Solution {\n    public int countPoints(String rings) {\n        Map<Integer,Set<Character>> m=new HashMap<>();\n        for(int i=0;i<rings.length();i=i+2){\n            char c=rings.charAt(i);\n            int index=(int)rings.charAt(i+1);\n            if(m.containsKey(index)){\n                Set<Character> x=m.get(index);\n                x.add(c);\n                m.put(index,x);\n            }else{\n                Set<Character> x=new HashSet<>();\n                x.add(c);\n                m.put(index,x);\n            }\n        }\n        int count=0;\n        for(Set<Character> k : m.values()){\n            if(k.size()==3) count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPoints(string rings) {\n\n        int n=rings.length();\n        //It is given that number of rod is 10 0 to 9 so we have to place ring any of these\n        vector<int>vp(10,0);//store the no of rings\n        for(int i=0;i<n;i+=2)\n        {\n            char col=rings[i];\n            vp[rings[i+1]-'0']|=(col=='R'? 1: col =='G' ? 2 : 4);//checking for rings\n\n        }\n        int count=0;\n        for(int i=0;i<10;i++)\n        {\n            if(vp[i]==7)\n            {\n                count++;\n            }\n        }\n        return count;\n\n    }\n};"
    },
    {
        "title": "Kth Smallest Element in a Sorted Matrix",
        "algo_input": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.\n\nNote that it is the kth smallest element in the sorted order, not the kth distinct element.\n\nYou must find a solution with a memory complexity better than O(n2).\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\nOutput: 13\nExplanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13\n\n\nExample 2:\n\nInput: matrix = [[-5]], k = 1\nOutput: -5\n\n\n&nbsp;\nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 &lt;= n &lt;= 300\n\t-109 &lt;= matrix[i][j] &lt;= 109\n\tAll the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.\n\t1 &lt;= k &lt;= n2\n\n\n&nbsp;\nFollow up:\n\n\n\tCould you solve the problem with a constant memory (i.e., O(1) memory complexity)?\n\tCould you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.\n\n",
        "solution_py": "class Solution:\n    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n        return sorted(list(sum(matrix, [])))[k-1]",
        "solution_js": "var kthSmallest = function(matrix, k) {\n    let arr = matrix.flat()\n    arr.sort((a,b)=>a-b)\n    return arr[k-1]\n};",
        "solution_java": "/**\n * Using PriorityQueue\n *\n * Time Complexity:\n *      O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.\n *                                   If we were adding all elements in one go, then the complexity would be O(min(N,K))\n *                                   Refer: https://stackoverflow.com/a/34697891\n *      O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.\n * Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))\n *\n * Space Complexity: O(min(N, K))\n *\n * N = Length of one side of the matrix. K = input value k.\n */\nclass Solution {\n    public int kthSmallest(int[][] matrix, int k) {\n        if (matrix == null || k <= 0) {\n            throw new IllegalArgumentException(\"Input is invalid\");\n        }\n\n        int n = matrix.length;\n        if (k > n * n) {\n            throw new NoSuchElementException(\"k is greater than number of elements in matrix\");\n        }\n        if (k == 1) {\n            return matrix[0][0];\n        }\n        if (k == n * n) {\n            return matrix[n - 1][n - 1];\n        }\n\n        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));\n\n        for (int i = 0; i < Math.min(n, k); i++) {\n            queue.offer(new int[] { i, 0 });\n        }\n        while (k > 1) {\n            int[] cur = queue.poll();\n            if (cur[1] < n - 1) {\n                cur[1]++;\n                queue.offer(cur);\n            }\n            k--;\n        }\n\n        return matrix[queue.peek()[0]][queue.peek()[1]];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int kthSmallest(vector<vector<int>>& matrix, int k) {\n        int n = matrix.size(), start = matrix[0][0], end = matrix[n-1][n-1];\n        unordered_map<int, int>mp;\n        for(int i = 0; i < n; i++)\n            for(int j = 0; j < n; j++)\n                mp[matrix[i][j]]++;\n        \n        for(int i = start; i <= end; i++)\n            if(mp.find(i) != mp.end()){\n                for(int j = 0; j < mp[i]; j++){\n                    k--;\n                    if(k == 0) return i;\n                }\n            }\n          return -1;  \n    }\n};"
    },
    {
        "title": "Flipping an Image",
        "algo_input": "Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.\n\nTo flip an image horizontally means that each row of the image is reversed.\n\n\n\tFor example, flipping [1,1,0] horizontally results in [0,1,1].\n\n\nTo invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.\n\n\n\tFor example, inverting [0,1,1] results in [1,0,0].\n\n\n&nbsp;\nExample 1:\n\nInput: image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n\n\nExample 2:\n\nInput: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == image.length\n\tn == image[i].length\n\t1 &lt;= n &lt;= 20\n\timages[i][j] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n        return [[(1 - i) for i in row[::-1]] for row in image]",
        "solution_js": "var flipAndInvertImage = function(image) {\n    const resversedArr = []\n    for(let i=0; i<image.length; i++){\n         resversedArr.push(resverseArr(image[i]));\n    }\n  return resversedArr;\n};\n\nfunction resverseArr(arr){\n    const lastIndex = arr.length -1, reversedArr = [];\n    for(i=0; i<=lastIndex; i++){\n        if(arr[i] !== arr[lastIndex-i]){\n            reversedArr[i] = arr[lastIndex-i] === 0 ? 1 : 0;\n            reversedArr[lastIndex-i] = arr[i] === 0 ? 1 : 0;\n        }else{\n           reversedArr[i] = arr[i] === 0 ? 1 : 0;\n        }\n    }\n    return reversedArr;\n}```\n\n/*\n*/",
        "solution_java": "class Solution {\n    public int[][] flipAndInvertImage(int[][] image) {\n        for (int i = 0; i < image.length; ++i) {\n            flip(image[i]);\n        }\n        for (int i = 0; i < image.length; ++i) {\n            for (int j = 0; j < image[i].length; ++j) {\n                image[i][j] = image[i][j] == 1 ? 0:1;\n            }\n        }\n        return image;\n    }\n    public static void flip(int[] row) {\n        int i = 0;\n        int j = row.length - 1;\n        while (i < j) {\n            int temp = row[i];\n            row[i] = row[j];\n            row[j] = temp;\n            ++i;\n            --j;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {\n        int n = image.size();\n        vector<int >ans;\n        for(int i=0;i<image.size();i++){\n            ans=image[i];\n            reverse(ans.begin(),ans.end());\n            image[i]=ans;\n        }\n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < n; j++){\n                if(image[i][j] == 0){\n                    image[i][j] = 1;\n                }\n                else{\n                    image[i][j] = 0;\n                }\n            }\n        }\n        return image;\n    }\n};"
    },
    {
        "title": "Shortest Unsorted Continuous Subarray",
        "algo_input": "Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.\n\nReturn the shortest such subarray and output its length.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,6,4,8,10,9,15]\nOutput: 5\nExplanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: 0\n\n\nExample 3:\n\nInput: nums = [1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-105 &lt;= nums[i] &lt;= 105\n\n\n&nbsp;\nFollow up: Can you solve it in O(n) time complexity?",
        "solution_py": "#lets start adding elements to stack. We have to fin the min length [a, b] interval (corresponding to the problem description).\n# a has to be the first element's index we pop from the array. lets say y is the last element's index we pop.\n# and max_pop is the maximum element(not index) we pop during stacking.After stacking process is done we are going to have\n#last elements in the stack E(E is the stack after stacking is done).We have to find M = maximum_element(max_pop, all elements of E)\n#Index of M is going to be right edge of the [a, b] interval\n\nclass Solution:\n    def findUnsortedSubarray(self, nums) -> int:\n        stack = []\n        min_index = len(nums)\n        max_index = 0\n        max_pop = float('-inf')\n        for i in range(len(nums)):\n            while stack and nums[i] < stack[-1][0]:\n\n                p = stack.pop()\n                if p[0] > max_pop:\n                    max_pop = p[0]\n                if p[1] < min_index:\n                    min_index = p[1]\n                if p[1] > max_index:\n                    max_index = p[1]\n            stack.append([nums[i], i])\n        max_r = max_index\n        for st in stack:\n            if st[0] < max_pop:\n                max_r = st[1]\n        if min_index == len(nums):\n            return 0\n        return max_r - min_index +1",
        "solution_js": "var findUnsortedSubarray = function(nums) {\n    let left = 0;\n    let right = nums.length - 1;\n    const target = [...nums].sort((a, b) => a - b);\n\n    while (left < right && nums[left] === target[left]) left += 1;\n    while (right > left && nums[right] === target[right]) right -= 1;\n    const result = right - left;\n\n    return result === 0 ? 0 : result + 1;\n};",
        "solution_java": "class Solution {\n    public int findUnsortedSubarray(int[] nums) {\n        int[] numsClone = nums.clone();\n        Arrays.sort(nums);\n\n        int s = Integer.MAX_VALUE;\n        int e = Integer.MIN_VALUE;\n\n        for(int i = 0; i<nums.length; i++) {\n            if(numsClone[i] != nums[i]) {\n                s = Math.min(s, i);\n                e = Math.max(e, i);\n            }\n        }\n\n        if(s == Integer.MAX_VALUE || e == Integer.MIN_VALUE) {\n            return 0;\n        }\n\n        return e-s+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int max_value = 1000000;\n    int min_value = -1000000;\n    \n    int findUnsortedSubarray(vector<int>& nums) {\n\t\t// max_list refers to: the max value on the left side of the current element\n\t\t// min_list refers to: the min value on the right side of the current element\n        vector<int> max_list(nums.size(), 0);\n        vector<int> min_list(nums.size(), 0);\n        min_list[nums.size()-1] = max_value;\n        max_list[0] = min_value;\n        \n        // init two lists\n        for(int i=nums.size()-2; i>=0; i--)\n            min_list[i] = min(min_list[i+1], nums[i+1]);\n        \n        for(int i=1; i<nums.size(); i++) \n            max_list[i] = max(max_list[i-1], nums[i-1]);\n        \n        // get left bound\n        int left = 0;\n        while(left < nums.size() && min_list[left] >= nums[left])\n            left++;\n        \n        // get right bound\n        int right = nums.size() - 1;\n        while(right >= 0 && max_list[right] <= nums[right])\n            right--;\n        \n        if (left == nums.size()) // monotonic ascending array\n            return 0;\n        else\n            return (right-left+1);\n    }\n};"
    },
    {
        "title": "Number of Pairs of Interchangeable Rectangles",
        "algo_input": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.\n\nTwo rectangles i and j (i &lt; j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).\n\nReturn the number of pairs of interchangeable rectangles in rectangles.\n\n&nbsp;\nExample 1:\n\nInput: rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput: 6\nExplanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.\n\n\nExample 2:\n\nInput: rectangles = [[4,5],[7,8]]\nOutput: 0\nExplanation: There are no interchangeable pairs of rectangles.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == rectangles.length\n\t1 &lt;= n &lt;= 105\n\trectangles[i].length == 2\n\t1 &lt;= widthi, heighti &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n        ratios = defaultdict(int)\n        for x, y in rectangles:\n            ratios[x/y] += 1\n        res = 0\n        for val in ratios.values():\n            res += (val*(val-1)//2)\n        return res",
        "solution_js": "/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nvar interchangeableRectangles = function(rectangles) {\n    let map = new Map();\n    for (let i = 0; i < rectangles.length; i++) {\n        let [a, b] = rectangles[i];\n        let val = a / b;\n        if (!map.get(val)) map.set(val, [0, 0]);\n        else {\n            const [count, total] = map.get(val);\n            map.set(val, [count + 1, total + count + 1]);\n        }\n    }\n    \n    return [...map.entries()].reduce((prev, [key, [count, total]]) => {\n        if (count < 1) return prev;\n        return prev + total;\n    }, 0);\n};",
        "solution_java": "class Solution {\n    \n    public long interchangeableRectangles(int[][] rectangles) {\n        Map <Double, Long> hash = new HashMap<>();\n        \n        for (int i = 0; i < rectangles.length; i++) {\n            Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]);\n            \n            hash.put(tmp, hash.getOrDefault(tmp, 0L) + 1);\n        }\n        \n        long ans = 0;\n        for (Map.Entry<Double,Long> entry : hash.entrySet()) {\n            if (entry.getValue() > 1) {\n                Long n = entry.getValue();\n                ans += (n * (n - 1)) / 2;\n            }\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long interchangeableRectangles(vector<vector<int>>& rectangles) {\n        int n = rectangles.size();\n        unordered_map<double,int> mp;\n        for(int i = 0;i<n;i++){\n            double ratio = rectangles[i][0]/(double)rectangles[i][1];\n            mp[ratio]++;\n        }\n        long long count = 0;\n\n        for(auto i: mp){\n            long long x = i.second;\n            x = (x * (x-1))/2.0;\n            count += x;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Relative Sort Array",
        "algo_input": "Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.\n\nSort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.\n\n&nbsp;\nExample 1:\n\nInput: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\nOutput: [2,2,2,1,4,3,3,9,6,7,19]\n\n\nExample 2:\n\nInput: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\nOutput: [22,28,8,6,17,44]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr1.length, arr2.length &lt;= 1000\n\t0 &lt;= arr1[i], arr2[i] &lt;= 1000\n\tAll the elements of arr2 are distinct.\n\tEach&nbsp;arr2[i] is in arr1.\n\n",
        "solution_py": "class Solution:\n    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n        arr = []\n        hashmap = {char: arr1.count(char) for char in arr1}\n        [arr.extend([char] * hashmap.pop(char)) for char in arr2]\n        return arr + sorted([int(key) * hashmap[key] for key in hashmap]",
        "solution_js": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number[]}\n */\nvar relativeSortArray = function(arr1, arr2) {\n  const indices = new Map();\n  arr2.forEach(indices.set, indices);\n\n  return arr1.sort((a, b) => {\n    if (indices.has(a)) {\n      return indices.has(b) ? indices.get(a) - indices.get(b) : -1;\n    }\n    if (indices.has(b)) {\n      return 1;\n    }\n    return a - b;\n  });\n};",
        "solution_java": "class Solution {\n    public int[] relativeSortArray(int[] arr1, int[] arr2) {\n        Map <Integer, Integer> map = new TreeMap();\n        for(int i = 0; i<arr1.length; i++){\n            if(map.containsKey(arr1[i])){\n                map.replace(arr1[i], map.get(arr1[i]),map.get(arr1[i])+1);\n            }\n            else{\n                map.put(arr1[i], 1);\n            }\n        }\n\n        int[] arr = new int [arr1.length];\n        int ind = 0;\n        for(int i = 0; i<arr2.length; i++){\n\n            for(int j = 0; j<map.get(arr2[i]);j++){\n                arr[ind] = arr2[i];\n                ind++;\n            }\n            map.remove(arr2[i]);\n        }\n\n        for(int i: map.keySet()){\n\n            for(int j = 0; j<map.get(i);j++){\n                arr[ind] = i;\n                ind++;\n            }\n\n        }\n\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {\n        map<int,int>sk;\n        vector<int>res;\n        for(auto i:arr1){\n            sk[i]++;\n        }\n        for(auto j:arr2){\n            for(auto z:sk){\n                if(z.first==j){\n                    int x=z.second;\n                    for(int l=0;l<x;l++){\n                        res.push_back(z.first);\n                    }\n                }\n               \n            }\n        }\n        for(auto z:sk){\n            if(z.second==4 && find(res.begin(), res.end(),z.first)==res.end()){\n                   int p=z.second;\n                  for(int aqq=0;aqq<p;aqq++){\n                      res.push_back(z.first);\n                  }\n                }\n            \n            if(z.second==3 && find(res.begin(), res.end(),z.first)==res.end()){\n                   int p=z.second;\n                  for(int aq=0;aq<p;aq++){\n                      res.push_back(z.first);\n                  }\n                }\n            \n              if(z.second==2 && find(res.begin(), res.end(),z.first)==res.end()){\n                   int p=z.second;\n                  for(int a=0;a<p;a++){\n                      res.push_back(z.first);\n                  }\n                }\n            \n         if(z.second==1 && find(res.begin(), res.end(),z.first)==res.end()){\n                    res.push_back(z.first);\n                }\n        }\n        \n        return res;\n            \n    }\n};"
    },
    {
        "title": "Check If N and Its Double Exist",
        "algo_input": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).\n\nMore formally check if there exists&nbsp;two indices i and j such that :\n\n\n\ti != j\n\t0 &lt;= i, j &lt; arr.length\n\tarr[i] == 2 * arr[j]\n\n\n&nbsp;\nExample 1:\n\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.\n\n\nExample 2:\n\nInput: arr = [7,1,14,11]\nOutput: true\nExplanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.\n\n\nExample 3:\n\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: In this case does not exist N and M, such that N = 2 * M.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 500\n\t-10^3 &lt;= arr[i] &lt;= 10^3\n\n",
        "solution_py": "class Solution(object):\n    def checkIfExist(self, arr):\n        \"\"\"\n        :type arr: List[int]\n        :rtype: bool\n        \"\"\"\n        '''\n            执行用时:24 ms, 在所有 Python 提交中击败了59.63%的用户\n            内存消耗:13 MB, 在所有 Python 提交中击败了58.72%的用户\n        '''\n        arr = sorted(arr) # 排序\n        for i in range(len(arr) - 1): # 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现\n            l = 0\n            r = len(arr) - 1\n            while (l <= r):\n                mid = int((l + r) / 2) # 目前位置\n                val1 = arr[mid] # 目前位置的数值\n                val2 = arr[i] * 2 # 要寻找的目标\n                if(val1 == val2 and mid != i): # arr[mid] 必須和 arr[i] * 2 且不同位置\n                    return True\n                elif(val2 < val1): # 目标在目前位置的左边,所以要往左边找\n                    r = mid - 1\n                else: # 目标在目前位置的右边,所以要往右边找\n                    l = mid + 1\n        return False",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {boolean}\n */\nvar checkIfExist = function(arr) {\n    for(let i=0;i<arr.length;i++){\n        for(let j=0;j<arr.length;j++){\n            if ( i!==j && arr[i]==2*arr[j]){\n                return true;\n            }\n        }\n    }\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean checkIfExist(int[] arr) {\n        /*\n            执行用时:3 ms, 在所有 Java 提交中击败了29.57%的用户\n            内存消耗:41 MB, 在所有 Java 提交中击败了42.27%的用户\n            2022年8月3日 14:36\n        */\n        int l, mid = 0, r;\n        int val1, val2;\n        Arrays.sort(arr); // 排序\n        for(int i=0; i < arr.length - 1; i++){ // 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现\n            l = 0;\n            r = arr.length - 1;\n            while(l <= r){\n                mid = (l + r) / 2; // 目前位置\n                val1 = arr[mid]; // 目前位置的数值\n                val2 = arr[i] * 2; // 要寻找的目标\n                if(val1 == val2 && mid != i) // arr[mid] 必須和 arr[i] * 2 且不同位置\n                    return true;\n                else if(val2 < val1) // 目标在目前位置的左边,所以要往左边找\n                    r = mid - 1;\n                else // 目标在目前位置的右边,所以要往右边找\n                    l = mid + 1;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkIfExist(vector<int>& arr) {\n        \n        sort(arr.begin(), arr.end());\n        \n        int i =0;\n            int j  = 1;\n        int n = arr.size();\n        while(i<n && j<n)\n        {\n                \n                if(  arr[i]<0 && arr[j]<0 && arr[i]==2*arr[j])return true;\n            \n                else if(2*arr[i]<arr[j])\n                {\n                    \n                    i++;\n                  \n\n                \n                }\n            else if(2*arr[i]>arr[j])j++;\n            else if(i==j && arr[i]==0){\n            i++;\n                j++;\n            }\n            \n            else return true;\n        \n        }\n        return false;\n        \n    }\n};"
    },
    {
        "title": "Group the People Given the Group Size They Belong To",
        "algo_input": "There are n people&nbsp;that are split into some unknown number of groups. Each person is labeled with a&nbsp;unique ID&nbsp;from&nbsp;0&nbsp;to&nbsp;n - 1.\n\nYou are given an integer array&nbsp;groupSizes, where groupSizes[i]&nbsp;is the size of the group that person&nbsp;i&nbsp;is in. For example, if&nbsp;groupSizes[1] = 3, then&nbsp;person&nbsp;1&nbsp;must be in a&nbsp;group of size&nbsp;3.\n\nReturn&nbsp;a list of groups&nbsp;such that&nbsp;each person&nbsp;i&nbsp;is in a group of size&nbsp;groupSizes[i].\n\nEach person should&nbsp;appear in&nbsp;exactly one group,&nbsp;and every person must be in a group. If there are&nbsp;multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.\n\n&nbsp;\nExample 1:\n\nInput: groupSizes = [3,3,3,3,3,1,3]\nOutput: [[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\n\n\nExample 2:\n\nInput: groupSizes = [2,1,3,3,3,2]\nOutput: [[1],[0,5],[2,3,4]]\n\n\n&nbsp;\nConstraints:\n\n\n\tgroupSizes.length == n\n\t1 &lt;= n&nbsp;&lt;= 500\n\t1 &lt;=&nbsp;groupSizes[i] &lt;= n\n\n",
        "solution_py": "class Solution(object):\n    def groupThePeople(self, groupSizes):\n        \"\"\"\n        :type groupSizes: List[int]\n        :rtype: List[List[int]]\n        \"\"\"\n        dict_group={}\n        for i in range(len(groupSizes)):\n            if groupSizes[i] not in dict_group:\n                dict_group[groupSizes[i]]=[i]\n            else:\n                dict_group[groupSizes[i]].append(i)\n        return_list=[]\n        for i in dict_group:\n            num_list=dict_group[i]\n            for j in range(0,len(num_list),i):\n                return_list.append(num_list[j:j+i])\n        return return_list",
        "solution_js": "/**\n * @param {number[]} groupSizes\n * @return {number[][]}\n */\nvar groupThePeople = function(groupSizes) {\n    let indices = [], result = [];\n    groupSizes.forEach((x, idx) => {\n        if (indices[x]) indices[x].push(idx);\n        else indices[x] = [idx];\n        if (indices[x].length === x) {\n            result.push(indices[x]);\n            indices[x] = undefined;\n        }\n    });\n    return result;\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> groupThePeople(int[] groupSizes) {\n\n        List<List<Integer>> temp = new ArrayList<List<Integer>>();\n        List<List<Integer>> result = new ArrayList<List<Integer>>();\n        for(int i = 0; i<groupSizes.length; i++){\n            int k = groupSizes[i];\n            boolean flag = true;\n            for(int j = 0; j<temp.size(); j++){\n                // If there is a list of reqired group size and it is filled lesser than we can put element in that one\n                if(k == temp.get(j).get(0) && k >temp.get(j).get(1)){\n                    result.get(j).add(i);\n                    temp.get(j).set(1,temp.get(j).get(1)+1);\n                    flag=false;\n                    break;\n                }\n            }\n            if(flag){\n                // comment 1\n                // We create a list with index and put it to result\n                List<Integer> res = new ArrayList();\n                res.add(i);\n                result.add(res);\n                // comment 2\n                // we create a new list recording max value can stored and currently filled\n                List<Integer> tempRes = new ArrayList();\n                tempRes.add(k);\n                tempRes.add(1);\n                temp.add(tempRes);\n            }\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {\n        vector<vector<int>>ans;\n        unordered_map<int,vector<int>> store;\n        \n        for(int i=0;i<groupSizes.size();i++){\n            if(store[groupSizes[i]].size()==groupSizes[i]){\n               ans.push_back(store[groupSizes[i]]) ;\n                store[groupSizes[i]].clear();\n                }\n            store[groupSizes[i]].push_back(i);}\n        \n        for(auto &x:store){\n            ans.push_back(x.second);}\n        return ans;     \n    }\n};"
    },
    {
        "title": "Create Maximum Number",
        "algo_input": "You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.\n\nCreate the maximum number of length k &lt;= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.\n\nReturn an array of the k digits representing the answer.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\nOutput: [9,8,6,5,3]\n\n\nExample 2:\n\nInput: nums1 = [6,7], nums2 = [6,0,4], k = 5\nOutput: [6,7,6,0,4]\n\n\nExample 3:\n\nInput: nums1 = [3,9], nums2 = [8,9], k = 3\nOutput: [9,8,9]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == nums1.length\n\tn == nums2.length\n\t1 &lt;= m, n &lt;= 500\n\t0 &lt;= nums1[i], nums2[i] &lt;= 9\n\t1 &lt;= k &lt;= m + n\n\n",
        "solution_py": "class Solution:\n    def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:\n        m = len(nums1)\n        n = len(nums2)\n        dp = {}\n        \n        # get the max number string with \"length\" from index \"i\" in nums1 and index \"j\" in nums2\n        # using number string to easy to compare\n        def getMaxNumberString(i, j, length):\n            if length == 0:\n                return \"\"\n            \n            # using memoization to optimize for the overlapping subproblems\n            key = (i, j, length)\n            if key in dp:\n                return dp[key]\n            \n            # greedy to find the possible max digit from nums1 and nums2\n            # 1) bigger digit in the higher position of the number will get bigger number\n            # 2) at the same time, we need to ensure that we still have enough digits to form a number with \"length\" digits\n            \n            # try to find the possible max digit from index i in nums1\n            index1 = None\n            for ii in range(i, m):\n                if (m - ii + n - j) < length:\n                    break\n                if index1 is None or nums1[index1] < nums1[ii]:\n                    index1 = ii\n            \n            # try to find the possible max digit from index j in nums2\n            index2 = None\n            for jj in range(j, n):\n                if (m - i + n - jj) < length:\n                    break\n                if index2 is None or nums2[index2] < nums2[jj]:\n                    index2 = jj\n                    \n            maxNumberStr = None\n            if index1 is not None and index2 is not None:\n                if nums1[index1] > nums2[index2]:\n                    maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n                elif nums1[index1] < nums2[index2]:\n                    maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n                else:\n                    # get the same digit from nums1 and nums2, so need to try two cases and get the max one \n                    maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1))\n            elif index1 is not None:\n                maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n            elif index2 is not None:\n                maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n            \n            dp[key] = maxNumberStr\n            return maxNumberStr\n\n        result_str = getMaxNumberString(0, 0, k)\n        \n        # number string to digit array\n        result = []\n        for c in result_str:\n            result.append(int(c))\n        \n        return result",
        "solution_js": "const maxNumber = (a, b, k) => {\n    let m = a.length, n = b.length;\n    let res = [];\n    for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) {\n        let maxA = maxArray(a, i), maxB = maxArray(b, k - i);\n        let merge = mergeArray(maxA, maxB);\n        if (merge > res) res = merge;\n    }\n    return res;\n};\n\nconst maxArray = (a, k) => {\n    let drop = a.length - k, res = [];\n    for (const x of a) {\n        while (drop > 0 && res.length && res[res.length - 1] < x) {\n            res.pop();\n            drop--;\n        }\n        res.push(x);\n    }\n    if (res.length >= k) {\n        res = res.slice(0, k);\n    } else {\n        res = res.concat(Array(k - res.length).fill(0));\n    }\n    return res;\n};\n\nconst mergeArray = (a, b) => {\n    let res = [];\n    while (a.length + b.length) res.push(a > b ? a.shift() : b.shift())\n    return res;\n};",
        "solution_java": "class Solution {\n    public int[] maxNumber(int[] nums1, int[] nums2, int k) {\n        String ans=\"\";\n        for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq\n            String one = solve(nums1, i); // find the best seq matching len of i\n            String two = solve(nums2, k-i); // len of k-i\n            StringBuilder sb = new StringBuilder();\n            int a = 0, b = 0;\n            while(a < i || b < k-i){ // merge it to the max\n                sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));\n            }\n            if (sb.toString().compareTo(ans)>0){ // if better, we replace.\n                ans=sb.toString();\n            }\n        }\n        int[] res = new int[k];\n        for (int i = 0; i < k;++i){\n            res[i]=ans.charAt(i)-'0';\n        }\n        return res;\n    }\n\n    private String solve(int[] arr, int k){\n        Deque<Integer> stack = new ArrayDeque<>();\n        for (int i = 0;i<arr.length;++i){\n            while(!stack.isEmpty()&&arr.length-i+stack.size()>k&&stack.peek()<arr[i]){\n                stack.pop();\n            }\n            stack.push(arr[i]);\n        }\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < k;i++){\n            sb.append(stack.pollLast());\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> maxArray(vector<int>&nums,int k){\n        int n=nums.size();\n        stack<int>seen;\n        for(int i=0;i<n;i++){\n            int right=n-i-1;\n            while(not seen.empty() and seen.top()<nums[i] and right+seen.size()>=k)seen.pop();\n            if(seen.size()<k)seen.push(nums[i]);\n        }\n        vector<int>res(k,0);\n        for(int i=res.size()-1;i>=0;i--){\n            res[i]=seen.top();\n            seen.pop();\n        }\n        return res;\n    }\n    bool greater(vector<int>&arr1,int i,vector<int>&arr2,int j){\n        for(;i<arr1.size() and j<arr2.size();i++,j++){\n            if(arr1[i]==arr2[j])continue;\n            return arr1[i]>arr2[j];\n        }\n        return i!=arr1.size();\n    }\n    vector<int> merge(vector<int>&arr1,vector<int>&arr2){\n        vector<int>res(arr1.size()+arr2.size());\n        for(int ind=0,i=0,j=0;ind<res.size();ind++){\n            if(greater(arr1,i,arr2,j)){\n                res[ind]=arr1[i];\n                i++;\n            }else{\n                res[ind]=arr2[j];\n                j++;\n            }\n        }\n        return res;\n    }\n    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {\n        int m=nums1.size(),n=nums2.size();\n        vector<int>ans;\n        for(int len1=max(0,k-n);len1<=min(m,k);len1++){\n            int len2 = k-len1;\n            vector<int> arr1 = maxArray(nums1,len1);\n            vector<int> arr2 = maxArray(nums2,len2);\n            vector<int> temp_res = merge(arr1,arr2);\n            if(greater(temp_res,0,ans,0)){\n                ans.resize(temp_res.size());\n                for(int i=0;i<temp_res.size();i++){\n                    ans[i]=temp_res[i];\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Valid Anagram",
        "algo_input": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\n&nbsp;\nExample 1:\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\nExample 2:\nInput: s = \"rat\", t = \"car\"\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, t.length &lt;= 5 * 104\n\ts and t consist of lowercase English letters.\n\n\n&nbsp;\nFollow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?\n",
        "solution_py": "class Solution:\n    def isAnagram(self, s: str, t: str) -> bool:\n        return Counter(s) == Counter(t)",
        "solution_js": "var isAnagram = function(s, t) {\n    if(s.length !== t.length) return false\n    \n    let charFreq = {}\n    \n    for(let char of s){\n        charFreq[char] ? charFreq[char] +=1 : charFreq[char] = 1\n    }\n    \n    for(let char of t){\n        if(!(charFreq[char])) return false\n        charFreq[char] -= 1\n    }\n    return true\n};",
        "solution_java": "class Solution {\n    public boolean isAnagram(String s, String t) {\n        if (s.length() != t.length()) return false;\n        int[] haha1 = new int[26];//26 because input contains of only lower english letters\n        int[] haha2 = new int[26];\n        for (int i = 0; i < s.length(); ++i) {\n            haha1[(int)s.charAt(i)-97] += 1;//omitting 97 because 'a' is 97, it will be 0 now\n            haha2[(int)t.charAt(i)-97] += 1;\n        }\n        for (int i = 0; i < haha1.length; ++i) {\n            if (haha1[i] != haha2[i]) return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isAnagram(string s, string t) {\n        sort(s.begin(), s.end());\n        sort(t.begin(), t.end());\n\n        if(s != t)\n            return false;\n\n        return true;\n    }\n};"
    },
    {
        "title": "Integer Break",
        "algo_input": "Given an integer n, break it into the sum of k positive integers, where k &gt;= 2, and maximize the product of those integers.\n\nReturn the maximum product you can get.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 1\nExplanation: 2 = 1 + 1, 1 × 1 = 1.\n\n\nExample 2:\n\nInput: n = 10\nOutput: 36\nExplanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 58\n\n",
        "solution_py": "class Solution:\n    def integerBreak(self, n: int) -> int:\n        dp = [0 for _ in range(n+1)]\n        dp[1] = 1\n        for i in range(2, n+1):\n            for j in range(1, i//2+1):\n                dp[i] = max(j * (i-j), j * dp[i-j], dp[i])\n        return dp[-1]",
        "solution_js": "var integerBreak = function(n) {\n\n       if(n == 2) return 1;\n       if(n == 3) return 2;\n       if(n == 4) return 4;\n\n       let c = ~~(n/3);\n       let d = n % 3;\n\n       if(d === 0){\n           return 3 ** c;\n       }\n\n       if(d === 1){\n           return 3 ** (c-1) * 4;\n       }\n\n       if(d === 2){\n           return 3 ** (c) * 2;\n       }\n\n};",
        "solution_java": "class Solution {\n    public int integerBreak(int n) {\n        //dp array: maximum product of splitling int i\n        int[] dp = new int[n + 1];\n        \n        // traverse\n        for (int i = 2; i <= n; i++) {\n            for (int j = 1; j <= i / 2; j++) {\n                 dp[i] = Math.max(Math.max(j * (i - j), j * dp[i - j]), dp[i]);\n            }\n        }\n        return dp[n];\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    int integerBreak(int n)\n    {\n        if (n == 2)\n            return 1;\n        if (n == 3)\n            return 2;\n        if (n == 4)\n            return 4;\n        int k = n / 3;\n        int m = n % 3;\n        int ans;\n        if (m == 0)\n            ans = pow(3, k);\n        else if (m == 1)\n            ans = pow(3, k - 1) * 4;\n        else if (m == 2)\n            ans = pow(3, k) * m;\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Number of Arrows to Burst Balloons",
        "algo_input": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.\n\nArrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart &lt;= x &lt;= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.\n\nGiven the array points, return the minimum number of arrows that must be shot to burst all balloons.\n\n&nbsp;\nExample 1:\n\nInput: points = [[10,16],[2,8],[1,6],[7,12]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].\n\n\nExample 2:\n\nInput: points = [[1,2],[3,4],[5,6],[7,8]]\nOutput: 4\nExplanation: One arrow needs to be shot for each balloon for a total of 4 arrows.\n\n\nExample 3:\n\nInput: points = [[1,2],[2,3],[3,4],[4,5]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 105\n\tpoints[i].length == 2\n\t-231 &lt;= xstart &lt; xend &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def findMinArrowShots(self, points: List[List[int]]) -> int:\n        points.sort()\n        \n        ans=[points[0]]\n        for i in points[1:]:\n            if(i[0]<=ans[-1][1]):\n                ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])]\n            else:\n                ans.append(i)\n        return len(ans)\n        ",
        "solution_js": "var findMinArrowShots = function(points) {\n    points.sort((a, b) => a[0] - b[0])\n\n    let merged = [points[0]];\n\n    let earliestEnd = points[0][1];\n\n    for (let i = 1; i < points.length; i++) {\n        let lastEnd = merged[merged.length - 1][1];\n        let currStart = points[i][0];\n        let currEnd = points[i][1];\n\n        if (lastEnd >= currStart && currStart <= earliestEnd) {\n            merged[merged.length - 1][1] = Math.max(lastEnd, currEnd)\n            earliestEnd = Math.min(earliestEnd, points[i][1]);\n        }\n        else {\n            merged.push(points[i])\n            earliestEnd = points[i][1]\n        }\n    }\n\n    return merged.length\n};",
        "solution_java": "class Solution {\n    public int findMinArrowShots(int[][] points) {\n        \n        int minNumArrows = 1;\n        Arrays.sort(points, new Comparator<int[]>(){\n            @Override\n            public int compare(int[] i1, int[] i2)\n            {\n                if(i1[0] < i2[0])\n                    return -1;\n                else if (i1[0] > i2[0])\n                    return 1;\n                return 0;\n            }\n        });\n            \n        // This is where they will trip you up ( at the merge stage )\n        // Wait ... do we actually have to merge here? The intervals have been sorted already\n        // No you must merge\n        // See if they can be merged\n        // If mergeable - overwrite OR write into a new subintervals code ( new ArrayList ) \n        // Ok ... so first we compare (a1,a2) and then next step compare (a2,a3)\n        // Now if (a1,a2) had an overlap -> why not make the next a2 = merged(a1,a2)? \n        // That would do a carry over effect then\n        int n = points.length;\n        int[] candid = new int[2];  // always first interval anyways\n        candid[0] = points[0][0];\n        candid[1] = points[0][1];\n        for(int i = 1; i < n; i++)\n        {\n            // System.out.printf(\"Current set = (%d,%d)\\n\", candid[0], candid[1]);\n            int[] next = points[i];\n            if(hasOverlap(candid,next))\n            {\n                int[] merged = mergeInterval(candid,next);\n                candid[0] = merged[0];\n                candid[1] = merged[1];\n            }\n            else\n            {\n                candid[0] = next[0];\n                candid[1] = next[1];                \n                minNumArrows++;\n            }\n        }\n         \n        return minNumArrows;\n    }\n    \n    public boolean hasOverlap(int[] i1, int[] i2)\n    {\n        boolean hasOverlap = false;\n        if(i1[0] <= i2[0] && i2[0] <= i1[1])\n            hasOverlap = true;\n        if(i2[0] <= i1[0] && i1[0] <= i2[1])\n            hasOverlap = true;\n        return hasOverlap;\n    }\n    \n    public int[] mergeInterval(int[] i1, int[] i2)\n    {\n        int[] merged = new int[2];\n        merged[0] = Math.max(i1[0],i2[0]);\n        merged[1] = Math.min(i1[1],i2[1]);\n        return merged;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    static bool cmp(vector<int>&a,vector<int>&b)\n    {\n        return a[1]<b[1];\n    }\n    int findMinArrowShots(vector<vector<int>>& points) {\n        sort(points.begin(),points.end(),cmp);\n        //burst the first ballon at least\n        int arrow=1;\n        int end=points[0][1];\n        for(int i=1;i<points.size();i++)\n        {\n            //start time of other interval is greater than current end time means we need one more arrow for bursting it\n            if(points[i][0]>end)\n            {\n                arrow++;\n                end=points[i][1];\n            }\n        }\n        return arrow;\n    }\n};"
    },
    {
        "title": "Kth Largest Element in a Stream",
        "algo_input": "Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n\nImplement KthLargest class:\n\n\n\tKthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.\n\tint add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]\nOutput\n[null, 4, 5, 5, 8, 8]\n\nExplanation\nKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3);   // return 4\nkthLargest.add(5);   // return 5\nkthLargest.add(10);  // return 5\nkthLargest.add(9);   // return 8\nkthLargest.add(4);   // return 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 104\n\t0 &lt;= nums.length &lt;= 104\n\t-104 &lt;= nums[i] &lt;= 104\n\t-104 &lt;= val &lt;= 104\n\tAt most 104 calls will be made to add.\n\tIt is guaranteed that there will be at least k elements in the array when you search for the kth element.\n\n",
        "solution_py": "class KthLargest:\n    def __init__(self, k: int, nums: List[int]):\n        self.k = k\n        self.hp = []\n        for x in nums:\n            self.add(x)\n\n        return None\n\n    def add(self, val: int) -> int:\n        heapq.heappush(self.hp, (val))\n        if len(self.hp) > self.k:\n            heapq.heappop(self.hp)\n\n        return self.get_kth_largest()\n\n    def get_kth_largest(self):\n        return self.hp[0]",
        "solution_js": "var KthLargest = function(k, nums) {\n    // sort ascending because I am familiar with it\n    // when applying my binary search algorithm\n    this.nums = nums.sort((a,b) => a - b);    \n    this.k = k;    \n};\n\nKthLargest.prototype.add = function(val) {\n    // search a place to push val\n    // using binary search\n    let left = 0; right = this.nums.length - 1;\n    while (left < right) {\n        let mid = left + Math.floor((right + 1 - left)/2);\n        \n        if (val < this.nums[mid]) {\n            right = mid - 1;\n        } else {\n            left = mid\n        }\n    }    \n    \n    // push val into the nums\n    this.nums.splice(left+(this.nums[left] < val ? 1 : 0), 0, val);  \n\n    // because our nums is sorted\n    // so kth largest element is easy to be returned\n    return this.nums[this.nums.length-this.k]\n};",
        "solution_java": "class KthLargest {\n    PriorityQueue<Integer> queue=new PriorityQueue();\n    int k=0;\n    public KthLargest(int k, int[] nums) {\n        this.k=k;\n        for(int i:nums)\n            add(i);\n    }\n    \n    public int add(int val) {\n        if(k>queue.size())\n            queue.add(val);\n        else\n            if(val>queue.peek())\n            {\n                queue.poll();\n                queue.add(val);\n            }\n        return queue.peek();\n    }\n}",
        "solution_c": "class KthLargest {\n    \n    int k;\n    priority_queue<int, vector<int>, greater<int>> minheap;\n    int n;\n    \npublic:\n    KthLargest(int k, vector<int>& nums) {\n        this->k=k;\n        this->n=nums.size();\n        \n//         push the initial elements in the heap\n        for(auto x : nums){\n            minheap.push(x);\n        }\n        \n//         if the no. of elements are greater than k then remove them\n        while(n>k){\n            minheap.pop();\n            n--;\n        }\n    }    \n    \n    int add(int val) {\n        \n//         if heap is empty or no. of elements are less than k then add the input\n        if(minheap.empty() || n<k){\n            minheap.push(val);\n            this->n=n+1;\n        }\n//         else compare it with top\n        else{\n            int minn=minheap.top();\n//             if the input is greater than top\n            if(minn<val){\n                minheap.pop();\n                minheap.push(val);\n            }\n        }\n//         at any point of time top of the heap is required ans\n        return minheap.top();\n        \n        \n    }\n};\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * KthLargest* obj = new KthLargest(k, nums);\n * int param_1 = obj->add(val);\n */"
    },
    {
        "title": "Degree of an Array",
        "algo_input": "Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.\n\nYour task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,2,3,1]\nOutput: 2\nExplanation: \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\n\n\nExample 2:\n\nInput: nums = [1,2,2,3,1,4,2]\nOutput: 6\nExplanation: \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n\n\n&nbsp;\nConstraints:\n\n\n\tnums.length will be between 1 and 50,000.\n\tnums[i] will be an integer between 0 and 49,999.\n\n",
        "solution_py": "class Solution:\n    def findShortestSubArray(self, nums):\n        # Group indexes by element type\n        d = defaultdict(list)\n        for i,x in enumerate(nums):\n            d[x].append(i)\n        #\n        # Find highest Degree\n        m = max([ len(v) for v in d.values() ])\n        #\n        # Find shortest span for max. degree\n        best = len(nums)\n        for v in d.values():\n            if len(v)==m:\n                best = min(best,v[-1]-v[0]+1)\n        return best",
        "solution_js": "/**\n * 1. compute all positions for each number\n * 2. filter arrays of max length\n * 3. select minimum difference between its first and last elems\n */\nvar findShortestSubArray = function(nums) {\n    const numPositions = {};\n    for (let i=0; i<nums.length; i++) {\n        const num = nums[i];\n        if (numPositions[num] == null) numPositions[num] = [];\n        numPositions[num].push(i);\n    }\n\n    let maxLen = 0;\n    // will store the positions of most frequent numbers\n    let maxPos = [];\n    for (const positions of Object.values(numPositions)) {\n        const curLen = positions.length;\n        if (curLen === maxLen) {\n            maxPos.push(positions);\n        } else if (curLen > maxLen) {\n            maxLen = curLen;\n            maxPos = [positions]\n        }\n    }\n\n    let minDist = Number.MAX_SAFE_INTEGER;\n    for (const positions of maxPos) {\n        minDist = Math.min(minDist, positions[positions.length-1] - positions[0] + 1);\n    }\n    return minDist;\n};",
        "solution_java": "class Solution {\n    public int findShortestSubArray(int[] nums) {\n       int ans = Integer.MAX_VALUE;\n        Map<Integer, Integer> count = new HashMap<>();\n        Map<Integer, Integer> startIndex = new HashMap<>();\n        Map<Integer, Integer> endIndex = new HashMap<>();\n\n        for (int i = 0; i < nums.length; i++) {\n            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);\n        }\n\n        for (int i = 0; i < nums.length; i++) {\n            int no = nums[i];\n            if (!startIndex.containsKey(no)) {\n                startIndex.put(no, i);\n            }\n            endIndex.put(no, i);\n        }\n\n        int degree = Integer.MIN_VALUE;\n        for (Integer key : count.keySet()) {\n            degree = Math.max(degree, count.get(key));\n        }\n\n        for (Integer key : count.keySet()) {\n            if (count.get(key) == degree) {\n                int arraySize = endIndex.get(key) - startIndex.get(key) + 1;\n                ans = Math.min(ans, arraySize);\n            }\n        }\n\n        return ans; \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findShortestSubArray(vector<int>& nums)\n    {\n        unordered_map<int,int> cnt,first;\n        int deg=0,ans=0;\n        for(int i=0;i<nums.size();i++)\n        {\n            if(cnt[nums[i]]==0)\n                first[nums[i]]=i;\n            cnt[nums[i]]++;\n            if(cnt[nums[i]]>deg)\n            {\n                ans=i-first[nums[i]]+1;\n                deg=cnt[nums[i]];\n            }\n            else if(cnt[nums[i]]==deg)\n            {\n                ans=min(ans,i-first[nums[i]]+1);\n            }\n\n        }\n        return ans;\n\n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Min Cost to Connect All Points",
        "algo_input": "You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].\n\nThe cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.\n\nReturn the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.\n\n&nbsp;\nExample 1:\n\nInput: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput: 20\nExplanation: \n\nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\n\n\nExample 2:\n\nInput: points = [[3,12],[-2,5],[-4,1]]\nOutput: 18\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 1000\n\t-106 &lt;= xi, yi &lt;= 106\n\tAll pairs (xi, yi) are distinct.\n\n",
        "solution_py": "class Solution:\n    def minCostConnectPoints(self, points: List[List[int]]) -> int:\n\n        cost = 0\n        heap = []\n\n        #set to store past points to prevent cycle\n        visited = set([0])\n\n        #i == the index of current point\n        i = 0\n\n        while len(visited) < len(points):\n            #Add all costs from current point to unreached points to min heap\n            for j in range(len(points)):\n                if j == i or j in visited:\n                    continue\n                distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])\n                heapq.heappush(heap, (distance, j))\n\n            #Add new min cost edge\n            while True:\n                dist, point = heapq.heappop(heap)\n                if point not in visited:\n                    cost += dist\n                    #Add point to visited to prevent cycle\n                    visited.add(point)\n                    #Update point\n                    i = point\n                    break\n\n        return cost",
        "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\n//By Kruskal Approach\nlet union_find,mapping_arr,count,maxCost,rank\nconst find=(root)=>{\n    if(union_find[root]===root)return root;\n    return union_find[root]= find(union_find[root]);\n}\nconst union=([src,dst,d])=>{\n    let rootX=find(src);\n    let rootY=find(dst);\n    if(rootX!=rootY){\n        if(rank[rootX]<rank[rootY]){\n            union_find[rootX]=rootY;\n        }else if(rank[rootX]>rank[rootY]){\n            union_find[rootY]=rootX;\n        }else{\n            union_find[rootY]=rootX;\n            rank[rootX]++;\n        }\n        count--;\n        maxCost+=d;\n    }\n    \n    \n}\nvar minCostConnectPoints = function(points) {\n    let edges=[];\n    union_find=[];\n    rank=[];\n    maxCost=0;\n    count=points.length;\n    for(let i=0;i<points.length;i++){\n        union_find[i]=i;\n        rank[i]=1\n        let src=points[i];\n        for(let j=i+1;j<points.length;j++){\n            let dst=points[j];\n            let d= Math.abs(src[0]-dst[0])+Math.abs(src[1]-dst[1])\n            edges.push([i,j,d]);\n        }\n    }\n    edges.sort((a,b)=>a[2]-b[2])\n    for(let i=0;i<edges.length;i++){\n        if(count>1)\n        union(edges[i]);\n    }\n\n    return maxCost;\n    \n};",
        "solution_java": "class Solution {\n\tpublic int minCostConnectPoints(int[][] points) {\n\t\tint n = points.length;\n\t\tPriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[0]-b[0]);\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tfor(int j = i + 1; j < n; j++) {\n\t\t\t\tpq.add(new int[]{calDis(points,i,j),i,j});\n\t\t\t}\n\t\t}\n\t\tint c = 0, ans = 0;\n\t\tUnionFind uf = new UnionFind(n);\n\t\twhile(c < n-1){\n\t\t\tint[] cur = pq.poll();\n\t\t\tif(uf.find(cur[1]) != uf.find(cur[2])) {\n\t\t\t\tans += cur[0];\n\t\t\t\tuf.union(cur[1],cur[2]);\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\tprivate int calDis(int[][] points, int a, int b) {\n\t\treturn Math.abs(points[a][0] - points[b][0]) + Math.abs(points[a][1] - points[b][1]);\n\t}\n\tclass UnionFind{\n\t\tint[] parent;\n\t\tUnionFind(int n){\n\t\t\tthis.parent = new int[n];\n\t\t\tfor(int i=0;i<n;i++)parent[i]=i;\n\t\t}\n\t\tpublic int find(int u){\n\t\t\tif(parent[u]!=u)parent[u] = find(parent[u]);\n\t\t\treturn parent[u];\n\t\t}\n\t\tpublic void union(int u, int v){\n\t\t\tparent[find(u)] = parent[find(v)];\n\t\t}\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    int minCostConnectPoints(vector<vector<int>>& points) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n\n        int n = points.size();\n        priority_queue<vector<int>> q;\n        unordered_set<int> vis;\n        int ans = 0;\n        q.push({0,0,0});\n        vector<int> cur;\n        while(!q.empty() && vis.size()<n){\n            cur = q.top(); q.pop();\n            if(vis.count(cur[2]))continue;\n            ans += -cur[0];\n            vis.insert(cur[2]);\n            for(int i=0;i<n;i++){\n                if(!vis.count(i)){\n                    int d = abs(points[cur[2]][0] - points[i][0]) +\n                        abs(points[cur[2]][1] - points[i][1]);\n                    q.push({-d,cur[2],i});\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Most Beautiful Item for Each Query",
        "algo_input": "You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.\n\nYou are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.\n\nReturn an array answer of the same length as queries where answer[j] is the answer to the jth query.\n\n&nbsp;\nExample 1:\n\nInput: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]\nOutput: [2,4,5,5,6,6]\nExplanation:\n- For queries[0]=1, [1,2] is the only item which has price &lt;= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n  The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n  The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n  Hence, the answer for them is the maximum beauty of all items, i.e., 6.\n\n\nExample 2:\n\nInput: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]\nOutput: [4]\nExplanation: \nThe price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty.  \n\n\nExample 3:\n\nInput: items = [[10,1000]], queries = [5]\nOutput: [0]\nExplanation:\nNo item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= items.length, queries.length &lt;= 105\n\titems[i].length == 2\n\t1 &lt;= pricei, beautyi, queries[j] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n\n        items.sort()\n        dic = dict()\n        res = []\n        gmax = 0\n        for p,b in items:\n            gmax = max(b,gmax)\n            dic[p] = gmax\n\n        keys = sorted(dic.keys())\n        for q in queries:\n            ind = bisect.bisect_left(keys,q)\n            if ind<len(keys) and keys[ind]==q:\n                res.append(dic[q])\n            elif ind==0:\n                res.append(0)\n            else:\n                res.append(dic[keys[ind-1]])\n\n        return res",
        "solution_js": "var maximumBeauty = function(items, queries) {\n    items.sort((a,b) => a[0]-b[0]);\n    const n = items.length;\n    \n    \n    let mx = items[0][1];\n    \n    for (let i = 0; i<n; i++) {\n        mx = Math.max(mx, items[i][1]);\n        items[i][1] = mx;\n    }\n    \n    \n    const ans = [];\n    \n    for (const q of queries) {\n        let l = 0, r = n-1, a = 0;\n        while (l<=r) {\n            let mid = Math.floor(l+(r-l)/2);\n            if (items[mid][0]<=q) {\n                a = items[mid][1]\n                l = mid+1;\n            } else r = mid-1;\n        }\n        ans.push(a)\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int[] maximumBeauty(int[][] items, int[] queries) {\n        int[] ans = new int[queries.length];\n        Arrays.sort(items, (a, b) -> (a[0] - b[0]));\n        int maxBeautySoFar = Integer.MIN_VALUE;\n        int[] maxBeauty = new int[items.length];\n        \n        for(int i = 0; i < items.length; i++) {\n            if(maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];\n            maxBeauty[i] = maxBeautySoFar;\n        }\n        \n        for(int i = 0; i < queries.length; i++) {\n            int idx = findLargestIdxWithPriceLessThan(items, queries[i]);\n            if(idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];\n        }\n        return ans;\n    }\n    \n    public int findLargestIdxWithPriceLessThan(int[][] items, int price) {\n        int l = 0;\n        int r = items.length - 1;\n        int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE; \n        while(l <= r) {\n            int mid = (l + r)/2;\n            if(items[mid][0] > price) {\n                r = mid - 1;\n            } else {\n                maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);\n                l = mid + 1;\n            }\n        }\n        return maxIdxLessThanEqualToPrice;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {\n       vector<vector<int>> v;\n        int n = queries.size();\n        for(int i = 0; i < n; i++){\n            v.push_back({queries[i],i});\n        }\n        sort(v.begin(),v.end());\n        sort(items.begin(),items.end());\n        vector<int> ans(n);\n        int j=0;\n        n = items.size();\n        int mx = 0;\n        for(auto &i: v){\n            while(j<n && items[j][0]<=i[0]){\n                mx = max(mx,items[j][1]);\n                j++;\n            }\n            ans[i[1]] = mx;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Add One Row to Tree",
        "algo_input": "Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.\n\nNote that the root node is at depth 1.\n\nThe adding rule is:\n\n\n\tGiven the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.\n\tcur's original left subtree should be the left subtree of the new left subtree root.\n\tcur's original right subtree should be the right subtree of the new right subtree root.\n\tIf depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput: [4,1,1,2,null,null,6,3,1,5]\n\n\nExample 2:\n\nInput: root = [4,2,null,3,1], val = 1, depth = 3\nOutput: [4,2,null,1,1,3,null,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\tThe depth of the tree is in the range [1, 104].\n\t-100 &lt;= Node.val &lt;= 100\n\t-105 &lt;= val &lt;= 105\n\t1 &lt;= depth &lt;= the depth of tree + 1\n\n",
        "solution_py": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\n\nclass Solution:\n\n    def Solve(\n        self,\n        root,\n        val,\n        depth,\n        curr,\n        ):\n        if root == None:\n            return None\n        if depth == 1:\n            return TreeNode(val, root)\n        if curr == depth - 1:\n            (left, right) = (root.left, root.right)\n            (root.left, root.right) = (TreeNode(val, left),\n                    TreeNode(val, None, right))\n            return root\n        self.Solve(root.left, val, depth, curr + 1)\n        self.Solve(root.right, val, depth, curr + 1)\n        return root\n\n    def addOneRow(\n        self,\n        root,\n        val,\n        depth,\n        ):\n        return self.Solve(root, val, depth, 1)",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} val\n * @param {number} depth\n * @return {TreeNode}\n */\nvar addOneRow = function(root, val, depth) {\n\tif (depth === 1) return new TreeNode(val, root);\n\n\tconst refactor = (node = root, currentDep = 1) => {\n\t\tif (!node) return;\n\t\tif (currentDep === depth - 1) {\n\t\t\tconst { left, right } = node;\n\t\t\tnode.left = new TreeNode(val, left);\n\t\t\tnode.right = new TreeNode(val, null, right);\n\t\t}\n\t\trefactor(node.left, currentDep + 1);\n\t\trefactor(node.right, currentDep + 1);\n\t};\n\trefactor();\n\treturn root;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    public TreeNode addOneRow(TreeNode root, int val, int depth) {\n        findAndAdd(root, val, depth, 1);\n        return root; \n    }\n\n    public void findAndAdd(TreeNode root, int val, int depth, int currDepth){\n        if(depth == 1 && currDepth == 1){\n            root.left = new TreeNode(root.val, root.left, root.right);\n            root.right = null;\n            root.val = val;\n            return;\n        }\n        if(root == null)\n            return;\n        if(currDepth == depth - 1){\n            root.left = new TreeNode(val, root.left, null);\n            root.right = new TreeNode(val, null, root.right);\n        }else{\n            findAndAdd(root.left, val, depth, currDepth + 1);\n            findAndAdd(root.right, val, depth, currDepth + 1);\n        }\n        return;\n    }\n}",
        "solution_c": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\n\nclass Solution:\n\n    def Solve(\n        self,\n        root,\n        val,\n        depth,\n        curr,\n        ):\n        if root == None:\n            return None\n        if depth == 1:\n            return TreeNode(val, root)\n        if curr == depth - 1:\n            (left, right) = (root.left, root.right)\n            (root.left, root.right) = (TreeNode(val, left),\n                    TreeNode(val, None, right))\n            return root\n        self.Solve(root.left, val, depth, curr + 1)\n        self.Solve(root.right, val, depth, curr + 1)\n        return root\n\n    def addOneRow(\n        self,\n        root,\n        val,\n        depth,\n        ):\n        return self.Solve(root, val, depth, 1)"
    },
    {
        "title": "Find Right Interval",
        "algo_input": "You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.\n\nThe right interval for an interval i is an interval j such that startj &gt;= endi and startj is minimized. Note that i may equal j.\n\nReturn an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,2]]\nOutput: [-1]\nExplanation: There is only one interval in the collection, so it outputs -1.\n\n\nExample 2:\n\nInput: intervals = [[3,4],[2,3],[1,2]]\nOutput: [-1,0,1]\nExplanation: There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is &gt;= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is &gt;= end2 = 2.\n\n\nExample 3:\n\nInput: intervals = [[1,4],[2,3],[3,4]]\nOutput: [-1,2,-1]\nExplanation: There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is &gt;= end1 = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= intervals.length &lt;= 2 * 104\n\tintervals[i].length == 2\n\t-106 &lt;= starti &lt;= endi &lt;= 106\n\tThe start point of each interval is unique.\n\n",
        "solution_py": "class Solution:\n    def findRightInterval(self, A: List[List[int]]) -> List[int]:\n        n = len(A)\n        ans = [-1] * n\n\n        for i in range(n):\n            A[i].append(i)\n\n        A.sort()\n        heap = []\n\n        for i in range(n):\n            if A[i][0] == A[i][1]:\n                ans[A[i][2]] = A[i][2]\n            else:\n                while heap and heap[0][0] <= A[i][0]:\n                    ans[heapq.heappop(heap)[1]] = A[i][2]\n                \n                heapq.heappush(heap, [A[i][1], A[i][2]])\n\n        return ans",
        "solution_js": "var findRightInterval = function(intervals) {\n    const data = intervals\n        .map((interval, i) => ({ interval, i }))\n        .sort((a, b) => a.interval[0] - b.interval[0]);\n\n    const res = Array(intervals.length).fill(-1);\n\n    for (let pos = 0; pos < data.length; pos++) {\n        let left = pos;\n        let right = data.length - 1;\n\n        while (left <= right) {\n            const mid = Math.floor((left + right) / 2);\n\n            if (data[pos].interval[1] <= data[mid].interval[0]) {\n                right = mid - 1;\n            } else {\n                left = mid + 1;                    \n            }\n        }\n\n        if (left < data.length) {\n            res[data[pos].i] = data[left].i;\n        }\n    }\n    \n    return res;\n};",
        "solution_java": "/*\n- Time: O(N*log(N))\nLoop through the array with n elements and run binary search with log(N) time for each of them.\n\n- Space: O(N)\nUsed a hashmap map of size N to store the original indeces of intervals\n */\nclass Solution {\n    public int[] findRightInterval(int[][] intervals) {\n        int n = intervals.length;\n        int[] res = new int[n];\n        Map<int[], Integer> map = new HashMap<>();\n        for (int i = 0; i < n; i++) {\n            map.put(intervals[i], i);\n        }\n\n        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n        for (int i = 0; i < n; i++) {\n            int[] interval = binarySearch(intervals, intervals[i][1], i);\n            res[map.get(intervals[i])] = interval == null ? -1 : map.get(interval);\n        }\n        \n        return res;\n    }\n\n    private int[] binarySearch(int[][] intervals, int target, int start) {\n        int l = start, r = intervals.length - 1;\n        \n        while (l <= r) {\n            int m = l + (r - l) / 2;\n            if (intervals[m][0] >= target) {\n                // keep moving the right boundary to the left to get the first\n                // element bigger than target\n                r = m - 1;\n            } else {\n                // if the element we get is bigger than the target, we move the \n                // left boundary to look at right part of the array\n                l = m + 1;\n            }\n        }\n        return l == intervals.length ? null : intervals[l];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findRightInterval(vector<vector<int>>& intervals) {\n\n        map<int, int> mp;\n        int n = intervals.size();\n\n        for(int i = 0; i < n; i++)\n            mp[intervals[i][0]] = i;\n\n        vector<int> ans;\n        for(auto &i : intervals)\n        {\n            auto it = mp.lower_bound(i[1]);\n            ans.push_back(it == mp.end() ? -1 : it->second);\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Letter Tile Possibilities",
        "algo_input": "You have n&nbsp;&nbsp;tiles, where each tile has one letter tiles[i] printed on it.\n\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n\n&nbsp;\nExample 1:\n\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n\n\nExample 2:\n\nInput: tiles = \"AAABBC\"\nOutput: 188\n\n\nExample 3:\n\nInput: tiles = \"V\"\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tiles.length &lt;= 7\n\ttiles consists of uppercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numTilePossibilities(self, tiles: str) -> int:\n        n= len(tiles)\n        tiles=list(tiles)\n        s1=set()\n        for i in range(1,n+1):\n            s1.update(permutations(tiles,i))\n        return len(s1)",
        "solution_js": "//\"\"This solution isn`t the best way but it`s simple\"\"\n var numTilePossibilities = function(tiles) {\n    return search(tiles);\n};\n// this function takes a state and check if it`s valid or !\n// valid state is not null state and unique\n// e.g [\"\",\"A\",\"A\"]=>is not valid state because is has null state and repeated\n// values by contrast [\"A\"] is valid state\n// !!state below is to check if state not null\nconst isValidState=(state=\"\",res=[])=>!!state&&!res.includes(state);\n// this function permutes tiles by backtracking\nconst search=(tiles=\"\",state='',result=[])=>{\n    if(isValidState(state,result))//check if the current state valid\n        result.push(state)\n    //loop through tiles and every time you push letter to state\n    // the remaining tiles will decreased by one\n    /**\n     * ---e.g--\n     * level 1 tiles=AAB state=\"\"\n     * it will loop through the tiles ;\n     * now I am in index 0 push tiles[0] to state now state=A\n     * by making this operation number of option tiles will be\n     * decreased to newTiles=\"AB\"\n     * ...\n     * ..\n     * .\n     * */\n    for(let i=0;i<tiles.length;i++){\n        state+=tiles[i];\n        const newTiles=tiles.substring(0,i)+tiles.substring(i+1);\n        search(newTiles,state,result)\n        state=state.slice(0,state.length-1);\n    }\n    return result.length;\n}",
        "solution_java": "class Solution {\n    private int result=0;\n    public int numTilePossibilities(String tiles) {\n        Map<Character,Integer> map = new HashMap<>();\n        for(char c:tiles.toCharArray()){\n            map.put(c,map.getOrDefault(c,0)+1);\n        }\n        find(map);\n        return result-1;\n    }\n    public void find(Map<Character,Integer> map){\n        result++;\n        for(Map.Entry<Character,Integer> m:map.entrySet()){\n            char c=m.getKey();\n            int val =m.getValue();\n            if(val>0){\n                map.put(c,val-1);\n                find(map);\n                map.put(c,val);\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void recur(vector<string> &ans, string tiles, int index, int &res)\n    {\n        res++;\n\n        for(int i=index; i<tiles.size(); i++)\n        {\n            if(i != index && tiles[i] == tiles[index])\n                continue;\n            swap(tiles[i], tiles[index]);\n            recur(ans, tiles, index+1, res);\n        }\n\n    }\n    \n    int numTilePossibilities(string tiles) {\n        \n        vector<string> ans;\n        sort(tiles.begin(), tiles.end());\n        int res = 0;\n        recur(ans, tiles, 0, res);\n        return res - 1;\n    }\n};"
    },
    {
        "title": "Maximum Number of Weeks for Which You Can Work",
        "algo_input": "There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.\n\nYou can work on the projects following these two rules:\n\n\n\tEvery week, you will finish exactly one milestone of one project. You&nbsp;must&nbsp;work every week.\n\tYou cannot work on two milestones from the same project for two consecutive weeks.\n\n\nOnce all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.\n\nReturn the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.\n\n&nbsp;\nExample 1:\n\nInput: milestones = [1,2,3]\nOutput: 6\nExplanation: One possible scenario is:\n​​​​- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 2.\n- During the 3rd week, you will work on a milestone of project 1.\n- During the 4th week, you will work on a milestone of project 2.\n- During the 5th week, you will work on a milestone of project 1.\n- During the 6th week, you will work on a milestone of project 2.\nThe total number of weeks is 6.\n\n\nExample 2:\n\nInput: milestones = [5,2,1]\nOutput: 7\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 1.\n- During the 3rd week, you will work on a milestone of project 0.\n- During the 4th week, you will work on a milestone of project 1.\n- During the 5th week, you will work on a milestone of project 0.\n- During the 6th week, you will work on a milestone of project 2.\n- During the 7th week, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == milestones.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= milestones[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def numberOfWeeks(self, m: List[int]) -> int:\n        return min(sum(m), 2 * (sum(m) - max(m)) + 1)",
        "solution_js": "var numberOfWeeks = function(milestones) {\n    let maxElement = 0,arraySum = 0;\n\n    for(let milestone of milestones){\n        arraySum += milestone;\n        maxElement = Math.max(maxElement,milestone);\n    }\n\n    let rest = arraySum - maxElement;\n    let difference = maxElement - rest;\n\n    if(difference <= 1) return arraySum;\n\n    return (arraySum - difference) + 1;\n};",
        "solution_java": "class Solution {\n    public long numberOfWeeks(int[] milestones) {\n     \n    \tint i,j,max=-1,n=milestones.length;\n  \n    \tlong sum=0;\n    \tfor(i=0;i<n;i++)\n    \t{\n    \t\tmax=Math.max(max, milestones[i]);\n    \t\tsum+=milestones[i];\n    \t}\n\t\t\n    \t\n    \tlong x=sum-max;\n    \t\n    \tif(max-x>1)\n    \t\treturn sum-(max-x-1);\n    \treturn sum;\n    \t\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long numberOfWeeks(vector<int>& milestones) {\n        long long unsigned int maxel = *max_element(milestones.begin(), milestones.end());\n        long long unsigned int sum = 0;\n        for (auto& m : milestones) sum += m;\n        if (sum - maxel >= maxel) return sum;\n        return (sum - maxel) * 2 + 1;\n    }\n};"
    },
    {
        "title": "Range Sum of BST",
        "algo_input": "Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].\n\n&nbsp;\nExample 1:\n\nInput: root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n\n\nExample 2:\n\nInput: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 2 * 104].\n\t1 &lt;= Node.val &lt;= 105\n\t1 &lt;= low &lt;= high &lt;= 105\n\tAll Node.val are unique.\n\n",
        "solution_py": "class Solution:\n    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n    \n        res = 0\n        \n        def dfs(node):\n            nonlocal res\n            \n            if not node:\n                return\n            \n            if node.val >= low and node.val <= high:\n                \n                res += node.val\n                \n            dfs(node.left)\n            dfs(node.right)\n            \n        dfs(root)\n        \n        return res",
        "solution_js": "var rangeSumBST = function(root, low, high) {\n    let sum = 0;\n    const summer = (root) => {\n        if(!root) {\n            return;\n        }\n\n        sum = root.val >= low && root.val <= high ? root.val + sum : sum;\n\n        summer(root.left)\n        summer(root.right)\n    }\n\n    summer(root);\n\n    return sum;\n};",
        "solution_java": "class Solution {\n    private int sum = 0;\n    public int rangeSumBST(TreeNode root, int low, int high) {\n        dfs(root, low, high);\n        return sum;\n    }\n    \n    public void dfs(TreeNode root, int low, int high){\n        if(root == null) return;\n        \n        if(root.val < low) dfs(root.right, low, high);\n        else if(root.val > high) dfs(root.left, low, high);\n        \n        if(root.val >= low && root.val <= high) {\n            sum += root.val;\n            dfs(root.left, low, high);\n            dfs(root.right, low, high);\n        }\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int solve(TreeNode* root, int low, int high){\n        if(root == NULL)\n            return 0;\n\n        int sum = 0;\n        if(low <= root->val && root->val <= high){\n            sum = root->val;\n        }\n\n        return sum + solve(root->left, low, high) + solve(root->right, low, high);\n    }\n\n    int rangeSumBST(TreeNode* root, int low, int high) {\n\n        return solve(root, low, high);\n    }\n};"
    },
    {
        "title": "Plus One",
        "algo_input": "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.\n\nIncrement the large integer by one and return the resulting array of digits.\n\n&nbsp;\nExample 1:\n\nInput: digits = [1,2,3]\nOutput: [1,2,4]\nExplanation: The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].\n\n\nExample 2:\n\nInput: digits = [4,3,2,1]\nOutput: [4,3,2,2]\nExplanation: The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].\n\n\nExample 3:\n\nInput: digits = [9]\nOutput: [1,0]\nExplanation: The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= digits.length &lt;= 100\n\t0 &lt;= digits[i] &lt;= 9\n\tdigits does not contain any leading 0's.\n\n",
        "solution_py": "class Solution(object):\n    def plusOne(self, digits):\n        for i in range(len(digits)-1, -1, -1):\n            if digits[i] == 9:\n                digits[i] = 0\n            else:\n                digits[i] += 1\n                return digits\n        return [1] + digits",
        "solution_js": "var plusOne = function(digits) {\n    for(let i=digits.length-1; i>=0; i--){\n        if(digits[i] === 9){\n            digits[i] = 0\n        }else{\n            digits[i] += 1\n            return digits\n        }\n    }\n    digits.unshift(1)\n    return digits\n};",
        "solution_java": "class Solution {\n    public int[] plusOne(int[] digits) {\n\n        int len = digits.length;\n\n        //last digit not a 9, just add 1 to it\n        if(digits[len - 1] != 9){\n            digits[len - 1] = digits[len - 1] + 1;\n            return digits;\n        }\n\n        //last digit is a 9, find the closest digit that is not a 9\n        else{\n            int i = len - 1;\n            while(i >= 0 && digits[i] == 9){\n                digits[i] = 0;\n                i--;\n            }\n            if(i == -1){\n                int[] ret = new int[len + 1];\n                for(int j = 0; j < len; j++){\n                    ret[j+1] = digits[j];\n                }\n                ret[0] = 1;\n                return ret;\n            }\n            digits[i] = digits[i] + 1;\n        }\n\n        return digits;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> plusOne(vector<int>& digits) {\n        int len = digits.size(), carry = 0, temp = 0;\n        \n        vector<int> arr;\n        \n        for(int i=len-1; i>=0; i--) { // traverse from back to front\n            temp = digits[i] + carry;\n            \n            if(i == len-1) {\n                temp++;\n            }\n            \n            arr.push_back(temp % 10);\n            carry = temp/10;\n        }\n        \n        if(carry) {\n            arr.push_back(carry);\n        }\n        \n        reverse(arr.begin(), arr.end());\n        return arr;\n    }\n};"
    },
    {
        "title": "Matrix Block Sum",
        "algo_input": "Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:\n\n\n\ti - k &lt;= r &lt;= i + k,\n\tj - k &lt;= c &lt;= j + k, and\n\t(r, c) is a valid position in the matrix.\n\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[12,21,16],[27,45,33],[24,39,28]]\n\n\nExample 2:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput: [[45,45,45],[45,45,45],[45,45,45]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm ==&nbsp;mat.length\n\tn ==&nbsp;mat[i].length\n\t1 &lt;= m, n, k &lt;= 100\n\t1 &lt;= mat[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def matrixBlockSum(self, matrix: List[List[int]], k: int) -> List[List[int]]:\n        ROWS, COLS = len(matrix), len(matrix[0])\n\n        prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)]\n\n        for r in range(1, ROWS + 1):\n            for c in range(1, COLS + 1):\n                prefix_sums[r][c] = prefix_sums[r - 1][c] + prefix_sums[r][c - 1] + \\\n                    matrix[r - 1][c - 1] - prefix_sums[r - 1][c - 1]\n\n        res = [[0] * COLS for _ in range(ROWS)]\n        for r in range(ROWS):\n            for c in range(COLS):\n                res[r][c] = prefix_sums[min(r + k + 1, ROWS)][min(c + k + 1, COLS)] - \\\n                    prefix_sums[max(r - k, 0)][min(c + k + 1, COLS)] - \\\n                    prefix_sums[min(r + k + 1, ROWS)][max(c - k, 0)] + \\\n                    prefix_sums[max(r - k, 0)][max(c - k, 0)]\n\n        return res",
        "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number[][]}\n */\nvar matrixBlockSum = function(mat, k) {\n    let sum = 0;\n    let dp = Array(mat.length + 1);\n    dp[0] = Array(mat[0].length).fill(0);\n\n    // sum of row el\n    for (let i = 0; i < mat.length; i++){\n        dp[i + 1] = Array(mat[0].length).fill(0);\n        for (let j = 0; j < mat[0].length; j++){\n            dp[i + 1][j] += mat[i][j] + sum;\n            sum = dp[i + 1][j];\n        }\n        sum = 0;\n    }\n\n    // sum of col el\n    for (let j = 0; j < mat[0].length; j++){\n        for (let i = 0; i < mat.length; i++){\n            dp[i + 1][j] += sum;\n            sum = dp[i + 1][j];\n        }\n        sum = 0;\n    }\n\n    dp = dp.slice(1);\n\n    // cal sum of blocks\n    for (let i = 0; i < mat.length; i++){\n        let r1 = Math.max(0, i - k);\n        let r2 = Math.min(mat.length - 1, i + k);\n        for (let j = 0; j < mat[0].length; j++){\n            let c1 = Math.max(0, j - k);\n            let c2 = Math.min(mat[0].length - 1, j + k);\n\n            let value = dp[r2][c2];\n\n            if (r1 - 1 >= 0){\n                value -= dp[r1 - 1][c2];\n            }\n            if (c1 - 1 >= 0){\n                value -= dp[r2][c1 - 1]\n            }\n            if (r1 - 1 >= 0 && c1 - 1 >= 0){\n                value += dp[r1 - 1][c1 - 1];\n            }\n            mat[i][j] = value;\n        }\n    }\n\n    return mat;\n\n};",
        "solution_java": "class Solution {\n    public int[][] matrixBlockSum(int[][] mat, int k) {\n        int m = mat.length,n = mat[0].length;\n        int[][] answer = new int[m][n];\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                int val = 0;\n                // take new variables to get starting index of mat[r][c]\n                int p = i-k,q=j-k;\n                //make sure p and q are atleast 0 (i.e. valid)\n                while(p<0)\n                    p++;\n                while(q<0)\n                    q++;\n                //traverse again in the matrix with starting at p,q and ending at i+k and j+k\n                //add conditions to make sure the indices dont cross the values of m and n\n                for(int x = p;x<=i+k && x<m;x++){\n                    for(int y = q;y<=j+k && y<n;y++){\n                        val += mat[x][y];\n                    }\n                }\n                answer[i][j] = val;\n            }\n        }\n        return answer;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {\n        int n = mat.size(), m = mat[0].size();\n        vector<vector<int>> pref(n+1, vector<int>(m+1, 0));\n        // Calculating prefix sum\n        for(int i = 1; i <= n; i++){\n            for(int j = 1; j <= m; j++){\n                // note that while counting for [i-1][j] and [i][j-1];\n                // pref[i-1][j-1] will be added twice. So we reduce it once.\n                pref[i][j] = mat[i-1][j-1] + pref[i-1][j] + pref[i][j-1] - pref[i-1][j-1];\n            }\n        }\n\n        // Find the sum of the elements specified in the K-block\n        vector<vector<int>> res(n, vector<int>(m, 0));\n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < m; j++){\n                // checking for all pairs to be in bounds.\n                int r1 = max(0, i-k);\n                int c1 = max(0, j-k);\n                int r2 = min(n-1, i+k);\n                int c2 = min(m-1, j+k);\n                // finding res[i][j] = bottom right - bottom left - top right + top left\n                res[i][j] = pref[r2+1][c2+1] - pref[r2+1][c1] - pref[r1][c2+1] + pref[r1][c1];\n            }\n        }\n\n        return res;\n\n    }\n};"
    },
    {
        "title": "Target Sum",
        "algo_input": "You are given an integer array nums and an integer target.\n\nYou want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.\n\n\n\tFor example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression \"+2-1\".\n\n\nReturn the number of different expressions that you can build, which evaluates to target.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,1,1,1], target = 3\nOutput: 5\nExplanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n\n\nExample 2:\n\nInput: nums = [1], target = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 20\n\t0 &lt;= nums[i] &lt;= 1000\n\t0 &lt;= sum(nums[i]) &lt;= 1000\n\t-1000 &lt;= target &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def findTargetSumWays(self, nums: List[int], target: int) -> int:\n        @cache\n        def dfs(i, sum_):\n            if i == len(nums):\n                if sum_ == target: return 1\n                else: return 0\n            return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i])\n        if abs(target) > sum(nums): return 0\n        return dfs(0, 0)",
        "solution_js": "var findTargetSumWays = function(nums, target) {\n    const memo = new Map()\n    return backtrack(0, 0)\n    \n    function backtrack(i, cur){\n        const key = `${i} ${cur}`\n        if(i == nums.length) return cur == target ? 1 : 0\n        if(!memo.has(key)) memo.set(key, backtrack(i + 1, -nums[i] + cur) + backtrack(i + 1, nums[i] + cur))\n        return memo.get(key)\n    }\n};",
        "solution_java": "class Solution {\n    public int findTargetSumWays(int[] nums, int target) {\n        int sum = 0;\n        for(int i:nums){\n            sum += i;\n        }\n        if(target>sum || target<-sum || ((target+sum)&1)!=0) return 0;\n        return subsetSum(nums,(target+sum)/2);\n    }\n    private int subsetSum(int[] nums,int target){\n        int[][] dp = new int[nums.length+1][target+1];\n        dp[0][0] = 1;\n        \n        for(int i=1;i<nums.length+1;i++){\n            for(int j=0;j<target+1;j++){\n                if(nums[i-1]<=j){\n                    dp[i][j] += dp[i-1][j-nums[i-1]] + dp[i-1][j];\n                }\n                else dp[i][j] += dp[i-1][j];\n            }\n        }\n        return dp[nums.length][target];\n    }\n}",
        "solution_c": "class Solution { // YAA\npublic:\n    \n    int solve(vector<int>& nums, int target, int idx, unordered_map<string, int> &dp) {\n        if(idx == nums.size()) {\n            if(target == 0) {\n                return 1;\n            }\n            return 0;\n        }\n        string key = to_string(idx) + \" \" + to_string(target);\n        if(dp.find(key) != dp.end()) {\n            return dp[key];\n        }\n        // +\n        int x = solve(nums, target - nums[idx], idx+1, dp);\n        // -\n        int y = solve(nums, target + nums[idx], idx+1, dp);\n        // sum\n        return dp[key] = x+y;\n    }\n    int findTargetSumWays(vector<int>& nums, int target) {\n        unordered_map<string, int> dp;\n        return solve(nums, target, 0, dp);\n    }\n};"
    },
    {
        "title": "Minimum Cost Tree From Leaf Values",
        "algo_input": "Given an array arr of positive integers, consider all binary trees such that:\n\n\n\tEach node has either 0 or 2 children;\n\tThe values of arr correspond to the values of each leaf in an in-order traversal of the tree.\n\tThe value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.\n\n\nAmong all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.\n\nA node is a leaf if and only if it has zero children.\n\n&nbsp;\nExample 1:\n\nInput: arr = [6,2,4]\nOutput: 32\nExplanation: There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.\n\n\nExample 2:\n\nInput: arr = [4,11]\nOutput: 44\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 40\n\t1 &lt;= arr[i] &lt;= 15\n\tIt is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 231).\n\n",
        "solution_py": "class Solution:\n    def mctFromLeafValues(self, arr: List[int]) -> int:\n        n = len(arr)\n        d = {}\n        def findMax(start,end):\n            if (start,end) in d: return d[(start,end)]\n            maxx = start\n            for i in range(start+1,end+1):\n                if arr[maxx] < arr[i] : maxx = i\n            d[(start,end)] = arr[maxx]\n            return arr[maxx]\n\n        dp = [[float('inf') for i in range(n)] for j in range(n)]\n        for gap in range(n):\n            for row in range(n - gap):\n                col = row + gap\n                if gap == 0:\n                    dp[row][col] = 0\n                elif gap == 1:\n                    dp[row][col] = arr[row] * arr[col]\n                else:\n                    for k in range(row,col):\n                        val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]\n                        if val < dp[row][col]: dp[row][col] = val\n\n        return dp[0][-1]",
        "solution_js": "var mctFromLeafValues = function(arr) {\n  const dp = [];\n\n  for (let i = 0; i < arr.length; i++) {\n    dp[i] = [];\n  }\n\n  return treeBuilder(0, arr.length - 1);\n\n  function treeBuilder(start, end) {\n\n    if (start == end) {\n      return 0;\n    }\n\n    if (dp[start][end]) {\n      return dp[start][end];\n    }\n\n    let min = Number.MAX_VALUE;\n\n    for (let i = start; i < end; i++) {\n      const left = treeBuilder(start, i);\n      const right = treeBuilder(i + 1, end);\n\n      const maxLeft = Math.max(...arr.slice(start, i + 1));\n      const maxRight = Math.max(...arr.slice(i + 1, end + 1));\n\n      const rootVal = maxLeft * maxRight;\n\n      min = Math.min(min, rootVal + left + right);\n\n    }\n\n    dp[start][end] = min;\n    return min;\n  }\n};",
        "solution_java": "class Solution {\n    public int mctFromLeafValues(int[] arr) {\n        \n        int sum = 0;\n        Stack<Integer> stack = new Stack<>();\n        for (int num: arr) {\n            sum += cleanUpStack(num, stack);\n        }\n        sum += cleanUpStack(17, stack);\n        \n        return sum;\n    }\n    \n    private int cleanUpStack(int target, Stack<Integer> stack) {\n        int last = 0;\n        int sum = 0;\n        while (!stack.isEmpty() && stack.peek() <= target) {\n            int cur = stack.pop();\n            sum += last * cur;\n            last = cur;\n        }\n        if (target != 17) {\n            sum += target * last;\n            stack.push(target);\n        }\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[40][40]={0};\n    int solve(vector<int> arr,int start,int end)\n    {\n        if(start==end)\n            return 0;\n        if(dp[start][end]!=0)\n            return dp[start][end];\n        int mn=INT_MAX;\n        for(int i=start;i<=end-1;i++)\n        {\n            int left=solve(arr,start,i);\n            int right=solve(arr,i+1,end);\n            int temp=left+right+*max_element(arr.begin()+start,arr.begin()+i+1) * *max_element(arr.begin()+i+1,arr.begin()+end+1);\n            mn=min(mn,temp);\n            \n        }\n        return dp[start][end]=mn;\n    }\n    int mctFromLeafValues(vector<int>& arr)\n    {\n        return solve(arr,0,arr.size()-1);\n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Longer Contiguous Segments of Ones than Zeros",
        "algo_input": "Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.\n\n\n\tFor example, in s = \"110100010\" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.\n\n\nNote that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.\n\n&nbsp;\nExample 1:\n\nInput: s = \"1101\"\nOutput: true\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.\n\n\nExample 2:\n\nInput: s = \"111000\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.\n\n\nExample 3:\n\nInput: s = \"110100010\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def checkZeroOnes(self, s: str) -> bool:\n        s1 = s.split('0')\n        s0 = s.split('1')\n        r1 = max([len(i) for i in s1])\n        r0 = max([len(i) for i in s0])\n        return r1>r0",
        "solution_js": "var checkZeroOnes = function(s) {\n    let longest1 = 0;\n    let longest0 = 0;\n\n    let count1 = 0;\n    let count0 = 0;\n\n    for (let i = 0; i < s.length; i++) {\n        const bit = s.charAt(i);\n\n        if (bit === \"1\") count1++;\n        else count1 = 0;\n\n        if (bit === \"0\") count0++;\n        else count0 = 0;\n\n        longest1 = Math.max(longest1, count1);\n        longest0 = Math.max(longest0, count0);\n    }\n\n    return longest1 > longest0;\n};",
        "solution_java": "class Solution {\n    public boolean checkZeroOnes(String s) {\n        int length1 = 0;\n        int length0 = 0;\n\n        int i = 0;\n        while(i < s.length()){\n            int temp = 0;\n            while(i < s.length() && s.charAt(i) == '1'){ //counting 1s\n                temp++;\n                i++;\n            }\n            length1 = Math.max(temp,length1);\n            temp = 0;\n            while(i < s.length() && s.charAt(i) == '0'){ // counting 0s\n                temp++;\n                i++;\n            }\n            length0 = Math.max(temp,length0);\n        }\n       return length1 > length0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkZeroOnes(string s) {\n        int count1=0;\n        int count2=0;\n       int max1=0;int max2=0;\n        for(int i=0;i<s.size();i++)\n        {\n            if(s[i]=='1')\n            {\n                count1++;\n                if(s[i+1]!=s[i])\n                {\n                    max1=max(count1,max1);\n                    count1=0;\n                }\n            }\n            \n            if(s[i]=='0')\n            {\n                count2++;\n                if(s[i+1]!=s[i])\n                {\n                    max2=max(count2,max2);\n                    count2=0;\n                }\n            }\n        }\n        \n        if(max1>max2)\n            return true;\n        return false;\n        \n        \n    }\n};"
    },
    {
        "title": "Tweet Counts Per Frequency",
        "algo_input": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).\n\nFor example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:\n\n\n\tEvery minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]\n\tEvery hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]\n\tEvery day (86400-second chunks): [10,10000]\n\n\nNotice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).\n\nDesign and implement an API to help the company with their analysis.\n\nImplement the TweetCounts class:\n\n\n\tTweetCounts() Initializes the TweetCounts object.\n\tvoid recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).\n\tList&lt;Integer&gt; getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.\n\t\n\t\tfreq is one of \"minute\", \"hour\", or \"day\" representing a frequency of every minute, hour, or day respectively.\n\t\n\t\n\n\n&nbsp;\nExample:\n\nInput\n[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]\n\nOutput\n[null,null,null,null,[2],[2,1],null,[4]]\n\nExplanation\nTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0);                              // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60);                             // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10);                             // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120);                            // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210);  // return [4]; chunk [0,210] had 4 tweets\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= time, startTime, endTime &lt;= 109\n\t0 &lt;= endTime - startTime &lt;= 104\n\tThere will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.\n\n",
        "solution_py": "import bisect\nclass TweetCounts:\n\n    def __init__(self):\n        self.tweets = {}\n        \n\n    def recordTweet(self, tweetName: str, time: int) -> None:\n        if not tweetName in self.tweets:\n            self.tweets[tweetName] = []\n        index = bisect.bisect_left(self.tweets[tweetName], time)\n        self.tweets[tweetName].insert(index, time)\n        \n    \n    def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n        \n        def find(step):\n            nonlocal tweet\n            result = []\n            for i in range(startTime, endTime+1, step):\n                result.append(bisect.bisect_right(tweet, min(endTime, i + step - 1)) - bisect.bisect_left(tweet, i))\n            return result\n                \n                \n        tweet = self.tweets[tweetName]\n        if freq == \"minute\":\n            return find(60)\n        elif freq == \"hour\":\n            return find(3600)\n        else:\n            return find(86400)",
        "solution_js": "var TweetCounts = function() {\n    this.map = new Map();\n};\n\nTweetCounts.prototype.recordTweet = function(tweetName, time) {\n    if (!this.map.has(tweetName)) this.map.set(tweetName, []);\n    this.map.get(tweetName).push(time);\n};\n\nTweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, endTime) {\n    if (!this.map.has(tweetName)) return [];\n\n    const tweets = this.map.get(tweetName);\n    const buckets = createBuckets(freq, startTime, endTime);\n\n    for (let i = 0; i < tweets.length; i++) {\n        const tweetTime = tweets[i];\n\n        let left = 0;\n        let right = buckets.length - 1;\n\n        while (left <= right) {\n            const mid = (left + right) >> 1;\n            const [startTime, endTime, count] = buckets[mid];\n\n            if (startTime <= tweetTime && tweetTime <= endTime) {\n                buckets[mid][2] = count + 1;\n                break;\n            }\n\n            if (endTime < tweetTime) left = mid + 1;\n            else right = mid - 1;\n        }\n    }\n\n    const res = [];\n\n    for (let i = 0; i < buckets.length; i++) {\n        res.push(buckets[i][2]);\n    }\n\n    return res;\n\n    function createBuckets(freq, startTime, endTime) {\n        const chunks = { \"minute\": 60, \"hour\": 3600, \"day\": 86400 };\n        const buckets = [];\n\n        let start = startTime;\n\n        while (start <= endTime) {\n            const end = Math.min(start + chunks[freq] - 1, endTime);\n            buckets.push([start, end, 0])\n            start = end + 1;\n        }\n\n        return buckets;\n    }\n};",
        "solution_java": "class TweetCounts {\n    Map<String, List<Integer>> map;\n    public TweetCounts() {\n        map = new HashMap<>();\n    }\n\n    public void recordTweet(String tweetName, int time) {\n        map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time);\n    }\n\n    public List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {\n        List<Integer> res = new ArrayList<>();\n        if(map.containsKey(tweetName)) {\n            Collections.sort(map.get(tweetName));\n            while(startTime<=endTime) {\n                int interval = Freq.valueOf(freq).getVal();\n                int end = Math.min(startTime+interval-1, endTime); // need this to handle the last interval\n                res.add(getFreq(map.get(tweetName), startTime, end));\n                startTime=end+1; // ex: for minute, the interval is 60 so our end is 59. The next startTime is end+1\n            }\n        }\n        return res;\n    }\n\n    public int getFreq(List<Integer> list, int start, int end) {\n        int st = Collections.binarySearch(list, start);\n        if(st<0) {\n            st = (st+1)*-1; // our exact start time might not be in the list, to get the 1st timestamp greater than start\n        }\n        int en = Collections.binarySearch(list, end);\n        if(en<0) {\n            en = (en+2)*-1; // our exact end time might not be in the list, to get the last timestamp just smaller than end\n        }\n\n        return en-st+1; // the freq count\n    }\n}\n\n enum Freq {\n    minute(60), hour(3600), day(86400);\n    Map<Freq, Integer> map = new HashMap<>();\n    Freq(int val) {\n        map.put(this, val);\n    }\n\n    public int getVal() {\n         return map.get(this);\n     }\n\n}\n\n/**\n * Your TweetCounts object will be instantiated and called as such:\n * TweetCounts obj = new TweetCounts();\n * obj.recordTweet(tweetName,time);\n * List<Integer> param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);\n */",
        "solution_c": "#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n//less_equal to use it as a multiset\ntypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\n\nclass TweetCounts {\npublic:\n    unordered_map<string, pbds> tweet;\n    TweetCounts() {\n        tweet.clear();\n    }\n    \n    void recordTweet(string tweetName, int time) {\n        tweet[tweetName].insert(time);\n    }\n    \n    vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {\n        int interval;\n        if(freq == \"minute\") interval = 60;\n        else if(freq == \"hour\") interval = 3600;\n        else interval = 86400;\n        \n        vector<int> ans;\n\t\t\n        for(int i=startTime; i<=endTime; i+=interval)\n        {\n            int start = i, end = min(endTime, i+interval-1);\n            \n            //[start - end] or [start - end+1)\n            auto low = tweet[tweetName].order_of_key(start);\n            auto high = tweet[tweetName].order_of_key(end+1);\n            \n            ans.push_back(high-low);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Stone Game IV",
        "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nInitially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\n\nAlso, if a player cannot make a move, he/she loses the game.\n\nGiven a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n\nExample 2:\n\nInput: n = 2\nOutput: false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -&gt; 1 -&gt; 0).\n\n\nExample 3:\n\nInput: n = 4\nOutput: true\nExplanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -&gt; 0).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def winnerSquareGame(self, n: int) -> bool:\n        squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n        \n        @cache\n        def can_win(n: int) -> bool:\n            return n and not all(can_win(n - s) for s in squares(n))\n        \n        return can_win(n)",
        "solution_js": "var winnerSquareGame = function(n) {\n    \n    const map = new Map();\n    map.set(0, false);\n    map.set(1, true);\n    \n    const dfs = (num) => {\n        if( map.has(num) ) return map.get(num);\n        let sqRoot = Math.floor(Math.sqrt(num));\n        \n        for(let g=1; g<=sqRoot; g++){\n            if( !dfs(num - (g*g)) ) {\n                map.set(num, true);\n                return true;\n            }    \n        }\n        map.set(num, false);\n        return false;\n    }\n    \n    return dfs(n)\n};",
        "solution_java": "class Solution {\n    // idea: Alice wins a game with n stones if and only if there exists\n    // some perfect square p <= n such that Alice wins a game with\n    // n - p stones... i.e., Bob DOES NOT win a game with n - p stones\n    public boolean winnerSquareGame(int n) {\n        // this bit would be better with just an array of booleans, but this\n        // is how i thought of it at the time, so leaving it this way...\n        // maybe it will be \"more explicit\" and help someone better understand dp?\n        HashMap<Integer, Boolean> memo = new HashMap<>();\n        memo.put(1, true); // if there is one stone in the pile to begin the game, the next player to go wins\n        memo.put(0, false); // if there are zero stones in the pile to begin the game, the next player to go loses\n        List<Integer> perfectSquares = new ArrayList<>();\n        int i = 1;\n        while (i * i <= n) {\n            perfectSquares.add(i * i);\n            i++;\n        }\n        // if there are some perfect square number of stones in the pile to begin the game, the next player to go wins\n        perfectSquares.forEach(p -> memo.put(p, true));\n        // Alice goes first...\n        return this.playerWins(n, perfectSquares, memo);\n    }\n\n    private boolean playerWins(int n, List<Integer> P, HashMap<Integer, Boolean> m) {\n        if (m.containsKey(n)) { return m.get(n); } // if we already computed the answer for n, just return it\n        m.put(n, false); // otherwise, assume it's false to begin...\n        for (Integer p : P) { // check every perfect square p...\n            if (p <= n && !playerWins(n - p, P, m)) {\n                // if p <= n AND the player who goes next (e.g., Bob) does not win a game that begins with\n                // n - p stones, then we know that the player whose turn it is right now (e.g., Alice) wins\n                // a game that begins with n stones, so record this discovery in the memo and then break out\n                // of the loop because there's no more work to do...\n                m.put(n, true);\n                break;\n            } // else p >= n OR taking p stones would not result in a win for the player whose turn it is right now...\n        }\n        // we put false in before the loop; if we never found a reason to change it to true,\n        // then false is the correct result...\n        return m.get(n);\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    bool winnerSquareGame(int n) {\n\n        vector<int> dp(n+1,false);\n\n        for(int i=1;i<=n;i++){\n            for(int j=sqrt(i);j>=1;j--){\n                if(dp[i-j*j] == false){\n                    dp[i] = true;\n                    break;\n                }\n            }\n        }\n\n        return dp[n];\n    }\n};"
    },
    {
        "title": "Minimum Moves to Reach Target with Rotations",
        "algo_input": "In an&nbsp;n*n&nbsp;grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at&nbsp;(n-1, n-2)&nbsp;and&nbsp;(n-1, n-1).\n\nIn one move the snake can:\n\n\n\tMove one cell to the right&nbsp;if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n\tMove down one cell&nbsp;if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n\tRotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from&nbsp;(r, c)&nbsp;and&nbsp;(r, c+1)&nbsp;to&nbsp;(r, c)&nbsp;and&nbsp;(r+1, c).\n\t\n\tRotate counterclockwise&nbsp;if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from&nbsp;(r, c)&nbsp;and&nbsp;(r+1, c)&nbsp;to&nbsp;(r, c)&nbsp;and&nbsp;(r, c+1).\n\t\n\n\nReturn the minimum number of moves to reach the target.\n\nIf there is no way to reach the target, return&nbsp;-1.\n\n&nbsp;\nExample 1:\n\n\n\nInput: grid = [[0,0,0,0,0,1],\n               [1,1,0,0,1,0],\n&nbsp;              [0,0,0,0,1,1],\n&nbsp;              [0,0,1,0,1,0],\n&nbsp;              [0,1,1,0,0,0],\n&nbsp;              [0,1,1,0,0,0]]\nOutput: 11\nExplanation:\nOne possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n\n\nExample 2:\n\nInput: grid = [[0,0,1,1,1,1],\n&nbsp;              [0,0,0,0,1,1],\n&nbsp;              [1,1,0,0,0,1],\n&nbsp;              [1,1,1,0,0,1],\n&nbsp;              [1,1,1,0,0,1],\n&nbsp;              [1,1,1,0,0,0]]\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 100\n\t0 &lt;= grid[i][j] &lt;= 1\n\tIt is guaranteed that the snake starts at empty cells.\n\n",
        "solution_py": "class Solution:\n    def minimumMoves(self, grid: List[List[int]]) -> int:\n        queue , vis , n = [(0,1,0,0)] , {} , len(grid)\n        while queue:\n            x,y,pos,moves = queue.pop(0)\n            if x == y == n-1 and pos == 0: return moves\n            if pos == 0:\n                if y + 1 < n and grid[x][y+1] == 0 and (x,y+1,0) not in vis:\n                    vis[(x,y+1,0)] = True\n                    queue.append((x,y+1,0,moves+1))\n                \n                if x + 1 < n and grid[x+1][y-1] == 0 and grid[x+1][y] == 0:\n                    if (x+1,y-1,1) not in vis:\n                        vis[(x+1,y-1,1)] = True\n                        queue.append((x+1,y-1,1,moves+1))\n                    if (x+1,y,0) not in vis:\n                        vis[(x+1,y,0)] = True\n                        queue.append((x+1,y,0,moves+1))\n            else:\n                if x + 1 < n and grid[x+1][y] == 0 and (x+1,y,1) not in vis:\n                    vis[(x+1,y,1)] = True\n                    queue.append((x+1,y,1,moves+1))\n                if y + 1 < n and grid[x-1][y+1] == grid[x][y+1] == 0:\n                    if (x-1,y+1,0) not in vis:\n                        vis[(x-1,y+1,0)] = True\n                        queue.append((x-1,y+1,0,moves+1))\n                    if (x,y+1,1) not in vis:\n                        vis[(x,y+1,1)] = True\n                        queue.append((x,y+1,1,moves+1))\n        return -1",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumMoves = function(grid) {\n    const len = grid.length;\n    const initPosition = [0, true, 1]\n    const visited = new Set([initPosition.join()]);\n\n    const queue = new Queue();\n    initPosition.push(0);\n    queue.enqueue(initPosition)\n    while (!queue.isEmpty()) {\n        let [row, isHorizontal, col, numMoves] = queue.dequeue();\n        if (row + col === len * 2 - 2 && isHorizontal) return numMoves;\n        numMoves++;\n        const positions = [];\n        if (isHorizontal) {\n            if (grid[row][col + 1] === 0) {\n                positions.push([row, true, col + 1])\n            }\n            if (row + 1 < len && grid[row + 1][col - 1] === 0 && grid[row + 1][col] === 0) {\n                positions.push([row + 1, true, col])\n                positions.push([row + 1, false, col - 1]);\n            }\n        } else {\n            if (row + 1 < len && grid[row + 1][col] === 0) {\n                positions.push([row + 1, false, col]);\n            }\n            if (row > 0 && grid[row - 1][col + 1] === 0 && grid[row][col + 1] === 0) {\n                positions.push([row, false, col + 1]);\n                positions.push([row - 1, true, col + 1]);\n            }\n        }\n        for (let position of positions) {\n            const str = position.join();\n            if (visited.has(str)) continue;\n            visited.add(str);\n            position.push(numMoves);\n            queue.enqueue(position);\n        }\n    }\n    return -1;\n};\n\nclass Queue {\n    constructor() {\n        this.head = { next: null };\n        this.tail = this.head;\n    }\n\n    isEmpty() {\n        return this.head.next === null;\n    }\n\n    dequeue() {\n        const { value } = this.head.next;\n        this.head = this.head.next;\n        return value;\n    }\n\n    enqueue(value) {\n        this.tail.next = { value, next: null };\n        this.tail = this.tail.next;\n    }\n}",
        "solution_java": "class Solution {\n    public int minimumMoves(int[][] grid) {\n        \n        int n = grid.length;  \n        //boolean[][][][] visited = new boolean[n][n][n][n];\n        Set<Position> set = new HashSet<>();\n       \n        Queue<Position> q = new LinkedList<>();\n        q.offer(new Position(0,0,0,1));        \n        int count = 0;\n                \n        if(grid[n-1][n-2] == 1 || grid[n-1][n-1] == 1)\n            return -1;\n        \n        while(!q.isEmpty()){\n            ++count;\n            Queue<Position> nextq = new LinkedList<>();\n            while(!q.isEmpty()){\n                \n                Position p = q.poll();\n\n                int r1 = p.getr1();\n                int r2 = p.getr2();\n                int c1 = p.getc1();\n                int c2 = p.getc2();\n                \n                if(r1 == n-1 && r2 == n-1 && c1 == n-2 && c2==n-1)\n                    return count-1;\n                \n                if(set.contains(p))\n                    continue;\n                \n                if(c1+1 < n && grid[r1] [c1+1] != 1 && c2+1 < n && grid[r2] [c2+1] != 1)\n                    nextq.offer(new Position(r1, c1+1, r2, c2+1));\n                if(r1+1 < n && grid[r1+1] [c1] != 1 && r2+1 < n && grid[r2+1] [c2] != 1)\n                    nextq.offer(new Position(r1+1, c1, r2+1, c2));\n                \n                if(r1 == r2 && r1+1 < n && r2+1 < n && grid[r1+1][c1] == 0 && grid[r2+1][c2] == 0 && grid[r1+1][c1] == 0)\n                    nextq.offer(new Position(r1,c1, r1+1, c1));\n                \n                if(c1 == c2 && c1+1 < n && c2+1 < n && grid[r1][c1+1] == 0 && grid[r2][c1+1] == 0   && grid[r1][c1+1] == 0)\n                    nextq.offer(new Position(r1,c1, r1, c1+1));\n                set.add(p);\n            }\n            q = nextq;\n        }\n        return -1;\n    }\n    \n    private class Position{\n        int r1;\n        int c1;\n        int r2;\n        int c2;\n        \n        public Position(int r1, int c1, int r2, int c2){\n            this.r1 = r1;\n            this.r2 = r2;\n            this.c1 =c1;\n            this.c2 = c2;\n        }\n        \n        public int getr1(){\n            return this.r1;\n        }\n        public int getr2(){\n            return this.r2;\n        }\n        public int getc1(){\n            return this.c1;\n        }\n        public int getc2(){\n            return this.c2;\n        }\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * r1 + c1 + prime *r2 + c2;\n            return result;\n        }\n        \n        @Override\n        public boolean equals(Object obj) {\n            Position p = (Position) obj;\n            if(this.r1 == p.getr1() && this.r2 ==p.getr2() && this.c1 == p.getc1() && this.c2==p.getc2())\n                return true;\n            else\n                return false;\n        }\n    }    \n}",
        "solution_c": "class Solution {\n\npublic:\n\nint n;\nset<vector<int>> visited;\nbool candown(vector<vector<int>>& grid,int x,int y,bool hor){\n    if(!hor){\n        if(x+2<n && grid[x+1][y]==0 && grid[x+2][y]==0 && !visited.count({x+1,y,hor})){\n            return true;\n        }\n    }else{\n        if(x+1<n && y+1<n && grid[x+1][y]==0 && grid[x+1][y+1]==0 && !visited.count({x+1,y,hor})){\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool canright(vector<vector<int>>& grid,int x,int y,bool hor){\n    if(hor){\n        if(y+2<n && grid[x][y+1]==0 && grid[x][y+2]==0 && !visited.count({x,y+1,hor})){\n            return true;\n        }\n    }else{\n        if(y+1<n && x+1<n && grid[x][y+1]==0 && grid[x+1][y+1]==0 && !visited.count({x,y+1,hor})){\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool canrot(vector<vector<int>>& grid,int x,int y,bool hor){\n    if(hor){\n        if(y+1<n && x+1<n && grid[x+1][y]==0 && grid[x+1][y+1]==0 && !visited.count({x,y,!hor})){\n            return true;\n        }\n    }else{\n        if(x+1<n && y+1<n && grid[x][y+1]==0 &&grid[x+1][y+1]==0 && !visited.count({x,y,!hor})){\n            return true;\n        }\n    }\n    return false;\n}\n\nint minimumMoves(vector<vector<int>>& grid) {\n    queue<array<int, 3>> q;\n    q.push({0,0,true});\n    int ans=0;\n    n=grid.size();\n    while(!q.empty()){\n        int size=q.size();\n        while(size--){\n            auto a=q.front();\n            q.pop();\n            if(visited.count({a[0],a[1],a[2]})){\n                continue;\n            }\n            visited.insert({a[0],a[1],a[2]});\n            int x=a[0];\n            int y=a[1];\n            if(x==n-1 && y==n-2 && a[2]==1){\n                return ans;\n            }\n            if(candown(grid,x,y,a[2])){\n                q.push({x+1,y,a[2]});\n            }\n            if(canrot(grid,x,y,a[2])){\n                q.push({x,y,!a[2]});\n            }\n            if(canright(grid,x,y,a[2])){\n                q.push({x,y+1,a[2]});\n            }\n        }\n        ans++;\n    }\n    return -1;\n}\n};"
    },
    {
        "title": "Merge Sorted Array",
        "algo_input": "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.\n\nMerge nums1 and nums2 into a single array sorted in non-decreasing order.\n\nThe final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput: [1,2,2,3,5,6]\nExplanation: The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.\n\n\nExample 2:\n\nInput: nums1 = [1], m = 1, nums2 = [], n = 0\nOutput: [1]\nExplanation: The arrays we are merging are [1] and [].\nThe result of the merge is [1].\n\n\nExample 3:\n\nInput: nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput: [1]\nExplanation: The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.\n\n\n&nbsp;\nConstraints:\n\n\n\tnums1.length == m + n\n\tnums2.length == n\n\t0 &lt;= m, n &lt;= 200\n\t1 &lt;= m + n &lt;= 200\n\t-109 &lt;= nums1[i], nums2[j] &lt;= 109\n\n\n&nbsp;\nFollow up: Can you come up with an algorithm that runs in O(m + n) time?\n",
        "solution_py": "class Solution(object):\n    def merge(self, nums1, m, nums2, n):\n        # Initialize nums1's index\n        i = m - 1\n        # Initialize nums2's index\n        j = n - 1\n        # Initialize a variable k to store the last index of the 1st array...\n        k = m + n - 1\n        while j >= 0:\n            if i >= 0 and nums1[i] > nums2[j]:\n                nums1[k] = nums1[i]\n                k -= 1\n                i -= 1\n            else:\n                nums1[k] = nums2[j]\n                k -= 1\n                j -= 1",
        "solution_js": "var merge = function(nums1, m, nums2, n) {\n    // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n    let i = m - 1 , j = n - 1;\n    // Initialize a variable k to store the last index of the 1st array...\n    let k = m + n - 1;\n    // Create a loop until either of i or j becomes zero...\n    while(i >= 0 && j >= 0) {\n        if(nums1[i] >= nums2[j]) {\n            nums1[k] = nums1[i];\n            i--;\n        } else {\n            nums1[k] = nums2[j];\n            j--;\n        }\n        k--;\n    // Either of i or j is not zero, which means some elements are yet to be merged.\n    // Being already in a sorted manner, append them to the 1st array in the front.\n    }\n    // While i does not become zero...\n    while(i >= 0)\n        nums1[k--] = nums1[i--];\n    // While j does not become zero...\n    while(j >= 0)\n        nums1[k--] = nums2[j--];\n    // Now 1st array has all the elements in the required sorted order...\n    return;\n};",
        "solution_java": "class Solution {\n    public void merge(int[] nums1, int m, int[] nums2, int n) {\n        // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n        int i = m - 1 , j = n - 1;\n        // Initialize a variable k to store the last index of the 1st array...\n        int k = m + n - 1;\n        // Create a loop until either of i or j becomes zero...\n        while(i >= 0 && j >= 0) {\n            if(nums1[i] >= nums2[j]) {\n                nums1[k] = nums1[i];\n                i--;\n            } else {\n                nums1[k] = nums2[j];\n                j--;\n            }\n            k--;\n        // Either of i or j is not zero, which means some elements are yet to be merged.\n        // Being already in a sorted manner, append them to the 1st array in the front.\n        }\n        // While i does not become zero...\n        while(i >= 0)\n            nums1[k--] = nums1[i--];\n        // While j does not become zero...\n        while(j >= 0)\n            nums1[k--] = nums2[j--];\n        // Now 1st array has all the elements in the required sorted order...\n        return;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n        vector<int> temp(n+m);\n        int i=0,j=0,k=0;\n        while(i<m && j<n){ //select smaller element from both vector\n            if(nums1[i]<nums2[j]){\n                temp[k]=nums1[i];\n                i++;\n                k++;\n            }\n            else{\n                temp[k]=nums2[j];\n                j++;\n                k++;\n            }\n        }\n        while(i<m){ //insert remaining nums1 element\n            temp[k]=nums1[i];\n            i++;\n            k++;\n        }\n        while(j<n){ //insert remaining nums2 element\n            temp[k]=nums2[j];\n            j++;\n            k++;\n        }\n        nums1=temp;\n        return ;\n    }\n};"
    },
    {
        "title": "Find Unique Binary String",
        "algo_input": "Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.\n\n&nbsp;\nExample 1:\n\nInput: nums = [\"01\",\"10\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"00\" would also be correct.\n\n\nExample 2:\n\nInput: nums = [\"00\",\"01\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"10\" would also be correct.\n\n\nExample 3:\n\nInput: nums = [\"111\",\"011\",\"001\"]\nOutput: \"101\"\nExplanation: \"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 16\n\tnums[i].length == n\n\tnums[i] is either '0' or '1'.\n\tAll the strings of nums are unique.\n\n",
        "solution_py": "class Solution(object):\n    def findDifferentBinaryString(self, nums):\n        ans='';\n        for i,num in enumerate(nums):\n            ans+= '1' if(num[i]=='0') else '0'       #ternary if else\n\t\t\t#ans+= str(1- int(num[i]));              # Alternate: cast to string & 1-x to flip\n        return ans;",
        "solution_js": "var findDifferentBinaryString = function(nums) {\n    return nums.map((s, i) => s[i] == 1 ? '0' : '1').join('');\n};",
        "solution_java": "class Solution {\n    public String findDifferentBinaryString(String[] nums) {\n        StringBuilder ans= new StringBuilder();                  \n        for(int i=0; i<nums.length; i++)  \n            ans.append(nums[i].charAt(i) == '0' ? '1' : '0');              // Using ternary operator\n        return ans.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string findDifferentBinaryString(vector<string>& nums) {\n        unordered_set<int> s;\n        for (auto num : nums) s.insert(stoi(num, 0, 2));\n        int res = 0;\n        while (++res) {\n            if (!s.count(res)) return bitset<16>(res).to_string().substr(16-nums.size());\n        }\n        return \"\";\n    }\n};"
    },
    {
        "title": "Remove Zero Sum Consecutive Nodes from Linked List",
        "algo_input": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\n\nAfter doing so, return the head of the final linked list.&nbsp; You may return any such answer.\n\n&nbsp;\n(Note that in the examples below, all sequences are serializations of ListNode objects.)\n\nExample 1:\n\nInput: head = [1,2,-3,3,1]\nOutput: [3,1]\nNote: The answer [1,2,1] would also be accepted.\n\n\nExample 2:\n\nInput: head = [1,2,3,-3,4]\nOutput: [1,2,4]\n\n\nExample 3:\n\nInput: head = [1,2,3,-3,-2]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe given linked list will contain between 1 and 1000 nodes.\n\tEach node in the linked list has -1000 &lt;= node.val &lt;= 1000.\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n    def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        root = ListNode(0,head)\n        summ , d , node = 0 , {} , root\n        while node:\n            summ += node.val\n            if summ in d:\n                prev = d[summ]\n                tmp = prev.next\n                tmp_sum = summ\n                while tmp != node:\n                    tmp_sum += tmp.val\n                    if tmp_sum in d and d[tmp_sum] == tmp :d.pop(tmp_sum)\n                    tmp = tmp.next\n                prev.next = node.next\n                node = prev\n            else:\n                d[summ] = node\n            node = node.next\n\n        return root.next",
        "solution_js": "var removeZeroSumSublists = function(head) {\n    const dummyHead = new ListNode();\n    dummyHead.next = head;\n    let prev = dummyHead;\n    let start = head;\n    \n    while (start != null) {\n        let sum = 0;\n        let tail = start;\n        \n        while (tail != null) {\n            sum += tail.val;\n            if (sum === 0) break;\n            tail = tail.next;\n        }\n        \n        if (tail) {\n            prev.next = tail.next;\n            start = tail.next;\n        }\n        else {\n            prev = start;\n            start = start.next;\n        }\n    }\n    \n    \n    return dummyHead.next;\n};",
        "solution_java": "class Solution {\n    public ListNode removeZeroSumSublists(ListNode head) {\n        \n        ListNode dummy = new ListNode(0);\n        dummy.next = head;\n        \n        int prefix = 0;\n        ListNode curr = dummy;\n        Map<Integer, ListNode> seen = new HashMap<>();\n        seen.put(prefix, dummy);\n        \n        while (curr != null) {\n            prefix += curr.val;\n            seen.put(prefix, curr);\n            curr = curr.next;\n        }\n        \n        prefix = 0;\n        curr = dummy;\n        while (curr != null) {\n            prefix += curr.val;\n            curr.next = seen.get(prefix).next;\n            curr = curr.next;\n        }\n        \n        return dummy.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* removeZeroSumSublists(ListNode* head) {\n        unordered_map<int, ListNode*> m; // {prefix -> node}\n        ListNode* dummy = new ListNode(0);\n        ListNode* cur = dummy;\n        dummy->next = head;\n        int prefix = 0;\n        while(cur){\n            prefix += cur->val;\n            if(m[prefix] != NULL){\n                ListNode *t = m[prefix]->next;\n                int sum = prefix;\n                sum+=t->val;\n                while(sum != prefix){\n                    m.erase(sum);\n                    t = t->next;\n                    sum+= t->val;\n                }\n                m[prefix]->next = cur->next;\n            }\n            else m[prefix] = cur;\n            cur = cur->next;\n        }\n        return dummy->next;\n    }\n};"
    },
    {
        "title": "Break a Palindrome",
        "algo_input": "Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.\n\nReturn the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.\n\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.\n\n&nbsp;\nExample 1:\n\nInput: palindrome = \"abccba\"\nOutput: \"aaccba\"\nExplanation: There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.\n\n\nExample 2:\n\nInput: palindrome = \"a\"\nOutput: \"\"\nExplanation: There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= palindrome.length &lt;= 1000\n\tpalindrome consists of only lowercase English letters.\n\n",
        "solution_py": "class Solution(object):\n    def breakPalindrome(self, palindrome):\n        \"\"\"\n        :type palindrome: str\n        :rtype: str\n        \"\"\"\n        s = palindrome\n        palindrome = [ch for ch in s]\n        if len(palindrome) == 1:\n            return \"\"\n        \n        for i in range(len(palindrome)//2):\n            if palindrome[i] != 'a':\n                palindrome[i] = 'a'\n                return \"\".join(palindrome)\n        palindrome[-1] = 'b'\n        return \"\".join(palindrome)\n        \n        \n                \n                ",
        "solution_js": "var breakPalindrome = function(palindrome) {\n    // domain n / 2 k pehlay\n    palindrome = palindrome.split('');\n    const len = palindrome.length;\n    if(len == 1) return \"\";\n    const domain = Math.floor(len / 2);\n    let firstNonAChar = -1, lastAChar = -1;\n    for(let i = 0; i < domain; i++) {\n        if(palindrome[i] != 'a') {\n            firstNonAChar = i;\n            break;\n        }\n    }\n    if(firstNonAChar == -1) {\n        palindrome[len - 1] = 'b';\n    } else palindrome[firstNonAChar] = 'a';\n    return palindrome.join('');\n};",
        "solution_java": "class Solution {\n    public String breakPalindrome(String palindrome) {\n        \n        int left = 0;\n        int right = palindrome.length()-1;\n        \n        if(palindrome.length()==1)\n            return \"\";\n        \n        while(left<right){\n            \n            char c = palindrome.charAt(left);\n            \n            if(c!='a'){\n                StringBuilder sb = new StringBuilder(palindrome);\n                sb.setCharAt(left,'a');\n                return sb.toString();\n            } \n            else{\n                left++;\n                right--;\n            }\n            \n        \n        }\n       \n        // aaaa\n        // aba\n        \n        \n              StringBuilder sb = new StringBuilder(palindrome);\n                sb.setCharAt(palindrome.length()-1,'b');\n                return sb.toString();\n        \n    \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string breakPalindrome(string palindrome) {\n        int n = palindrome.size();\n        string res = \"\";\n        if(n==1){\n            return res;\n        }\n        int i = 0;\n        while(i<n){\n            if(n%2!=0 && i==n/2){\n                i++;\n                continue;\n            }\n            if(palindrome[i] != 'a'){\n                palindrome[i] = 'a';\n                break;\n            }\n            i++;\n        }\n        if(i==n){\n            palindrome[i-1] = 'b';\n        }\n        return palindrome;\n    }\n};"
    },
    {
        "title": "Delete and Earn",
        "algo_input": "You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:\n\n\n\tPick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.\n\n\nReturn the maximum number of points you can earn by applying the above operation some number of times.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,4,2]\nOutput: 6\nExplanation: You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.\n\n\nExample 2:\n\nInput: nums = [2,2,3,3,3,4]\nOutput: 9\nExplanation: You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t1 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def deleteAndEarn(self, nums: List[int]) -> int:\n        count = Counter(nums)\n        m = max(nums)\n        memo = {}\n        def choose(num):\n            if num > m:\n                return 0\n            if num not in count:\n                count[num] = 0\n            if num in memo:\n                return memo[num]\n            memo[num] = max(choose(num + 1), num * count[num] + choose(num + 2))\n            return memo[num]\n        \n        return choose(1)\n\n# time and space complexity\n# n = max(nums)\n# time: O(n)\n# space: O(n)\n            \n            ",
        "solution_js": "var deleteAndEarn = function(nums) {\n    let maxNumber = 0;\n    \n    const cache = {};\n    const points = {};\n\n    function maxPoints(num) {\n        if (num === 0) {\n            return 0;\n        }\n        \n        if (num === 1) {\n            return points[1] || 0;\n        }\n        \n        if (cache[num] !== undefined) {\n            return cache[num];\n        }\n        \n        const gain = points[num] || 0;\n        return cache[num] = Math.max(maxPoints(num - 1), maxPoints(num - 2) + gain);\n    }\n    \n    for (let num of nums) {\n        points[num] = (points[num] || 0) + num;\n        maxNumber = Math.max(maxNumber, num);\n    }\n\n    return maxPoints(maxNumber);\n};",
        "solution_java": "class Solution {\n    public int deleteAndEarn(int[] nums) {\n        Arrays.sort(nums);\n        int onePreviousAgo = 0;\n        int previous = 0;\n        for(int i = 0; i < nums.length; i++) {\n            int sum = 0;\n            // On hop there's no constraint to add the previous value\n            if(i > 0 && nums[i-1] < nums[i] - 1) {\n                onePreviousAgo = previous;\n            }\n            // Accumulate equal values\n            while(i < nums.length - 1 && nums[i] == nums[i+1]) {\n                sum += nums[i];\n                i++;\n            }\n            int currentPrevious = previous;\n            previous = Math.max(\n                onePreviousAgo + nums[i] + sum,\n                previous\n            );\n            onePreviousAgo = currentPrevious;\n            // System.out.println(nums[i] + \":\" + previous);\n        }\n        return previous;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    // Dynamic Programming : Bottom Up Approach Optmised\n    int deleteAndEarn(vector<int>& nums)\n    {\n        int size = nums.size();\n\n        // Initialise vectors with size 10001 and value 0\n        vector<int> memo(10001 , 0);\n        vector<int> res(10001 , 0);\n\n        // get the count of elements int res vector\n        for(auto num : nums)\n            res[num]++;\n\n        // for index : less than 3 calculate memo[i] as the index times number of occurences\n        // : greater than equal to 3 as calculate memo[i] as the index times number of occurences + max of the last second and third element\n        for(int i = 0 ; i < 10001 ; i++)\n            memo[i] += (i < 3) ? (i * res[i]) : (i * res[i]) + max(memo[i-2] , memo[i-3]);\n\n        // return max of last 2 elements\n        return max(memo[10000] , memo[9999]);\n    }\n};"
    },
    {
        "title": "Count All Valid Pickup and Delivery Options",
        "algo_input": "Given n orders, each order consist in pickup and delivery services.&nbsp;\n\nCount all valid pickup/delivery possible sequences such that delivery(i) is always after of&nbsp;pickup(i).&nbsp;\n\nSince the answer&nbsp;may be too large,&nbsp;return it modulo&nbsp;10^9 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 1\nExplanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 6\nExplanation: All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n\n\nExample 3:\n\nInput: n = 3\nOutput: 90\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 500\n\n",
        "solution_py": "class Solution:\n    def countOrders(self, n: int) -> int:\n        total = 1\n        mod = 10 ** 9 + 7\n        for k in reversed(range(2, n + 1)):\n            total = total * ((2 * k - 1) * (2 * k - 2) // 2 + 2 * k - 1)\n            total = total % mod\n        return total",
        "solution_js": "var countOrders = function(n) {\n    let ans = 1; //for n=1, there will only be one valid pickup and delivery\n    for(let i = 2; i<=n; i++){\n        let validSlots = 2 * i -1; //calculating number of valid slots of new pickup in (n-1)th order\n        validSlots =  (validSlots * (validSlots+1))/2; \n        ans = (ans * validSlots)%1000000007; //multiplying the ans of (n-1)th order to current order's valid slots\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int countOrders(int n) {\n        long res = 1;\n        long mod = 1000000007;\n        for (int i = 1; i <= n; i++) {\n            res = res * (2 * i - 1) * i % mod;\n        }\n        return (int)res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countOrders(int n) {\n        int mod = 1e9+7;\n        long long ans = 1;\n        for(int i=1;i<=n;i++){\n            int m = 2*i-1;\n            int p = (m*(m+1))/2;\n            ans=(ans*p)%mod;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Split a String Into the Max Number of Unique Substrings",
        "algo_input": "Given a string&nbsp;s,&nbsp;return the maximum&nbsp;number of unique substrings that the given string can be split into.\n\nYou can split string&nbsp;s into any list of&nbsp;non-empty substrings, where the concatenation of the substrings forms the original string.&nbsp;However, you must split the substrings such that all of them are unique.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ababccc\"\nOutput: 5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: 2\nExplanation: One way to split maximally is ['a', 'ba'].\n\n\nExample 3:\n\nInput: s = \"aa\"\nOutput: 1\nExplanation: It is impossible to split the string any further.\n\n\n&nbsp;\nConstraints:\n\n\n\t\n\t1 &lt;= s.length&nbsp;&lt;= 16\n\t\n\t\n\ts contains&nbsp;only lower case English letters.\n\t\n\n",
        "solution_py": "class Solution:\n    def maxUniqueSplit(self, s: str) -> int:\n        ans, n = 0, len(s)\n        def dfs(i, cnt, visited):\n            nonlocal ans, n\n            if i == n: ans = max(ans, cnt); return  # stop condition\n            for j in range(i+1, n+1):    \n                if s[i:j] in visited: continue      # avoid re-visit/duplicates\n                visited.add(s[i:j])                 # update visited set\n                dfs(j, cnt+1, visited)              # backtracking\n                visited.remove(s[i:j])              # recover visited set for next possibility\n        dfs(0, 0, set())                            # function call\n        return ans",
        "solution_js": "var maxUniqueSplit = function(s) {\n    let wordSet = new Set(), res = 1;\n    \n    function checkUniqueSubstring(i) {\n        if (i === s.length) {\n            res = Math.max(wordSet.size, res);\n            return;\n        }\n        \n        for (let j = i+1; j <= s.length; j++) {\n            let str = s.substring(i,j);\n            if (!wordSet.has(str)) {\n                wordSet.add(str);\n                checkUniqueSubstring(j);\n                wordSet.delete(str);\n            }\n        }\n    }\n    \n    checkUniqueSubstring(0);\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    int max = 0;\n    public int maxUniqueSplit(String s) {\n        int n = s.length();\n        backtrack(s, 0, new HashSet<String>());\n        return max;\n    }\n    public void backtrack(String s, int start, Set<String> h) {\n        if(start == s.length()) {\n            max = Math.max(max, h.size());\n        }\n        String res = \"\";\n        \n        for(int i = start;i < s.length();i++) {\n            res += s.charAt(i);\n            if(h.contains(res)) continue;\n            h.add(res);\n            backtrack(s, i+1, h);\n            h.remove(res);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    unordered_set<string>st;\n    int ans=0;\n    void dfs(string &s, int idx)\n    {\n        if(st.size()>ans) ans=st.size();\n        if(idx>=s.length()) return;\n        string str=\"\";\n        for(int i=idx ; i<s.length() ; i++)\n        {\n            str += s[i];\n            if(st.find(str)==st.end())\n            {\n                st.insert(str);\n                dfs(s,i+1);\n                st.erase(str);\n            }\n        }\n    }\n    \n    int maxUniqueSplit(string s) {\n        dfs(s,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Insert into a Binary Search Tree",
        "algo_input": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.\n\nNotice&nbsp;that there may exist&nbsp;multiple valid ways for the&nbsp;insertion, as long as the tree remains a BST after insertion. You can return any of them.\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,7,1,3], val = 5\nOutput: [4,2,7,1,3,5]\nExplanation: Another accepted tree is:\n\n\n\nExample 2:\n\nInput: root = [40,20,60,10,30,50,70], val = 25\nOutput: [40,20,60,10,30,50,70,null,null,25]\n\n\nExample 3:\n\nInput: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput: [4,2,7,1,3,5]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in&nbsp;the tree will be in the range [0,&nbsp;104].\n\t-108 &lt;= Node.val &lt;= 108\n\tAll the values Node.val are unique.\n\t-108 &lt;= val &lt;= 108\n\tIt's guaranteed that val does not exist in the original BST.\n\n",
        "solution_py": "class Solution:\n    def insertIntoBST(self, root, val):\n        if not root:\n            return TreeNode(val)\n      \n        if val<root.val:\n            root.left = self.insertIntoBST(root.left, val)\n        else:\n            root.right = self.insertIntoBST(root.right, val)\n  \n        return root",
        "solution_js": "var insertIntoBST = function(root, val) {\n    \n    if (root == null) {\n        return new TreeNode(val);\n    }\n    \n    if(val < root.val) {\n        root.left = insertIntoBST(root.left, val);\n    } else {\n        root.right = insertIntoBST(root.right, val);\n    }\n    \n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode insertIntoBST(TreeNode root, int val) {\n        if(root == null) return new TreeNode(val);\n      \n     if(root.val > val) root.left = insertIntoBST(root.left, val);\n      \n      else root.right = insertIntoBST(root.right, val);\n      \n      return root;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* insertIntoBST(TreeNode* root, int val) {\n        if(root==NULL) return new TreeNode(val);\n        TreeNode* node = root;\n        while(true){\n            if(val>=node->val){\n                if(node->right) node = node->right;\n                else{\n                    node->right = new TreeNode(val);\n                    break;\n                }\n            }\n            else{\n                if(node->left) node = node->left;\n                else{\n                    node->left = new TreeNode(val);\n                    break;\n                }\n            }\n        }\n        return root;\n    }\n};"
    },
    {
        "title": "Coloring A Border",
        "algo_input": "You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.\n\nTwo squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.\n\nThe border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).\n\nYou should color the border of the connected component that contains the square grid[row][col] with color.\n\nReturn the final grid.\n\n&nbsp;\nExample 1:\nInput: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput: [[3,3],[3,2]]\nExample 2:\nInput: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput: [[1,3,3],[2,3,3]]\nExample 3:\nInput: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput: [[2,2,2],[2,1,2],[2,2,2]]\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 50\n\t1 &lt;= grid[i][j], color &lt;= 1000\n\t0 &lt;= row &lt; m\n\t0 &lt;= col &lt; n\n\n",
        "solution_py": "class Solution:\n    def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n\n        rows, cols = len(grid), len(grid[0])\n        border_color = grid[row][col]\n        border = []\n\n        # Check if a node is a border node or not\n        def is_border(r, c):\n            if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n                return True\n\n            for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n                nr, nc = r + dr, c + dc\n                if grid[nr][nc] != border_color:\n                    return True\n            return False\n\n        def dfs(r, c):\n            if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color:\n                return\n            visited.add((r, c))\n\n            if is_border(r, c):\n                border.append((r, c))\n\n            dfs(r + 1, c)\n            dfs(r - 1, c)\n            dfs(r, c + 1)\n            dfs(r, c - 1)\n\n        visited = set()\n        dfs(row, col)\n        for r, c in border:\n            grid[r][c] = color\n        return grid",
        "solution_js": "var colorBorder = function(grid, row, col, color) {\n    const m = grid.length;\n    const n = grid[0].length;\n    const dirs = [-1, 0, 1, 0, -1];\n\n    const res = [];\n\n    for (let i = 0; i < m; i++) {\n        res[i] = new Array(n).fill(-1);\n    }\n\n    const val = grid[row][col];\n\n    const stack = [];\n    const visited = new Set();\n\n    visited.add(`${row}#${col}`); \n    stack.push([row, col]);\n\n    while (stack.length > 0) {\n        const [currRow, currCol] = stack.pop();\n\n        let isConnected = true;\n\n        for (let i = 0; i < dirs.length - 1; i++) {\n            const neiRow = currRow + dirs[i];\n            const neiCol = currCol + dirs[i + 1];\n\n            if (withinBound(neiRow, neiCol)) {\n                if (!visited.has(`${neiRow}#${neiCol}`)) {\n                    if (grid[neiRow][neiCol] === val) {\n                        visited.add(`${neiRow}#${neiCol}`);\n                        stack.push([neiRow, neiCol]);\n                    }\n                    else {\n                        isConnected = false;\n                    }\n                }\n            }\n        }\n\n        if (isBorder(currRow, currCol) || !isConnected) res[currRow][currCol] = color;\n    }\n\n    for (let i = 0; i < m; i++) {\n        for (let j = 0; j < n; j++) {\n            if (res[i][j] === -1) {\n                res[i][j] = grid[i][j];\n            }\n        }\n    }\n\n    return res;\n\n\n    function withinBound(row, col) {\n        return row >= 0 && col >= 0 && row < m && col < n;\n    }\n\n    function isBorder(row, col) {\n        return row === 0 || col === 0 || row === m - 1 || col === n - 1;\n    }\n};",
        "solution_java": "class Solution {\n    public int[][] colorBorder(int[][] grid, int row, int col, int color) {\n    dfs(grid,row,col,grid[row][col]);\n        for(int i = 0;i<grid.length;i++)\n        {\n            for(int j = 0;j<grid[0].length;j++)\n            {\n               if(grid[i][j]<0)\n               {\n                   grid[i][j] = color;\n               }\n            }\n        }\n     \n        \n        return grid;\n    }\n    int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};\n      public void dfs(int[][] grid, int row, int col, int color) {\n        grid[row][col] = - color;\n          int count = 0;\n         for(int i = 0;i<4;i++)\n         {\n             int rowdash = row+dirs[i][0];\n             int coldash = col+dirs[i][1];\n             \n             if(rowdash<0||coldash<0||rowdash>=grid.length||coldash>=grid[0].length||\n               Math.abs(grid[rowdash][coldash])!=color)\n             {\n                 continue;\n             }\n             count++;\n             \n             if(grid[rowdash][coldash]==color)\n             {\n                 dfs(grid,rowdash,coldash,color);\n             }\n     \n         }\n          if(count==4)\n          {\n              grid[row][col] = color;\n          }\n      \n    }\n}",
        "solution_c": "// marking element -ve and then fix it while backtracking worked as visited matrix\n// marking element 1e9 and not fixing it while backtracking works for coloring element\nclass Solution {\nprivate:\n    int m,n;\npublic:\n    bool is_valid(int i,int j,vector<vector<int>> &grid,int org_color){\n        return i >= 0 and j >= 0 and i < m and j < n and grid[i][j] == org_color and grid[i][j] > 0;\n    }\n\n    bool is_colorable(int i,int j,vector<vector<int>> &grid,int org_color){\n        if(i == 0 or j == 0 or i == m-1 or j == n-1) return true; // boundary condn\n\n        // checking any of the neighbour is of opposite color or not\n        if(i-1 >= 0 and abs(grid[i-1][j]) != org_color and grid[i-1][j] != 1e9) return true;\n\n        if(i+1 < m and abs(grid[i+1][j]) != org_color and grid[i+1][j] != 1e9) return true;\n\n        if(j-1 >= 0 and abs(grid[i][j-1]) != org_color and grid[i][j-1] != 1e9) return true;\n\n        if(j+1 < n and abs(grid[i][j+1]) != org_color and grid[i][j+1] != 1e9) return true;\n\n        return false;\n    }\n\n    void dfs(int i,int j,vector<vector<int>> &grid,int org_color){\n        if(!is_valid(i,j,grid,org_color)) return;\n\n        if(is_colorable(i,j,grid,org_color)) grid[i][j] = 1e9;\n        else grid[i][j] = -grid[i][j];\n\n        dfs(i-1,j,grid,org_color); dfs(i+1,j,grid,org_color); // up and down\n        dfs(i,j-1,grid,org_color); dfs(i,j+1,grid,org_color); // left and right\n\n        if(grid[i][j] < 0) grid[i][j] = -grid[i][j];\n    }\n    vector<vector<int>> colorBorder(vector<vector<int>>& grid, int row, int col, int color){\n        m = grid.size(), n = grid[0].size();\n        dfs(row,col,grid,grid[row][col]);\n        for(auto &it : grid){\n            for(auto &i : it){\n                if(i == 1e9) i = color;\n            }\n        }\n        return grid;\n    }\n};"
    },
    {
        "title": "Perfect Rectangle",
        "algo_input": "Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).\n\nReturn true if all the rectangles together form an exact cover of a rectangular region.\n\n&nbsp;\nExample 1:\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\nOutput: true\nExplanation: All 5 rectangles together form an exact cover of a rectangular region.\n\n\nExample 2:\n\nInput: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\nOutput: false\nExplanation: Because there is a gap between the two rectangular regions.\n\n\nExample 3:\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\nOutput: false\nExplanation: Because two of the rectangles overlap with each other.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rectangles.length &lt;= 2 * 104\n\trectangles[i].length == 4\n\t-105 &lt;= xi, yi, ai, bi &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n        X1, Y1 = float('inf'), float('inf')\n        X2, Y2 = -float('inf'), -float('inf')\n\n        points = set()\n        actual_area = 0\n        for x1, y1, x2, y2 in rectangles:\n            # calculate the coords of the potential perfect rectangle\n            X1, Y1 = min(X1, x1), min(Y1, y1)\n            X2, Y2 = max(X2, x2), max(Y2, y2)\n            # add up to the actual_area, so we can check against to see if thers is any part overwritten.\n            actual_area += (x2 - x1) * (y2 - y1)\n            \n            # proving steps in https://labuladong.github.io/algo/4/32/131/\n            for p in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]:\n                if p in points: \n                    points.remove(p)\n                else:           \n                    points.add(p)\n\n        # check the area \n        expected_area = (X2 - X1) * (Y2 - Y1)\n        if actual_area != expected_area:\n            return False\n        \n        if len(points) != 4:       \n            return False\n\n        if (X1, Y1) not in points: \n            return False\n        if (X1, Y2) not in points: \n            return False\n        if (X2, Y1) not in points: \n            return False\n        if (X2, Y2) not in points: \n            return False\n\n        return True",
        "solution_js": "var isRectangleCover = function(R) {\n    // left to right, bottom to top (so sort on bottom first, then left)\n    R.sort(([left1, bottom1], [left2, bottom2]) => bottom1 - bottom2 || left1 - left2);\n\n    // Find all corners\n    let leftMost = Infinity,\n        bottomMost = Infinity,\n        rightMost = -Infinity,\n        topMost = -Infinity;\n    for (let [left, bottom, right, top] of R) {\n        leftMost = Math.min(leftMost, left);\n        bottomMost = Math.min(bottomMost, bottom);\n        rightMost = Math.max(rightMost, right);\n        topMost = Math.max(topMost, top);\n    }\n\n    // All calculations are with-respect-to large rectangle\n    let CH = new Array(rightMost - leftMost).fill(0);\n    for (let [left, bottom, right, top] of R) {\n        const baseHeight = bottom - bottomMost; // how high base is\n        const ceilHeight = top - bottomMost; // how high ceil is\n        for (let tempLeft = left; tempLeft < right; tempLeft++) {\n            if (CH[tempLeft - leftMost] != baseHeight)\n                return false; // > is a duplicate cell < is a gap/ missing cell/ hole\n            CH[tempLeft - leftMost] = ceilHeight;\n        }\n    }\n\n    const rectHeight = topMost - bottomMost;\n    for (let ceilHeight of CH) {\n        if (ceilHeight !== rectHeight)\n            return false;\n    }\n    return true;\n}",
        "solution_java": "class Solution {\n    // Rectangle x0,y0,x1,y1\n    public boolean isRectangleCover(int[][] rectangles) {\n        // Ordered by y0 first and x0 second\n        Arrays.sort(rectangles,(r1,r2)->{\n           if(r1[1]==r2[1]) return r1[0]-r2[0];\n            return r1[1]-r2[1];\n        });\n\n        // Layering rectangles with pq, ordered by y1 first and x0 second\n        PriorityQueue<int[]> pq = new PriorityQueue<>((r1,r2)->{\n            if(r1[3]==r2[3]) return r1[0]-r2[0];\n            return r1[3]-r2[3];\n        });\n\n        // Create first layer\n        pq.offer(rectangles[0]);\n        int i=1;\n        while(i<rectangles.length&&rectangles[i][1]==rectangles[i-1][1]){\n            if(rectangles[i][0]!=rectangles[i-1][2]) return false;\n            pq.offer(rectangles[i++]);\n        }\n\n        while(i<rectangles.length){\n            int[] curr = rectangles[i++];\n            int x=curr[0];\n            //matching current rectangle with rectangles in the lower layer\n            while(!pq.isEmpty()&&x<curr[2]){\n                int[] prev=pq.poll();\n                if(prev[3]!=curr[1]||prev[0]!=x) return false;\n                if(prev[2]>curr[2]){\n                    pq.offer(new int[]{curr[2], prev[1], prev[2], prev[3]});\n                    x=curr[2];\n                }else {\n                    x=prev[2];\n                }\n            }\n            if(x<curr[2]) return false;\n            pq.offer(curr);\n        }\n\n        int[] prev=pq.poll();\n        while(!pq.isEmpty()){\n            if(pq.poll()[3]!=prev[3]) return false;\n        }\n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\n public:\n  bool isRectangleCover(vector<vector<int>>& rectangles) {\n    SegmentTree<STMax> st(2e5 + 1);\n    sort(rectangles.begin(), rectangles.end(), [](auto& lhs, auto& rhs) -> bool {\n      if (lhs[1] != rhs[1]) return lhs[1] < rhs[1];\n      return lhs[0] < rhs[0];\n    });\n\n    int min_x = rectangles[0][0];\n    int min_y = rectangles[0][1];\n    int max_a = rectangles[0][2];\n    int max_b = rectangles[0][3];\n    long long sum = 1ll * (max_a - min_x) * (max_b - min_y);\n    st.update(min_x + 1e5 + 1, max_a + 1e5, max_b);\n    for (int i = 1; i < rectangles.size(); ++i) {\n      if (rectangles[i][0] < min_x) return false;\n      int max_height = st.query(rectangles[i][0] + 1e5 + 1, rectangles[i][2] + 1e5);\n      if (max_height > rectangles[i][1]) return false;\n      max_a = max(max_a, rectangles[i][2]);\n      max_b = max(max_b, rectangles[i][3]);\n      sum += 1ll * (rectangles[i][2] - rectangles[i][0]) * (rectangles[i][3] - rectangles[i][1]);\n      st.update(rectangles[i][0] + 1e5 + 1, rectangles[i][2] + 1e5, rectangles[i][3]);\n    }\n    return sum == 1ll * (max_a - min_x) * (max_b - min_y);\n  }\n};"
    },
    {
        "title": "Find First and Last Position of Element in Sorted Array",
        "algo_input": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.\n\nIf target is not found in the array, return [-1, -1].\n\nYou must&nbsp;write an algorithm with&nbsp;O(log n) runtime complexity.\n\n&nbsp;\nExample 1:\nInput: nums = [5,7,7,8,8,10], target = 8\nOutput: [3,4]\nExample 2:\nInput: nums = [5,7,7,8,8,10], target = 6\nOutput: [-1,-1]\nExample 3:\nInput: nums = [], target = 0\nOutput: [-1,-1]\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= nums.length &lt;= 105\n\t-109&nbsp;&lt;= nums[i]&nbsp;&lt;= 109\n\tnums is a non-decreasing array.\n\t-109&nbsp;&lt;= target&nbsp;&lt;= 109\n\n",
        "solution_py": "class Solution:\n    def searchRange(self, nums: List[int], target: int) -> List[int]:\n        # if target is not in nums list, we simply return [-1,-1]\n\t\tif target not in nums:\n            return [-1,-1]\n        \n\t\t# create an empty list\n        result = []\n\t\t# iterate nums for the first time, if we found nums[i] matches with target\n\t\t# append the index i to result, break the for loop\n\t\t# because we only care the first and last index of target in nums\n        for i in range(len(nums)):\n            if nums[i] == target:\n                result.append(i)\n                break\n        \n\t\t# loop through nums backward, if we found nums[j] matches target\n\t\t# append j to result and break the for loop\n        for j in range(len(nums)-1, -1, -1):\n            if nums[j] == target:\n                result.append(j)\n                break\n        \n        return result\n\t\t\n\t\t",
        "solution_js": "var searchRange = function(nums, target) {\n    if (nums.length === 1) return nums[0] === target ? [0, 0] : [-1, -1];\n    \n    const findFirstInstance = (left, right) => {\n        if (left === right) return left;\n        var pivot;\n        while (left < right) {\n            if (left === pivot) left += 1;\n            pivot = Math.floor((left + right) / 2);\n            if (nums[pivot] === target) {\n                if (nums[pivot - 1] !== target) return pivot;\n                return findFirstInstance(left, pivot - 1);\n            }\n            if (nums[pivot] > target) right = pivot;\n            else left = pivot;\n        }\n    }\n    const findLastInstance = (left, right) => {\n        if (left === right) return left;\n        var pivot;\n        while (left < right) {\n            if (left === pivot) left += 1;\n            pivot = Math.floor((left + right) / 2);\n            if (nums[pivot] === target) {\n                if (nums[pivot + 1] !== target) return pivot;\n                return findLastInstance(pivot + 1, right);\n            }\n            if (nums[pivot] > target) right = pivot;\n            else left = pivot;\n        }\n    }\n    \n    var left = 0,\n        right = nums.length - 1,\n        pivot;\n    \n    while (left < right) {\n        if (left === pivot) left += 1;\n        pivot = Math.floor((left + right) / 2);\n        if (nums[pivot] === target) {\n            var first = nums[pivot - 1] !== target ? pivot : findFirstInstance(left, pivot - 1);\n            var last = nums[pivot + 1] !== target ? pivot : findLastInstance(pivot + 1, right);\n            return [first, last];\n        }\n        if (nums[pivot] > target) right = pivot;\n        else left = pivot;\n    }\n    \n    return [-1, -1];\n};",
        "solution_java": "class Solution {\n    public int[] searchRange(int[] nums, int target) {\n        int[] ans={-1,-1}; \n        int start=search(nums,target,true);\n        int end=search(nums,target,false);\n        ans[0]=start;\n        ans[1]=end;\n        return ans;\n    }\n    int search(int[] nums ,int target,boolean findStart){\n        int ans=-1;\n        int start=0;\n        int end=nums.length-1;\n        while(start<=end){\n         int  mid=start+(end-start)/2;\n            if(target>nums[mid]){\n           start=mid+1;\n            }\n            else if(target<nums[mid]){\n                end=mid-1;\n            }\n            else{\n                ans=mid;\n                if(findStart){\n                    end=mid-1;\n                }\n                else{\n                    start=mid+1;\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int startEle(vector<int>& nums, int target,int l,int r)\n    {\n        while(l<=r)\n        {\n            int m = (l+r)/2;\n            if(nums[m]<target) l=m+1;\n            else if(nums[m]>target) r = m-1;\n            else\n            {\n                if(m==0)\n                    return m;\n                else if(nums[m-1]==target)\n                    r = m-1;\n                else\n                    return m;\n            }\n        }\n\n        return -1;\n    }\n\n     int lastEle(vector<int>& nums, int target,int l,int r)\n    {\n        while(l<=r)\n        {\n            int m = (l+r)/2;\n            if(nums[m]<target) l=m+1;\n            else if(nums[m]>target) r = m-1;\n            else\n            {\n                if(m==nums.size()-1)\n                    return m;\n                else if(nums[m+1]==target)\n                    l = m+1;\n                else\n                    return m;\n            }\n        }\n\n         return -1;\n    }\n    vector<int> searchRange(vector<int>& nums, int target) {\n\n        vector<int> binSearch;\n        int a = startEle(nums,target,0,nums.size()-1);\n        if(a==-1)\n        {\n             binSearch.push_back(-1);\n             binSearch.push_back(-1);\n            return binSearch;\n        }\n        else\n        {\n            binSearch.push_back(a);\n        }\n\n        int b = lastEle(nums,target,0,nums.size()-1);\n        binSearch.push_back(b);\n\n        return binSearch;\n\n    }\n};"
    },
    {
        "title": "Find and Replace Pattern",
        "algo_input": "Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.\n\nA word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.\n\nRecall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\nOutput: [\"mee\",\"aqq\"]\nExplanation: \"mee\" matches the pattern because there is a permutation {a -&gt; m, b -&gt; e, ...}. \n\"ccc\" does not match the pattern because {a -&gt; c, b -&gt; c, ...} is not a permutation, since a and b map to the same letter.\n\n\nExample 2:\n\nInput: words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput: [\"a\",\"b\",\"c\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pattern.length &lt;= 20\n\t1 &lt;= words.length &lt;= 50\n\twords[i].length == pattern.length\n\tpattern and words[i] are lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n        d={}\n        for i,v in enumerate(pattern):\n            if v in d:\n                d[v].append(i)\n            else:\n                d|={v:[i]}\n        #DICTIONARY CONTAINING LETTERS AND THEIR INDICES\n        ans=[]\n        for i in words:\n            e={}\n            for j,v in enumerate(i):\n                if v in e:\n                    e[v].append(j)\n                else:\n                    e|={v:[j]}\n        #DICTIONARY CONTAINING LETTERS OF INDICES OF CURRENT WORD\n            for u,v in zip(d.values(),e.values()):\n                #COMPARING EACH VALUE\n                if u!=v:\n                    break\n            #IF SUCCESSFUL APPEND TO ANS\n            else:ans.append(i)\n        return ans",
        "solution_js": "var findAndReplacePattern = function(words, pattern) {\n    var patt = patternarr(pattern)  // 010\n    return words.filter(e=>patternarr(e) == patt)\n};\n\nconst patternarr = function (str) {\n    var result = '';\n    \n    for(let i=0;i<str.length;i++) {\n\t//finding the first index \n        result += str.indexOf(str[i])\n    }\n    return result\n    \n}",
        "solution_java": "class Solution {\n    public List<String> findAndReplacePattern(String[] words, String pattern) {\n        List<String> result=new ArrayList<>();\n        for(String word:words) {\n            Map<Character,Character> map=new HashMap<>();\n            Set<Character> set=new HashSet<>();\n            int i=0;\n            for(;i<word.length();i++) {\n                char ch=pattern.charAt(i);\n                if(map.get(ch)==null) {\n                    if(set.contains(word.charAt(i))) break;\n                   map.put(ch, word.charAt(i));\n                    set.add(word.charAt(i));\n                }\n                else {\n                    char mc=map.get(ch);\n                    if(mc!=word.charAt(i)) break;\n                }\n            }\n            if(i==pattern.length()) result.add(word);\n        }\n        return result;\n    }\n}",
        "solution_c": "\t\t\t//😉If you Like the repository don't foget to star & fork the repository😉\nclass Solution {\npublic:\n    \n    vector<int> found_Pattern(string pattern)\n    {\n\t   // if string is empty return empty vector.\n        if(pattern.size() == 0)\n            return {};\n        \n        vector<int> v;\n\t\t\n\t\t// ind variable for keeping track of unique characters\n        int ind = 0;\n\t\t\n        unordered_map<char,int> mp;\n        for(int i = 0; i<pattern.size(); ++i)\n        {\n\t\t\t// if character not present in map, insert the char with an index,\n\t\t\t// increment index because for next unique character the index should be differnt.\n           if(mp.find(pattern[i]) == mp.end())\n           {\n               mp.insert({pattern[i],ind++});\n\t\t\t   // also  push the index to v(numeric  pattern vector)\n\t\t\t   // mp[pattern[i]] gives the key to that character, here key is ind(which we are giving to every unique character)\n               v.push_back(mp[pattern[i]]);\n           }\n            else\n            {\n\t\t\t\t// if char is already in map than push index mapped to that character into the vector\n                v.push_back(mp[pattern[i]]);\n            }\n        }\n\t\t// return numeric pattern\n        return v;\n    }\n    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {\n       \n\t\t// store numeric patten of Pattern string in v\n        vector<int> v = found_Pattern(pattern);\n        \n        int n = words.size();\n        vector<string> ans;\n        \n\t\t// iterating and comparing pattern of each word with v(numeric pattern of Pattern)\n        for(int i = 0; i<n; ++i)\n        {\n            vector<int> pattern_word = found_Pattern(words[i]);\n            \n\t\t\t// if matched add words[i] to answer vector\n            if(v == pattern_word)\n                ans.push_back(words[i]);\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Repeated Substring Pattern",
        "algo_input": "Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abab\"\nOutput: true\nExplanation: It is the substring \"ab\" twice.\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: false\n\n\nExample 3:\n\nInput: s = \"abcabcabcabc\"\nOutput: true\nExplanation: It is the substring \"abc\" four times or the substring \"abcabc\" twice.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def repeatedSubstringPattern(self, s: str) -> bool:\n        for i in range(1, len(s)//2+1):\n            if s[:i] * (len(s)//i) == s:\n                return True\n        return False",
        "solution_js": "var repeatedSubstringPattern = function(s) {\n    let repeatStr = s.repeat(2) //first duplicate the string with repeat function\n    let sliceStr = repeatStr.slice(1,-1) // slice string first and last string word\n    return sliceStr.includes(s) // now check if the main string(s) is included by sliced string\n}",
        "solution_java": "class Solution {\n\n  public boolean repeatedSubstringPattern(String s) {\n       String temp=\"\";\n        for(int i=0 ;i<s.length()/2 ;i++){\n            temp+=s.charAt(i);\n\n            if(s.length()%temp.length()==0) {\n                int times_repeat= s.length()/temp.length();\n                StringBuilder str = new StringBuilder();\n                for(int j=0 ;j<times_repeat ;j++){\n                    str.append(temp);\n                }\n                if(str.toString().equals(s)) return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    vector<int> get_kmp_table(const string &s) {\n        vector<int> table(s.size());\n        int i=0; int j=-1;\n        table[0] = -1;\n        while (i < s.size()) {\n            if (j == -1 || s[i] == s[j]) {\n                i++;\n                j++;\n                table[i] = j;\n            }\n            else {\n                j = table[j];\n            }\n        }\n        return table;\n    }\n    \n    bool validate_table(const vector<int>& table) {\n        int idx = table.size() - 1;\n        while (idx >= 0 && table[idx] > 0) {\n            idx--;\n        }\n        if (idx <= 0) return false;\n        int substr_len = idx;\n        if (table.size() % substr_len != 0) return false;\n        idx = idx + 1; // the first nonzero element in the string\n        while (idx < table.size()-1) {\n            if (table[idx] != table[idx+1]-1) return false;\n            idx++;\n        }\n        return true;\n    }\n    \n    bool repeatedSubstringPattern(string s) {\n        if (s.size() <= 1) return true;\n        \n        auto table1 = get_kmp_table(s);\n        string ss = s;\n        reverse(ss.begin(), ss.end());\n        auto table2 = get_kmp_table(ss);\n        \n        return (validate_table(table1) && validate_table(table2));\n        \n    }\n};"
    },
    {
        "title": "Reshape the Matrix",
        "algo_input": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.\n\nYou are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.\n\nThe reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.\n\nIf the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,2],[3,4]], r = 1, c = 4\nOutput: [[1,2,3,4]]\n\n\nExample 2:\n\nInput: mat = [[1,2],[3,4]], r = 2, c = 4\nOutput: [[1,2],[3,4]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 100\n\t-1000 &lt;= mat[i][j] &lt;= 1000\n\t1 &lt;= r, c &lt;= 300\n\n",
        "solution_py": "import numpy\nclass Solution:\n    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n        return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat",
        "solution_js": "var matrixReshape = function(mat, r, c) {\n  const origR = mat.length;\n  const origC = mat[0].length;\n  \n  if (r*c !== origR*origC) {\n    return mat;\n  }\n  \n  const flat = mat.flatMap(n => n);\n  \n  const output = [];\n  for (let i=0; i<flat.length; i++) {\n    if (i%c === 0) {\n      output.push([]);\n    }\n    \n    output[output.length-1].push(flat[i]);\n  };\n  return output;\n};",
        "solution_java": "class Solution {\n    public int[][] matrixReshape(int[][] mat, int r, int c) {\n\n        if (r * c != mat.length * mat[0].length) {\n            return mat;\n        }\n\n        int[][] ans = new int[r][c];\n\n        int i = 0;\n        int j = 0;\n\n        for(int k = 0; k < mat.length; k++) {\n            for(int l = 0; l < mat[0].length; l++) {\n                if (j == c) {\n                    i++;\n                    j = 0;\n                }\n                ans[i][j++] = mat[k][l];\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n        if(mat.size()* mat[0].size()!= r * c) {\n            return mat;\n        } \n        vector<vector<int>>v(r,vector<int>(c));\n        int k = 0;\n        int l = 0;\n\n        for(int i = 0; i < mat.size(); i++) {\n            for(int j = 0; j < mat[0].size(); j++) {\n                if(l == v[0].size()) {\n                    l = 0;\n                    k++;\n                }\n\n                v[k][l++] = mat[i][j];\n            }\n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Add Two Numbers II",
        "algo_input": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\n&nbsp;\nExample 1:\n\nInput: l1 = [7,2,4,3], l2 = [5,6,4]\nOutput: [7,8,0,7]\n\n\nExample 2:\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [8,0,7]\n\n\nExample 3:\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in each linked list is in the range [1, 100].\n\t0 &lt;= Node.val &lt;= 9\n\tIt is guaranteed that the list represents a number that does not have leading zeros.\n\n\n&nbsp;\nFollow up:&nbsp;Could you solve it without reversing the input lists?\n",
        "solution_py": "class Solution:\n    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n        def number(head):\n            ans = ''\n            while head:\n                ans+=str(head.val)\n                head = head.next\n            return int(ans) \n        temp = dummy = ListNode(0)\n        for i in str(number(l1) + number(l2)):\n            temp.next = ListNode(i)\n            temp = temp.next\n        return dummy.next\n      ",
        "solution_js": "var addTwoNumbers = function(l1, l2) {\n    const reverse = head =>{\n        let prev = null\n        let dummy = head\n\n        while(dummy){\n            let temp = dummy.next\n            dummy.next = prev\n            prev = dummy\n            dummy = temp\n        }\n        return prev\n    }\n\n    let head1 = reverse(l1)\n    let head2 = reverse(l2)\n\n    // add\n    let sum = new ListNode()\n    let p = sum\n    let carry = 0\n\n    while((head1 && head2) || carry){\n        let v1 = head1?head1.val:0\n        let v2 = head2?head2.val:0\n        let v = v1+v2+carry\n\n        if(v>=10) carry = 1\n        else carry = 0\n\n        let node = new ListNode(v%10)\n\n        sum.next = node\n        sum = sum.next\n        head1 = head1&&head1.next\n        head2 = head2&&head2.next\n\n    }\n    sum.next = head1||head2\n    return reverse(p.next)\n};",
        "solution_java": "class Solution {\n    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n        ListNode res=new ListNode(0);\n        ListNode curr=res;\n         l1=reverseLinkedList(l1);\n         l2=reverseLinkedList(l2);\n        int carry=0;\n        while(l1!=null||l2!=null||carry==1)\n        {\n            int sum=0;\n            if(l1!=null)\n            {\n                sum+=l1.val;\n                l1=l1.next;\n            }\n            if(l2!=null)\n            {\n                sum+=l2.val;\n                l2=l2.next;\n            }\n            sum+=carry;\n            carry = sum/10; \n            curr.next= new ListNode(sum % 10); \n            \n            curr = curr.next; \n        }\n        return reverseLinkedList(res.next);\n    }\n    public ListNode reverseLinkedList(ListNode head)\n    {\n        ListNode curr=head;\n        ListNode prev=null;\n        ListNode next;\n        while(curr!=null)\n        {\n            next=curr.next;\n            curr.next=prev;\n            prev=curr;\n            curr=next;\n        }\n        return prev;\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* reverse(ListNode* l1){\n        if(l1==NULL||l1->next==NULL){\n            return l1;\n        }\n        ListNode* ans=reverse(l1->next);\n        l1->next->next=l1;\n        l1->next=NULL;\n        return ans;\n    }\n    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n       ListNode* l11= reverse(l1);\n       ListNode* l22= reverse(l2);\n        ListNode* dummy=new ListNode(0);\n        ListNode* curr=dummy;\n        int carry=0;\n        int sum=0;\n        while(l11||l22||carry!=0){\n            int x=l11?l11->val:0;\n            int y=l22?l22->val:0;\n            sum=x+y+carry;\n            carry=sum/10;\n            curr->next=new ListNode(sum%10);\n            curr=curr->next;\n            l11=l11?l11->next:nullptr;\n            l22=l22?l22->next:nullptr;\n        }\n        dummy=dummy->next;\n       dummy=reverse(dummy);\n        return dummy;\n    }\n};"
    },
    {
        "title": "Flood Fill",
        "algo_input": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.\n\nYou are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].\n\nTo perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.\n\nReturn the modified image after performing the flood fill.\n\n&nbsp;\nExample 1:\n\nInput: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.\n\n\nExample 2:\n\nInput: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\nOutput: [[0,0,0],[0,0,0]]\nExplanation: The starting pixel is already colored 0, so no changes are made to the image.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == image.length\n\tn == image[i].length\n\t1 &lt;= m, n &lt;= 50\n\t0 &lt;= image[i][j], color &lt; 216\n\t0 &lt;= sr &lt; m\n\t0 &lt;= sc &lt; n\n\n",
        "solution_py": "class Solution:\n    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n        queue = deque()\n        rows = len(image)\n        cols = len(image[0])\n        \n        targetColor = image[sr][sc]\n        \n        if color == targetColor:\n\t\t    # in this case, we don't need to do anything\n            return image\n\n        rDirs = [1, 0, -1, 0]\n        cDirs = [0, 1, 0, -1]\n        \n        queue.append((sr, sc))\n        \n        while len(queue) > 0:\n            r, c = queue.pop()\n            \n            image[r][c] = color\n            for rd, cd in zip(rDirs, cDirs):\n                newRow = r + rd\n                newCol = c + cd\n                \n                isValidCoordinate = newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols\n                \n                if isValidCoordinate and image[newRow][newCol] == targetColor:\n                    queue.append((newRow, newCol))\n        \n        return image\n            \n    ",
        "solution_js": "/**\n * @param {number[][]} image\n * @param {number} sr\n * @param {number} sc\n * @param {number} color\n * @return {number[][]}\n */\nvar floodFill = function(image, sr, sc, color) {\n    const pixelsToCheck = [[sr, sc]]\n    const startingPixelColor = image[sr][sc]\n    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n    const seenPixels = new Set()\n\n    if (\n        startingPixelColor === undefined ||\n        startingPixelColor === color\n    ) return image\n\n    for (const pixel of pixelsToCheck) {\n        const currentPixelColor = image[pixel[0]]?.[pixel[1]]\n\n        if (\n            currentPixelColor === undefined ||\n            startingPixelColor !== currentPixelColor\n        ) continue\n\n        image[pixel[0]][pixel[1]] = color\n\n        for (const direction of directions) {\n            const newPixel = [pixel[0] + direction[0], pixel[1] + direction[1]]\n            const pixelString = newPixel.join()\n\n            if (seenPixels.has(pixelString)) continue\n\n            pixelsToCheck.push(newPixel)\n            seenPixels.add(pixelString)\n        }\n    }\n\n    return image\n};",
        "solution_java": "class Solution {\n    void colorFill(int[][]image,int sr,int sc,int sourceColor,int targetColor){\n        int m = image.length, n = image[0].length;\n\n        if(sr>=0 && sr<m && sc>=0 && sc<n)\n        {\n            if( (image[sr][sc] != sourceColor) ||(image[sr][sc] == targetColor)) return;\n\n        image[sr][sc] = targetColor;\n        colorFill(image,sr,sc-1,sourceColor,targetColor); // left\n        colorFill(image,sr,sc+1,sourceColor,targetColor); // right\n        colorFill(image,sr-1,sc,sourceColor,targetColor); // up\n        colorFill(image,sr+1,sc,sourceColor,targetColor); // down\n        }\n       else\n           return;\n    }\n    public int[][] floodFill(int[][] image, int sr, int sc, int color) {\n        int rows = image.length, cols = image[0].length;\n\n        colorFill(image,sr,sc,image[sr][sc],color);\n    return image;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> paths = {{0,1},{0,-1},{-1,0},{1,0}};\n    bool check(int i,int j , int n, int m){\n        if(i>=n or i<0 or j>=m or j<0) return false;\n        return true;\n    }\n    void solve(vector<vector<int>> &image, int sr, int sc, int color, int orig){\n        int n = image.size(), m = image[0].size();\n        image[sr][sc] = color;\n        for(int i=0;i<4;i++){\n            int new_sr = paths[i][0] + sr;\n            int new_sc = paths[i][1] + sc;\n            if(check(new_sr,new_sc,n,m)==true and image[new_sr][new_sc]==orig){\n                solve(image, new_sr, new_sc, color,orig);\n            }\n        }\n\n    }\n    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {\n        if(color==image[sr][sc]) return image;\n        int orig = image[sr][sc];\n        solve(image, sr,sc,color, orig);\n        return image;\n    }\n};"
    },
    {
        "title": "Valid Sudoku",
        "algo_input": "Determine if a&nbsp;9 x 9 Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;according to the following rules:\n\n\n\tEach row&nbsp;must contain the&nbsp;digits&nbsp;1-9 without repetition.\n\tEach column must contain the digits&nbsp;1-9&nbsp;without repetition.\n\tEach of the nine&nbsp;3 x 3 sub-boxes of the grid must contain the digits&nbsp;1-9&nbsp;without repetition.\n\n\nNote:\n\n\n\tA Sudoku board (partially filled) could be valid but is not necessarily solvable.\n\tOnly the filled cells need to be validated according to the mentioned&nbsp;rules.\n\n\n&nbsp;\nExample 1:\n\nInput: board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput: true\n\n\nExample 2:\n\nInput: board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput: false\nExplanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == 9\n\tboard[i].length == 9\n\tboard[i][j] is a digit 1-9 or '.'.\n\n",
        "solution_py": "class Solution:\n    def isValidSudoku(self, board: List[List[str]]) -> bool:\n\n        hrow = {}\n        hcol = {}\n        hbox = defaultdict(list)\n\n        #CHECK FOR DUPLICATES ROWWISE\n        for i in range(9):\n            for j in range(9):\n\n                #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n                if board[i][j] != '.':\n\n                    if board[i][j] not in hrow:\n                        hrow[board[i][j]] = 1\n\n                    else:\n                        return False\n\n            #CLEAR HASHMAP FOR THIS ROW\n            hrow.clear()\n        print(\"TRUE1\")\n        #CHECK FOR DUPLICATES COLUMNWISE\n\n        for i in range(9):\n            for j in range(9):\n\n                #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n                if board[j][i] != '.':\n\n                    if board[j][i] not in hcol:\n                        hcol[board[j][i]] = 1\n\n                    else:\n                        return False\n\n        #CLEAR HASHMAP FOR THIS COL\n\n            hcol.clear()\n\n        print('TRUE2')\n\n        #CHECK DUPLICATE IN BOX, THIS IS WHERE KEY DESIGN SKILLS COME INTO PLAY, FOR SUDOKU YOU COMBINE ROW INDICES AND COL INDICES\n\n        for i in range(9):\n            for j in range(9):\n\n                i_3 = i //3\n                j_3 = j//3\n\n                # print(hbox)\n                if board[i][j] != '.':\n\n                #CHECK ELEMENT OF ORIGINAL INDICE present in key i_3 , j_3\n                    if board[i][j] not in hbox[i_3 , j_3]:\n# #CHECKED IN NEW KEY\n                        hbox[i_3 ,j_3 ]= hbox[i_3 ,j_3 ] + [board[i][j]]\n\n                    else:\n                        return False\n\n        return True",
        "solution_js": "/**\n * @param {character[][]} board\n * @return {boolean}\n */\nvar isValidSudoku = function(board) {\n    let rowMap = new Map();\n    let colMap = new Map();\n    let square = new Map();\n    for(let i=0; i<board.length; i++) {\n        for(let j=0; j<board[0].length; j++) {\n            if(board[i][j] === '.') continue;\n            if(!rowMap.has(i)) rowMap.set(i, new Set());\n            if(!colMap.has(j)) colMap.set(j, new Set());\n            let squareKey = Math.floor(i/3) + '#' + Math.floor(j/3);\n            if(!square.has(squareKey)) square.set(squareKey, new Set());\n            let rowSet = rowMap.get(i);\n            let colSet = colMap.get(j);\n            let squareSet = square.get(squareKey);\n            if(rowSet.has(board[i][j]) || colSet.has(board[i][j]) || squareSet.has(board[i][j])) return false;\n            rowSet.add(board[i][j]);\n            colSet.add(board[i][j]);\n            squareSet.add(board[i][j]);\n            rowMap.set(i, rowSet);\n            colMap.set(j, colSet);\n            square.set(squareKey, squareSet);\n        }\n    }\n    return true;\n};",
        "solution_java": "    for(int i=0; i<9; i++){\n         for(int j=0; j<9; j++){\n          if(board[i][j] != '.'){ \n              char currentVal = board[i][j];\n               if(!(seen.add(currentVal + \"found in row \"+ i)) ||\n                  !(seen.add(currentVal + \"found in column \"+ j) ) ||\n                  !(seen.add(currentVal + \"found in sub box \"+ i/3 + \"-\"+ j/3)))\n                   return false;\n          }\n      \n       } \n    \n    }\n    return true;\n}",
        "solution_c": "class Solution {\npublic:\n    bool isValidSudoku(vector<vector<char>>& board) {\n        \n        int n = board.size();\n        \n        for(int i=0;i<n;i++){\n            unordered_map<char,int>m;\n            for(int j=0;j<board[i].size();j++){\n                if(board[i][j]=='.'){\n                    continue;\n                }\n                if(m.find(board[i][j])!=m.end()){\n                    return false;\n                }\n                else{\n                    m[board[i][j]]++;\n                }\n            }\n        }\n        \n        for(int i=0;i<n;i++){\n            unordered_map<char,int>m;\n            for(int j=0;j<n;j++){\n                \n                if(board[j][i]=='.'){\n                    continue;\n                }\n                \n                if(m.find(board[j][i])!=m.end()){\n                    return false;\n                }\n                else{\n                    m[board[j][i]]++;\n                }\n            }\n        }\n        \n        for(int i=0;i<n;i+=3){\n            for(int j=0;j<n;j+=3){\n                \n                unordered_map<char,int>m;\n                for(int k=i;k<=i+2;k++){\n                    for(int p=j;p<=j+2;p++){\n                        \n                        if(board[k][p]=='.'){\n                            continue;\n                        }\n                        \n                        if(m.find(board[k][p])!=m.end()){\n                            return false;\n                        }\n                        else{\n                            m[board[k][p]]++;\n                        }\n                    }\n                }\n            }\n        }\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Binary Search",
        "algo_input": "Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n&nbsp;\nExample 1:\n\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\n\nExample 2:\n\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-104 &lt; nums[i], target &lt; 104\n\tAll the integers in nums are unique.\n\tnums is sorted in ascending order.\n\n",
        "solution_py": "class Solution:\n    def search(self, nums: List[int], target: int) -> int:\n        left = 0\n        right = len(nums)-1\n        \n        while left<=right:\n            mid = (left+right)//2\n            if nums[mid]==target:\n                return mid\n            elif nums[mid]>target:\n                right = mid-1\n            else:\n                left = mid+1\n        \n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n    \n    let low=0;\n    let high=nums.length-1;\n    \n    if(target<nums[0] || target>nums[high]){\n        return -1;\n    }\n    \n    while(low<=high) {\n        \n        mid=Math.floor((low+high)/2);\n        \n        if (nums[mid]==target){\n            return mid;\n        }\n        else{\n            \n            if(target>nums[mid]){\n                low=mid+1;\n                \n            }\n            else{\n                high=mid-1;\n            }\n        }\n    }\n    \n    return -1;\n    \n};",
        "solution_java": "class Solution {\n    public int search(int[] nums, int target) {\n        int l = 0;\n        int r = nums.length - 1;\n        return binarySearch(nums, l, r, target);\n    }\n    \n    private int binarySearch(int[] nums, int l, int r, int target) {\n        if (l <= r) {\n            int mid = (r + l) / 2;\n        \n            if (nums[mid] == target) {\n                return mid;\n            } \n        \n            if (nums[mid] < target) {\n                return binarySearch(nums, mid + 1, r, target);\n            } else {\n                return binarySearch(nums, l, mid - 1, target);\n            }\n        } \n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int search(vector<int>& nums, int target) {\n        int n = nums.size();\n        int jump = 5;\n        int p = 0;\n        while (jump*5 < n) jump *= 5;\n        while (jump > 0) {\n            while (p+jump < n && nums[p+jump] <= target) p += jump;\n            jump /= 5;\n        }\n        return (p == n || nums[p]!= target) ? -1 : p;\n    }\n};"
    },
    {
        "title": "Design Circular Queue",
        "algo_input": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\".\n\nOne of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.\n\nImplementation the MyCircularQueue class:\n\n\n\tMyCircularQueue(k) Initializes the object with the size of the queue to be k.\n\tint Front() Gets the front item from the queue. If the queue is empty, return -1.\n\tint Rear() Gets the last item from the queue. If the queue is empty, return -1.\n\tboolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.\n\tboolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.\n\tboolean isEmpty() Checks whether the circular queue is empty or not.\n\tboolean isFull() Checks whether the circular queue is full or not.\n\n\nYou must solve the problem without using the built-in queue data structure in your programming language.&nbsp;\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 3, true, true, true, 4]\n\nExplanation\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear();     // return 3\nmyCircularQueue.isFull();   // return True\nmyCircularQueue.deQueue();  // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear();     // return 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 1000\n\t0 &lt;= value &lt;= 1000\n\tAt most 3000 calls will be made to&nbsp;enQueue, deQueue,&nbsp;Front,&nbsp;Rear,&nbsp;isEmpty, and&nbsp;isFull.\n\n",
        "solution_py": "class MyCircularQueue {\n\n    int head = -1;\n    int tail = -1;\n    int[] q;\n    int k;\n    \n    public MyCircularQueue(int k) {\n        q = new int[k];\n        this.k = k;\n    }\n    \n    public boolean enQueue(int value) {\n        if(head == -1 && tail == -1) {\n            // enqueue when the queue is empty\n            head = tail = 0;\n            q[tail] = value;    // enQueue done\n            return true;\n        }\n        if((tail == k-1 && head == 0) || tail+1 == head) {\n            // queue is full\n            return false;\n        }\n        tail++;\n        if(tail == k) // condition for circularity\n            tail = 0;\n        q[tail] = value;    // enQueue done\n        return true;\n    }\n    \n    public boolean deQueue() {\n        if(head == -1) {\n            // check if q is already empty\n            return false;\n        } \n        if(head == tail) {\n            // only 1 element is there and head,tail both points same index\n            head = tail = -1;   // deQueue done\n            return true;\n        }\n        head++;       // deQueue done\n        if(head == k) // condition for circularity\n            head = 0;\n        return true;\n    }\n    \n    public int Front() {\n        if(head == -1) \n            return -1;\n        return q[head];\n    }\n    \n    public int Rear() {\n        if(tail == -1) \n            return -1;\n        return q[tail];\n    }\n    \n    public boolean isEmpty() {\n        if(head == -1 && tail == -1) \n            return true;\n        return false;\n    }\n    \n    public boolean isFull() {\n        if(tail == k-1 || tail+1 == head) \n            return true;\n        return false;\n    }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */",
        "solution_js": "class MyCircularQueue {\n\n    int head = -1;\n    int tail = -1;\n    int[] q;\n    int k;\n    \n    public MyCircularQueue(int k) {\n        q = new int[k];\n        this.k = k;\n    }\n    \n    public boolean enQueue(int value) {\n        if(head == -1 && tail == -1) {\n            // enqueue when the queue is empty\n            head = tail = 0;\n            q[tail] = value;    // enQueue done\n            return true;\n        }\n        if((tail == k-1 && head == 0) || tail+1 == head) {\n            // queue is full\n            return false;\n        }\n        tail++;\n        if(tail == k) // condition for circularity\n            tail = 0;\n        q[tail] = value;    // enQueue done\n        return true;\n    }\n    \n    public boolean deQueue() {\n        if(head == -1) {\n            // check if q is already empty\n            return false;\n        } \n        if(head == tail) {\n            // only 1 element is there and head,tail both points same index\n            head = tail = -1;   // deQueue done\n            return true;\n        }\n        head++;       // deQueue done\n        if(head == k) // condition for circularity\n            head = 0;\n        return true;\n    }\n    \n    public int Front() {\n        if(head == -1) \n            return -1;\n        return q[head];\n    }\n    \n    public int Rear() {\n        if(tail == -1) \n            return -1;\n        return q[tail];\n    }\n    \n    public boolean isEmpty() {\n        if(head == -1 && tail == -1) \n            return true;\n        return false;\n    }\n    \n    public boolean isFull() {\n        if(tail == k-1 || tail+1 == head) \n            return true;\n        return false;\n    }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */",
        "solution_java": "class MyCircularQueue {\n\n    private int front;\n    private int rear;\n    private int[] arr;\n    private int cap;\n    \n    private int next(int i){ // to get next idx after i in circular queue\n        return (i+1)%cap;\n    }\n    private int prev(int i){ // to get prev idx before i in circular queue\n        return (i+cap-1)%cap;\n    }\n    \n\t// rest is as simple as implmenting a normal queue using array.\n    public MyCircularQueue(int k) {\n        arr = new int[k];\n        cap=k;\n        front=-1;\n        rear=-1;\n    }\n    \n    public boolean enQueue(int value) {\n        if(isFull())return false;\n        if(front==-1){\n            front=0;\n            rear=0;\n            arr[rear]=value;\n            return true;\n        }\n        rear = next(rear);\n        arr[rear]=value;\n        return true;\n    }\n    \n    public boolean deQueue() {\n        if(isEmpty())return false;\n        if(front==rear){\n            front=-1;\n            rear=-1;\n            return true;\n        }\n        front=next(front);\n        return true;\n    }\n    \n    public int Front() {\n        if(front==-1)return -1;\n        return arr[front];\n    }\n    \n    public int Rear() {\n        if(rear==-1)return -1;\n        return arr[rear];\n    }\n    \n    public boolean isEmpty() {\n        return front==-1;\n    }\n    \n    public boolean isFull() {\n        return front!=-1 && next(rear)==front;\n    }\n}",
        "solution_c": "class MyCircularQueue {\n\n    int head = -1;\n    int tail = -1;\n    int[] q;\n    int k;\n    \n    public MyCircularQueue(int k) {\n        q = new int[k];\n        this.k = k;\n    }\n    \n    public boolean enQueue(int value) {\n        if(head == -1 && tail == -1) {\n            // enqueue when the queue is empty\n            head = tail = 0;\n            q[tail] = value;    // enQueue done\n            return true;\n        }\n        if((tail == k-1 && head == 0) || tail+1 == head) {\n            // queue is full\n            return false;\n        }\n        tail++;\n        if(tail == k) // condition for circularity\n            tail = 0;\n        q[tail] = value;    // enQueue done\n        return true;\n    }\n    \n    public boolean deQueue() {\n        if(head == -1) {\n            // check if q is already empty\n            return false;\n        } \n        if(head == tail) {\n            // only 1 element is there and head,tail both points same index\n            head = tail = -1;   // deQueue done\n            return true;\n        }\n        head++;       // deQueue done\n        if(head == k) // condition for circularity\n            head = 0;\n        return true;\n    }\n    \n    public int Front() {\n        if(head == -1) \n            return -1;\n        return q[head];\n    }\n    \n    public int Rear() {\n        if(tail == -1) \n            return -1;\n        return q[tail];\n    }\n    \n    public boolean isEmpty() {\n        if(head == -1 && tail == -1) \n            return true;\n        return false;\n    }\n    \n    public boolean isFull() {\n        if(tail == k-1 || tail+1 == head) \n            return true;\n        return false;\n    }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */"
    },
    {
        "title": "Online Majority Element In Subarray",
        "algo_input": "Design a data structure that efficiently finds the majority element of a given subarray.\n\nThe majority element of a subarray is an element that occurs threshold times or more in the subarray.\n\nImplementing the MajorityChecker class:\n\n\n\tMajorityChecker(int[] arr) Initializes the instance of the class with the given array arr.\n\tint query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MajorityChecker\", \"query\", \"query\", \"query\"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]\nOutput\n[null, 1, -1, 2]\n\nExplanation\nMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 2 * 104\n\t1 &lt;= arr[i] &lt;= 2 * 104\n\t0 &lt;= left &lt;= right &lt; arr.length\n\tthreshold &lt;= right - left + 1\n\t2 * threshold &gt; right - left + 1\n\tAt most 104 calls will be made to query.\n\n",
        "solution_py": "MAX_N = 2*10**4\nMAX_BIT = MAX_N.bit_length()\nclass MajorityChecker:\n\n    def __init__(self, nums: List[int]):\n        n = len(nums)\n        self.bit_sum = [[0] * MAX_BIT for _ in range(n+1)]\n        for i in range(1, n+1):\n            for b in range(MAX_BIT):\n                self.bit_sum[i][b] = self.bit_sum[i-1][b] + ((nums[i-1] >> b) & 1)\n        self.num_idx = defaultdict(list)\n        for i in range(n):\n            self.num_idx[nums[i]].append(i)\n\n    def query(self, left: int, right: int, threshold: int) -> int:\n        num = 0\n        for b in range(MAX_BIT):\n            if self.bit_sum[right+1][b] - self.bit_sum[left][b] >= threshold:\n                num |= 1 << b\n        l = bisect.bisect_left(self.num_idx[num], left)\n        r = bisect.bisect_right(self.num_idx[num], right)\n        if r-l >= threshold:\n            return num\n        return -1",
        "solution_js": "var MajorityChecker = function(arr) {\n    this.arr = arr;\n};\n\nMajorityChecker.prototype.query = function(left, right, threshold) {\n    var candidate = 0\n    var count = 0\n    for (var i = left; i < right+1; i++) {\n        if (count == 0) {\n            candidate = this.arr[i];\n            count = 1;\n        }\n        else if (candidate == this.arr[i]) {\n            count += 1\n        }\n        else {\n            count -= 1\n        }\n    }\n    \n    count = 0\n    for (var i = left; i < right+1; i++) {\n        if (candidate == this.arr[i]) {\n            count += 1\n        }\n    }\n\n    if (count >= threshold) {\n        return candidate\n    }   \n    return -1\n};",
        "solution_java": "class MajorityChecker {\n    \n    private final int digits=15;\n    private int[][]presum;\n    private ArrayList<Integer>[]pos;\n    \n    public MajorityChecker(int[] arr) {\n        int len=arr.length;\n        presum=new int[len+1][digits];\n        pos=new ArrayList[20001];\n        \n        for(int i=0;i<len;i++){\n            int n=arr[i];\n            if(pos[n]==null)pos[n]=new ArrayList();\n            pos[n].add(i);\n            \n            for(int j=0;j<digits;j++){\n                presum[i+1][j]=presum[i][j]+(n&1);\n                n>>=1;\n            }\n        }\n    }\n    \n    public int query(int left, int right, int threshold) {\n        int ans=0;\n        for(int i=digits-1;i>=0;i--){\n            int cnt=presum[right+1][i]-presum[left][i];\n            int b=1;\n            if(cnt>=threshold)b=1;\n            else if(right-left+1-cnt>=threshold)b=0;\n            else return -1;\n            ans=(ans<<1)+b;\n        }\n        \n        // check\n        ArrayList<Integer>list=pos[ans];\n        if(list==null)return -1;\n        int L=floor(list,left-1);\n        int R=floor(list,right);\n        if(R-L>=threshold)return ans;\n        return -1;\n    }\n    \n    private int floor(ArrayList<Integer>list,int n){\n        int left=0, right=list.size()-1, mid;\n        while(left<=right){\n            mid=left+(right-left)/2;\n            int index=list.get(mid);\n            if(index==n)return mid;\n            else if(index<n)left=mid+1;\n            else right=mid-1;\n        }\n        return right;\n    }\n    \n}",
        "solution_c": "class MajorityChecker {\npublic:\n    MajorityChecker(vector<int>& arr) {\n        this->arr = arr;\n        map<int, int> cnt;\n        for (auto& v: arr) {\n            cnt[v]++;\n        }\n        val_idx = vector<int>(20001, -1);\n        for (auto it = cnt.begin(); it != cnt.end(); ++it) {\n            if (it->second >= 250) {\n                val_idx[it->first] = elems.size();\n                elems.push_back(it->first);\n            }\n        }\n        n = elems.size();\n        pre = vector<vector<int>>(n, vector<int>(arr.size(), 0));\n        if (val_idx[arr[0]] != -1)\n            pre[val_idx[arr[0]]][0]++;\n        for (int i = 1; i < arr.size(); ++i) {\n            for (int j = 0; j < n; ++j) {\n                pre[j][i] = pre[j][i-1];\n            }\n            if (val_idx[arr[i]] != -1)\n                pre[val_idx[arr[i]]][i]++;\n        }\n    }\n\n    int query(int left, int right, int threshold) {\n        int width = right - left + 1;\n        if (width < 500) {\n            map<int, int> cnt;\n            int most_frequent = 0;\n            int most_frequent_val;\n            while (left <= right) {\n                if (++cnt[arr[left++]] > most_frequent) {\n                    most_frequent = cnt[arr[left - 1]];\n                    most_frequent_val = arr[left - 1];\n                }\n                // early end condition, there are not enough elements left\n                if (right + most_frequent + 1 < threshold + left) return -1;\n            }\n            return most_frequent >= threshold ? most_frequent_val : -1;\n        }\n\n        for (int i = 0; i < n; ++i) {\n            if (pre[i][right] - (left - 1 >= 0 ? pre[i][left - 1] : 0) >= threshold) {\n                return elems[i];\n            }\n        }\n        return -1;\n    }\n\nprivate:\n    vector<int> arr;\n    vector<int> elems;\n    vector<int> val_idx;\n    int n;\n    vector<vector<int>> pre;\n};"
    },
    {
        "title": "Find And Replace in String",
        "algo_input": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.\n\nTo complete the ith replacement operation:\n\n\n\tCheck if the substring sources[i] occurs at index indices[i] in the original string s.\n\tIf it does not occur, do nothing.\n\tOtherwise if it does occur, replace that substring with targets[i].\n\n\nFor example, if s = \"abcd\", indices[i] = 0, sources[i] = \"ab\", and targets[i] = \"eee\", then the result of this replacement will be \"eeecd\".\n\nAll replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.\n\n\n\tFor example, a testcase with s = \"abc\", indices = [0, 1], and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap.\n\n\nReturn the resulting string after performing all replacement operations on s.\n\nA substring is a contiguous sequence of characters in a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput: \"eeebffff\"\nExplanation:\n\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".\n\n\nExample 2:\n\nInput: s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput: \"eeecd\"\nExplanation:\n\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\tk == indices.length == sources.length == targets.length\n\t1 &lt;= k &lt;= 100\n\t0 &lt;= indexes[i] &lt; s.length\n\t1 &lt;= sources[i].length, targets[i].length &lt;= 50\n\ts consists of only lowercase English letters.\n\tsources[i] and targets[i] consist of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n        \n        inputs = list(zip(indices,sources,targets))\n        inputs.sort(key = lambda x: x[0])\n        \n        offset = 0\n        for idx, src, tgt in inputs:\n            idx += offset\n            if s[idx:idx + len(src)] != src:\n                print('hi')\n                print(idx)\n                continue\n                \n            offset += len(tgt) - len(src)\n            s = s[:idx] + tgt + s[idx+len(src):]\n            \n        return s",
        "solution_js": "var findReplaceString = function(s, indices, sources, targets) {\n    let res = s.split(''); \n\n    for(let i=0; i<indices.length; i++) { \n        let index = indices[i]; \n        let str = sources[i]; \n        \n        if(s.slice(index, index + str.length) == str) {\n            res[index] = targets[i]; \n            for(let j = 1; j < str.length; j++) { \n                res[index+=1] = \"\"; \n            }\n        }\n    }\n\n    return res.join('');\n};",
        "solution_java": "class Solution {\n    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {\n        \n        HashMap<Integer, String> subst = new HashMap<>();\n        HashMap<Integer, String> tgt = new HashMap<>();\n        \n        for(int i = 0; i< indices.length; i++) {\n            subst.put(indices[i], sources[i]);\n            tgt.put(indices[i],targets[i]);\n        }\n        \n        Arrays.sort(indices);\n        \n        String res = \"\";\n        int count = 0;\n        int avail[] = new int[indices.length];\n        for(int i = 0; i< s.length(); i++) {\n            if(count < indices.length && i == indices[count] && s.indexOf(subst.get(indices[count]), indices[count]) == indices[count]){\n                res = res+\"\"+tgt.get(indices[count]);\n                i = i+ subst.get(indices[count]).length()-1;\n                count++;\n            } else {\n                if(count < indices.length && i == indices[count])\n                    count++;\n                res+= s.charAt(i);\n            }\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) {     \n        int baggage = 0;\n        int n = indices.size();\n        map<int, pair<string,string>> mp;\n        for(int i=0;i<n;++i)\n        {\n            mp[indices[i]]={sources[i], targets[i]};\n        }\n        for(auto it:mp)\n        {\n            string temp = s.substr(it.first+baggage, it.second.first.size());\n            if(temp ==  it.second.first)\n            {\n                s.erase(it.first+baggage,it.second.first.size());\n                s.insert(it.first+baggage, it.second.second);\n                baggage += it.second.second.size() - it.second.first.size();\n            }\n        }\n        return s;\n    }\n};"
    },
    {
        "title": "Find Palindrome With Fixed Length",
        "algo_input": "Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.\n\nA palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.\n\n&nbsp;\nExample 1:\n\nInput: queries = [1,2,3,4,5,90], intLength = 3\nOutput: [101,111,121,131,141,999]\nExplanation:\nThe first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90th palindrome of length 3 is 999.\n\n\nExample 2:\n\nInput: queries = [2,4,6], intLength = 4\nOutput: [1111,1331,1551]\nExplanation:\nThe first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= queries.length &lt;= 5 * 104\n\t1 &lt;= queries[i] &lt;= 109\n\t1 &lt;= intLength&nbsp;&lt;= 15\n\n",
        "solution_py": "class Solution:\n    def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n        ogLength = intLength\n        isOdd = intLength & 1\n        if isOdd:\n            intLength += 1\n        k = intLength // 2\n        k = 10 ** (k - 1)\n        op = []\n        for q in queries:\n            pal = str(k + q - 1)\n            if isOdd:\n                pal += pal[::-1][1:]\n            else:\n                pal += pal[::-1]\n            if len(pal) == ogLength:\n                op.append(int(pal))\n            else:\n                op.append(-1)\n        return op",
        "solution_js": "var kthPalindrome = function(queries, intLength) {\n    let output=[];\n    // 1. We use FIRST 2 digits to create palindromes: Math.floor((3+1)/2)=2\n    let digit=Math.floor((intLength+1)/2);\n\n    for(let i=0; i<queries.length; i++){\n        // 2A. Get Nth 2-digits numbers: 10*(2-1)-1+[5,98]=[14,107]\n        let helper=10**(digit-1)-1+queries[i];\n        // 2B. Digits checking: 107>=100, which is INVALID\n        if(helper>=10**digit){output.push(-1)}\n        else{\n            let m=intLength-digit;\n            // 3A. We still need m digits for REFLECTION: 14=>[\"1\",\"4\"]=>\"41\"\n            let add=helper.toString().substr(0, m).split(\"\").reverse().join(\"\");\n            // 3B. Multiply 10**m for reversed digits: 14=>1400=>1441\n            helper=helper*10**m+add*1;\n            output.push(helper);\n        }\n    }\n    return output; // [1441,-1]\n};",
        "solution_java": "class Solution {\n    public long[] kthPalindrome(int[] queries, int intLength) {\n        long[] res= new long[queries.length];\n        for(int i=0;i<queries.length;i++){\n            res[i]=nthPalindrome(queries[i],intLength);\n        }\n        return res;\n    }\n    public long nthPalindrome(int nth, int kdigit)\n    {\n    long temp = (kdigit & 1)!=0 ? (kdigit / 2) : (kdigit/2 - 1);\n    long palindrome = (long)Math.pow(10, temp);\n    palindrome += nth - 1;\n    long res1=palindrome;\n    if ((kdigit & 1)>0)\n        palindrome /= 10;\n    while (palindrome>0)\n    {\n        res1=res1*10+(palindrome % 10);\n        palindrome /= 10;\n    }\n    String g=\"\";\n    g+=res1;\n    if(g.length()!=kdigit)\n        return -1;\n    return res1;\n}\n}",
        "solution_c": "#define ll long long\nclass Solution {\npublic:\n    vector<long long> kthPalindrome(vector<int>& queries, int intLength) {\n        vector<ll> result;\n        ll start = intLength % 2 == 0 ? pow(10, intLength/2 - 1) : pow(10, intLength/2);\n        for(int q: queries) { \n            string s = to_string(start + q - 1);\n            string palindrome = s;\n            reverse(s.begin(), s.end());\n            if(intLength % 2 == 0) {\n                palindrome += s;\n            } else {\n                palindrome += s.substr(1, s.size() - 1);\n            }\n\t\t\t\n\t\t\t// len of palindrome should be intLength, otherwise -1\n            if (palindrome.size() == intLength)\n                result.push_back(stoll(palindrome));\n            else\n                result.push_back(-1);\n        }\n        \n        return result;\n    }\n};"
    },
    {
        "title": "Find Subsequence of Length K With the Largest Sum",
        "algo_input": "You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.\n\nReturn any such subsequence as an integer array of length k.\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,1,3,3], k = 2\nOutput: [3,3]\nExplanation:\nThe subsequence has the largest sum of 3 + 3 = 6.\n\nExample 2:\n\nInput: nums = [-1,-2,3,4], k = 3\nOutput: [-1,3,4]\nExplanation: \nThe subsequence has the largest sum of -1 + 3 + 4 = 6.\n\n\nExample 3:\n\nInput: nums = [3,4,3,3], k = 2\nOutput: [3,4]\nExplanation:\nThe subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t-105&nbsp;&lt;= nums[i] &lt;= 105\n\t1 &lt;= k &lt;= nums.length\n\n",
        "solution_py": "class Solution(object):\n    def maxSubsequence(self, nums, k):\n        ret, max_k = [], sorted(nums, reverse=True)[:k]\n        for num in nums:\n            if num in max_k:\n                ret.append(num)\n                max_k.remove(num)\n                if len(max_k) == 0:\n                    return ret",
        "solution_js": "var maxSubsequence = function(nums, k) {\n    return nums.map((v,i)=>[v,i]).sort((a,b)=>a[0]-b[0]).slice(-k).sort((a,b)=>a[1]-b[1]).map(x=>x[0]);\n};",
        "solution_java": "class Solution {\n    public int[] maxSubsequence(int[] nums, int k) {\n        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> b[0] - a[0]);\n        \n        for(int i=0; i<nums.length; i++)\n            pq.offer(new int[]{nums[i], i});\n        \n        List<int[]> l = new ArrayList<>();\n        \n        while(k-- != 0)\n            l.add(pq.poll());\n        \n        Collections.sort(l, (a,b) -> a[1] - b[1]);\n            \n        int[] res = new int[l.size()];\n        \n        int index = 0;\n        \n        for(int[] i: l)\n            res[index++] = i[0];\n        \n        return res;\n    }\n}",
        "solution_c": "// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(N)\nclass Solution {\npublic:\n    vector<int> maxSubsequence(vector<int>& A, int k) {\n        vector<int> id(A.size());\n        iota(begin(id), end(id), 0); // Index array 0, 1, 2, ...\n        sort(begin(id), end(id), [&](int a, int b) { return A[a] > A[b]; }); // Sort the indexes in descending order of their corresponding values in `A`\n        id.resize(k); // Only keep the first `k` indexes with the greatest `A` values\n        sort(begin(id), end(id)); // Sort indexes in ascending order\n        vector<int> ans;\n        for (int i : id) ans.push_back(A[i]);\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Operations to Make a Subsequence",
        "algo_input": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.\n\nIn one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.\n\nReturn the minimum number of operations needed to make target a subsequence of arr.\n\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n\n&nbsp;\nExample 1:\n\nInput: target = [5,1,3], arr = [9,4,2,3,4]\nOutput: 2\nExplanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.\n\n\nExample 2:\n\nInput: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target.length, arr.length &lt;= 105\n\t1 &lt;= target[i], arr[i] &lt;= 109\n\ttarget contains no duplicates.\n\n",
        "solution_py": "from bisect import bisect_left\nclass Solution:\n    def minOperations(self, target: List[int], arr: List[int]) -> int:\n        dt = {num: i for i, num in enumerate(target)}\n        stack = []\n        for num in arr:\n            if num not in dt: continue\n            i = bisect_left(stack, dt[num])\n            if i == len(stack):\n                stack.append(dt[num])\n            else:\n                stack[i] = dt[num]\n        return len(target) - len(stack)",
        "solution_js": "const minOperations = function (targets, arr) {\n  const map = {};\n  const n = targets.length;\n  const m = arr.length;\n  targets.forEach((target, i) => (map[target] = i));\n\n//map elements in arr to index found in targets array\n  const arrIs = arr.map(el => {\n    if (el in map) {\n      return map[el];\n    } else {\n      return -1;\n    }\n  });\n\n//create a LIS table dp whose length is the longest increasing subsequence\n  const dp = [];\n\n  for (let i = 0; i < m; i++) {\n    const curr = arrIs[i];\n    if (curr === -1) continue;\n    if (!dp.length || curr > dp[dp.length - 1]) {\n      dp.push(curr);\n    } else if (curr < dp[0]) {\n      dp[0] = curr;\n    } else {\n      let l = 0;\n      let r = dp.length;\n      while (l < r) {\n        const mid = Math.floor((l + r) / 2);\n        if (arrIs[i] <= dp[mid]) {\n          r = mid;\n        } else {\n          l = mid + 1;\n        }\n      }\n      dp[r] = curr;\n    }\n  }\n  return n-dp.length;\n};",
        "solution_java": "class Solution {\n    public int minOperations(int[] target, int[] arr) {\n        int n = target.length;\n        Map<Integer, Integer> map = new HashMap<>();\n\n        for(int i = 0; i < n; i++) {\n            map.put(target[i], i);\n        }\n\n        List<Integer> array = new ArrayList<>();\n\n        for(int i = 0; i < arr.length; i++) {\n            if(!map.containsKey(arr[i])) {\n                continue;\n            }\n\n            array.add(map.get(arr[i]));\n        }\n\n        int maxLen = 0;\n        int[] tails = new int[n + 1];\n\n        for(int i = 0; i < n; i++) {\n            tails[i] = -1;\n        }\n\n        for(int num: array) {\n            int index = findMinIndex(tails, maxLen, num);\n\n            if(tails[index] == -1) {\n                maxLen++;\n            }\n            tails[index] = num;\n        }\n\n        return n - maxLen;\n    }\n\n    public int findMinIndex(int[] tails, int n, int val) {\n        int low = 0;\n        int ans = n;\n        int high = n - 1;\n\n        while(low <= high) {\n            int mid = (high + low) / 2;\n\n            if(tails[mid] >= val) {\n                ans = mid;\n                high = mid - 1;\n            }\n            else {\n                low = mid + 1;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> ans;\n    \n    void bin(int lo, int hi, int num) {\n        if(lo == hi) {\n            ans[lo] = num;\n            return;\n        }\n        int mid = (lo + hi) / 2;\n        if(ans[mid] < num) bin(mid + 1, hi, num);\n        else bin(lo, mid, num);\n    }\n    \n    int minOperations(vector<int>& target, vector<int>& arr) {\n        unordered_map<int, int> idx;\n        for(int i = 0; i < target.size(); i++) {\n            idx[target[i]] = i;\n        }\n        \n        for(int i = 0; i < arr.size(); i++) {\n            if(idx.find(arr[i]) == idx.end()) continue;\n            int num = idx[arr[i]];\n            if(ans.size() == 0 || num > ans.back()) {\n                ans.push_back(num);\n            }\n            else {\n                bin(0, ans.size() - 1, num);\n            }\n        }\n        \n        return (target.size() - ans.size());\n    }\n};"
    },
    {
        "title": "Ugly Number",
        "algo_input": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\n\nGiven an integer n, return true if n is an ugly number.\n\n&nbsp;\nExample 1:\n\nInput: n = 6\nOutput: true\nExplanation: 6 = 2 × 3\n\n\nExample 2:\n\nInput: n = 1\nOutput: true\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n\n\nExample 3:\n\nInput: n = 14\nOutput: false\nExplanation: 14 is not ugly since it includes the prime factor 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t-231 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def isUgly(self, n: int) -> bool:\n        if n == 0:\n            return False\n        res=[2, 3, 5]\n        while n!= 1:\n            for i in res:\n               if n%i==0:\n                   n=n//i\n                   break\n            else:\n                return False\n        return True",
        "solution_js": "var isUgly = function(n) {\n    let condition = true;\n    if(n == 0) // 0 has infinite factors. So checking if the number is 0 or not\n        return false;\n    while(condition){ //applying for true until 2, 3, 5 gets removed from the number\n        if(n % 2 == 0)\n            n = n / 2;\n        else if(n % 3 == 0)\n            n = n / 3;\n        else if(n % 5 == 0)\n            n = n / 5;\n        else\n        condition = false; //if the number doesnt have 2, 3, 5 in it anymore, this part will execute and will end the while loop\n    }\n    return n == 1 ? true : false;//checking if the number only had 2, 3, 5 in it or had something else in it as well\n};",
        "solution_java": "class Solution {\n    public boolean isUgly(int n) {\n        if(n==0) return false; //edge case\n        while(n!=1){\n            if(n%2==0){\n               n=n/2;\n            }\n            else if(n%3==0){\n               n=n/3;\n            }\n            else if(n%5==0){\n               n=n/5;\n            }\n            else{\n                return false;\n            }\n        }\n        return true;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n   bool isUgly(int n)\n  {\n     if (n <= 0) return false;\n     int n1 = 0;\n     while(n != n1)\n     {\n     n1 = n;\n     if ((n % 2) == 0) n /= 2;\n     if ((n % 3) == 0) n /= 3;\n     if ((n % 5) == 0) n /= 5;\n     }\n     if (n < 7) return true;\n     return false;\n  }\n};"
    },
    {
        "title": "Word Pattern",
        "algo_input": "Given a pattern and a string s, find if s&nbsp;follows the same pattern.\n\nHere follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.\n\n&nbsp;\nExample 1:\n\nInput: pattern = \"abba\", s = \"dog cat cat dog\"\nOutput: true\n\n\nExample 2:\n\nInput: pattern = \"abba\", s = \"dog cat cat fish\"\nOutput: false\n\n\nExample 3:\n\nInput: pattern = \"aaaa\", s = \"dog cat cat dog\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pattern.length &lt;= 300\n\tpattern contains only lower-case English letters.\n\t1 &lt;= s.length &lt;= 3000\n\ts contains only lowercase English letters and spaces ' '.\n\ts does not contain any leading or trailing spaces.\n\tAll the words in s are separated by a single space.\n\n",
        "solution_py": "class Solution(object):\n    def wordPattern(self, pattern, s):\n        \"\"\"\n        :type pattern: str\n        :type s: str\n        :rtype: bool\n        \"\"\"\n        p, s = list(pattern), list(s.split(\" \"))\n\n        return len(s) == len(p) and len(set(zip(p, s))) == len(set(s)) == len(set(p))",
        "solution_js": "var wordPattern = function(pattern, s) {\n    let wordArray = s.split(\" \");\n    if(wordArray.length !== pattern.length) return false;\n\n    let hm = {};\n    let hs = new Set();\n\n    for(let index in pattern) {\n        let word = wordArray[index];\n        let char = pattern[index];\n\n        if(hm[char] !== undefined) {\n            if(hm[char] !== word) return false;\n        } else {\n            if(hs.has(word)) return false; // Duplicate Occurence of word on first occurrence of a char\n            hm[char] = word;\n            hs.add(word);\n        }\n    }\n\n    return true;\n}",
        "solution_java": "class Solution {\n    public boolean wordPattern(String pattern, String s) {\n        String[] arr=s.split(\" \");\n         if(pattern.length()!=arr.length) return false;\n        Map<Character,String> map=new HashMap<Character,String>();\n        \n        for(int i=0;i<pattern.length();i++){\n            char ch=pattern.charAt(i);\n            if(map.containsKey(ch)){\n                 if(!map.get(ch).equals(arr[i])){\n                    return false;\n                }    \n            }else if(!(map.containsKey(ch)|| map.containsValue(arr[i]))){\n               map.put(ch,arr[i]);\n            }else{\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    unordered_set<string> processed_words;\n    string m[26]; // char to string mapping\n\n    bool crunch_next_word(char c, string word)\n    {\n        int idx = c-'a';\n        if(m[idx].empty() && processed_words.count(word)==0)\n        {\n            m[idx] = word;\n            processed_words.insert(word);\n            return true;\n        }\n        else if(m[idx]==word) return true;\n        else return false;\n    }\n\n    bool wordPattern(string pattern, string s)\n    {\n        int count = 0;\n\n        int start = 0;\n        int end = s.find(' ');\n        while (end != -1)\n        {\n            string word = s.substr(start, end - start);\n            char c = pattern[count];\n            if(!crunch_next_word(c,word)) return false;\n\n            start = end + 1;\n            end = s.find(' ', start);\n            count++;\n            if(count == pattern.length()) return false;\n        }\n        if(count != pattern.length()-1) return false;\n        string word = s.substr(start, end - start);\n        char c = pattern[count];\n        if(!crunch_next_word(c,word)) return false;\n        return true;\n    }\n};"
    },
    {
        "title": "House Robber",
        "algo_input": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\nExample 2:\n\nInput: nums = [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 400\n\n",
        "solution_py": "class Solution:\n    def rob(self, nums: List[int]) -> int:\n        # [rob1,rob2,n,n+1]\n        # 1 | 2 | 3 | 1  \n   #index 0   1   2   3\n        # so upto last index it depends on previous 2 values :\n    # here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2\n    # and upto 1st index  max rob is 2 ; not choosing any adjacent elements\n    # so at 3rd index it depend on prev rob value and 1st index rob value+last value\n    # i.e max(2+(val at last index),4)\n        rob1=0;rob2=0;\n        for i in nums:\n            temp=max(rob1+i,rob2);\n            rob1=rob2;\n            rob2=temp;\n        return rob2;",
        "solution_js": "const max=(x,y)=>x>y?x:y\nvar rob = function(nums) {\n     if(nums.length==1) return(nums[0]);\n    let temp=[]\n    temp[0]=nums[0];\n        temp[1]=max(nums[0],nums[1]);\n\n        for(let i =2;i<nums.length;i++){\n            temp[i] = max(temp[i-1],nums[i]+temp[i-2]);\n        }\n        // console.log(temp)\n        return(temp[nums.length-1]);\n};",
        "solution_java": "class Solution {\n    public int rob(int[] nums) {\n        int[] t = new int[nums.length] ;\n        for(int i=0; i<t.length; i++){\n            t[i] =-1;\n        }\n       return helper(nums,0,t);\n    }\n    static int helper(int[] nums, int i,int[] t){\n        if(i>=nums.length){\n            return 0;\n        }\n        if(i==nums.length-1){\n            return nums[i];\n        }\n        if(t[i] != -1){\n            return t[i];\n        }\n\n        int pick = nums[i] + helper(nums,i+2,t);\n        int unpicked = helper(nums,i+1,t);\n        t[i] = Math.max(pick,unpicked);\n        return t[i];\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int helper(int i, vector<int>& nums) {\n        if(i == 0) return nums[i];\n        if(i < 0) return 0;\n\n        int pick = nums[i] + helper(i-2, nums);\n        int not_pick = 0 + helper(i-1, nums);\n\n        return max(pick,not_pick);\n    }\n    int rob(vector<int>& nums) {\n        return helper(nums.size()-1, nums);\n    }\n};"
    },
    {
        "title": "Integer to English Words",
        "algo_input": "Convert a non-negative integer num to its English words representation.\n\n&nbsp;\nExample 1:\n\nInput: num = 123\nOutput: \"One Hundred Twenty Three\"\n\n\nExample 2:\n\nInput: num = 12345\nOutput: \"Twelve Thousand Three Hundred Forty Five\"\n\n\nExample 3:\n\nInput: num = 1234567\nOutput: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def numberToWords(self, num: int) -> str:\n        \n        if num == 0:\n            return \"Zero\"\n        \n        dic1 = {1000000000: \"Billion\", 1000000: \"Million\", 1000: \"Thousand\", 1: \"\"}\n        dic2 = {90: \"Ninety\", 80: \"Eighty\", 70: \"Seventy\", 60: \"Sixty\", 50: \"Fifty\", 40: \"Forty\", 30: \"Thirty\", 20: \"Twenty\", 19: 'Nineteen', 18: \"Eighteen\", 17: \"Seventeen\", 16: \"Sixteen\", 15: \"Fifteen\", 14: \"Fourteen\", 13: \"Thirteen\", 12: \"Twelve\", 11: \"Eleven\", 10: \"Ten\", 9: \"Nine\", 8: \"Eight\", 7: \"Seven\", 6: \"Six\", 5: \"Five\", 4: \"Four\", 3: \"Three\", 2: \"Two\", 1: \"One\"}\n        \n        def construct_num(num):\n            ans = ''\n            d, num = divmod(num, 100)\n            if d > 0:\n                ans += dic2[d] + \" \" + \"Hundred\"\n            for k, v in dic2.items():\n                d, num = divmod(num, k)\n                if d > 0:\n                    ans += \" \" + v\n            return ans.lstrip()                               \n        \n        ans = \"\"\n        for k, v in dic1.items():\n            d, num = divmod(num, k)\n            if d > 0:\n                ans += \" \" + construct_num(d) + \" \" + v\n                \n        return ans.strip()",
        "solution_js": "let numberMap = {\n\t0: 'Zero',\n  100: 'Hundred',\n  1: 'One',\n  2: 'Two',\n  3: 'Three',\n  4: 'Four',\n  5: 'Five',\n  6: 'Six',\n  7: 'Seven',\n  8: 'Eight',\n  9: 'Nine',\n  10: 'Ten',\n  11: 'Eleven',\n  12: 'Twelve',\n  13: 'Thirteen',\n  14: 'Fourteen',\n  15: 'Fifteen',\n  16: 'Sixteen',\n  17: 'Seventeen',\n  18: 'Eighteen',\n  19: 'Nineteen',\n  20: 'Twenty',\n  30: 'Thirty',\n  40: 'Forty',\n  50: 'Fifty',\n  60: 'Sixty',\n  70: 'Seventy',\n  80: 'Eighty',\n  90: 'Ninety'\n};\n\nlet bigNumberMap = {\n\t1000000000: 'Billion',\n  1000000: 'Million',\n  1000: 'Thousand',\n  1: 'One'\n}\n\nlet bases = [];\n\nfor (let base in numberMap) {\n\tbases.push(parseInt(base, 10));\n}\nbases = bases.sort((a,b) => b-a);\n\nlet bigBases = [];\nfor (let base in bigNumberMap) {\n\tbigBases.push(parseInt(base, 10));\n}\nbigBases = bigBases.sort((a,b) => b-a);\n\nvar numberToWords = function(num) {\n    let res = '';\n    if (num === 0) return numberMap[num];\n   \tbigBases.forEach((base) => {\n    \tbase = parseInt(base, 10);\n      let baseAsString = base + '';\n      let nums = num/base << 0;\n      let remainder = num - nums * base;\n      if (nums >= 1) {\n    \t\t[res, nums] = getForHundredBase(res, nums);\n        res += baseAsString.length > 1 ? (' ' + bigNumberMap[base + '']) : '';\n        num = remainder;\n      }\n    });\n    return res;\n};\n\nfunction getForHundredBase(res, num) {\n\t\tbases.forEach((base) => {\n    \tbase = parseInt(base, 10);\n    \t[num, res] = getNums(num, base, res);\n    });\n    return [res, num];\n}\n\nfunction getNums(num, base, res) {\n\tlet nums = num / base << 0;\n  let baseAsString = base + '';\n  if (nums > 1 || (nums == 1 && baseAsString.length > 2)) {\n  \tres += res === '' ? res : \" \";\n  \tres += numberMap[nums] + \" \" + numberMap[baseAsString];\n  } else if (nums == 1) {\n  \tres += res === '' ? res : \" \";\n  \tres += numberMap[baseAsString];\n  }\n  return [num - (nums * base), res];\n}",
        "solution_java": "class Solution {\n    \n    private static final int[] INT_NUMBERS = {\n            1_000_000_000, 1_000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};\n    private static final String[] STRING_NUMBERS = {\n            \"Billion\", \"Million\", \"Thousand\", \"Hundred\", \"Ninety\", \"Eighty\", \"Seventy\", \"Sixty\", \"Fifty\", \"Forty\", \"Thirty\", \"Twenty\",\n            \"Nineteen\", \"Eighteen\", \"Seventeen\", \"Sixteen\", \"Fifteen\", \"Fourteen\", \"Thirteen\", \"Twelve\", \"Eleven\", \"Ten\",\n            \"Nine\", \"Eight\", \"Seven\", \"Six\", \"Five\", \"Four\", \"Three\", \"Two\", \"One\"};\n\n    public String numberToWords(int num) {\n        if (num == 0) return \"Zero\";\n        return numberToWordsHelper(num).toString();\n    }\n\n    private StringBuilder numberToWordsHelper(int num) {\n        StringBuilder sb = new StringBuilder();\n        if (num == 0) return sb;\n        for (int i = 0; i < INT_NUMBERS.length; i++) {\n            if (num >= INT_NUMBERS[i]) {\n                if (num >= 100) {\n                    sb.append(numberToWordsHelper(num / INT_NUMBERS[i]).append(\" \"));\n                }\n\n                sb.append(STRING_NUMBERS[i]).append(\" \").append(numberToWordsHelper(num % INT_NUMBERS[i]));\n                break;\n            }\n        }\n        return sb.charAt(sb.length() - 1) == ' ' ? sb.deleteCharAt(sb.length() - 1) : sb; // trim\n    }\n    \n}",
        "solution_c": "unordered_map<int, string> mp_0 = {{1, \"One \"},{2, \"Two \"},{3, \"Three \"},{4, \"Four \"},  {5, \"Five \"},{6, \"Six \"},{7, \"Seven \"},{8, \"Eight \"},{9, \"Nine \"}, {10, \"Ten \"},{11,\"Eleven \"},{12, \"Twelve \"},{13, \"Thirteen \"},{14, \"Fourteen \"},{15, \"Fifteen \"},{16, \"Sixteen \"},{17, \"Seventeen \"},{18, \"Eighteen \"},{19, \"Nineteen \"}};\n        \nunordered_map<int, string> mp_10 = {{20, \"Twenty \"},{30, \"Thirty \"},{40 , \"Forty \"},{50, \"Fifty \"},{60, \"Sixty \"},{70, \"Seventy \"},{80, \"Eighty \"},{90, \"Ninety \"}};\n\nclass Solution {\n    \n    void Solve2(string &ans , int num)\n    {\n       ans = mp_0[num] + ans;\n    }\n    \n    void Solve( string &ans, int num)\n    {\n        int factor = 1;\n        for(int i = 0 ; num>0 ; i++)\n        {\n            if(factor == 1)\n            {\n                \n                if(num%100 < 20)\n                {\n                    Solve2(ans, num%100);\n                    factor = factor*10;\n                    num = num/10;\n                }\n                else\n                {\n                if(num%10 !=0)\n                ans = mp_0[num%10] + ans;   \n                }\n            }\n            \n            else if(factor == 10)\n            {\n                if(num%10 != 0)\n                   ans = mp_10[(num%10)*10] + ans;   \n            }\n            \n            else if(factor == 100)\n            {\n                if(num%10 != 0)\n                    ans = (mp_0[num%10] + \"Hundred \") + ans;            \n            }\n            \n            factor = factor*10;\n            num = num/10;\n        }\n    }\npublic:\n    string numberToWords(int num) {\n        //2,147,483,647\n        \n        if(num == 0)\n            return \"Zero\";\n        \n        string ans ;\n        \n       \n        for(int i = 0 ; num>0 ; i++)\n        {   \n            if(i == 1)   \n           { \n             if(num%1000>0)\n             ans = \"Thousand \"+ ans;\n           }\n            else if(i == 2)\n           { \n             if(num%1000>0)\n             ans = \"Million \"+ ans;\n           }\n            else if( i == 3)\n             ans = \"Billion \"+ ans;\n            \n            Solve(ans, num%1000);\n            num = num/1000;\n          \n        }\n                ans.pop_back();\n        return ans;\n        \n        \n    }\n};"
    },
    {
        "title": "Calculate Money in Leetcode Bank",
        "algo_input": "Hercy wants to save money for his first car. He puts money in the Leetcode&nbsp;bank every day.\n\nHe starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. \n\nGiven n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: 10\nExplanation:&nbsp;After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\n\n\nExample 2:\n\nInput: n = 10\nOutput: 37\nExplanation:&nbsp;After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\n\n\nExample 3:\n\nInput: n = 20\nOutput: 96\nExplanation:&nbsp;After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "from itertools import cycle, \\\n                      repeat, \\\n                      starmap\nfrom operator import floordiv\n\n\nclass Solution:\n    def totalMoney(self, n: int) -> int:\n        return sum(starmap(add,zip(\n            starmap(floordiv, zip(range(n), repeat(7, n))),\n            cycle((1,2,3,4,5,6,7))\n        )))",
        "solution_js": "var totalMoney = function(n) {\n    let min = 1;\n    let days = 7;\n    let total = 0;\n    let inc = 1;\n    for (let i = 0; i < n; i++) {\n        if (days !== 0) {\n            total += min;\n            min++;\n            days--;\n        } else {\n            inc++;\n            min = inc\n            days = 7;\n            i--;\n        }\n    }\n    return total;\n};",
        "solution_java": "class Solution {\n    public int totalMoney(int n) {\n        int m=n/7; //(no.of full weeks)\n        // first week 1 2 3 4 5 6 7 (sum is 28 i.e. 7*(i+3) if i=1)\n        // second week 2 3 4 5 6 7 8 (sum is 35 i.e. 7*(i+3) if i=2)\n        //.... so on\n        int res=0; //for result\n        //calculating full weeks\n        for(int i=1;i<=m;i++){\n            res+=7*(i+3);\n        }\n        //calculating left days\n        for(int i=7*m;i<n;i++){\n            res+=++m;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int totalMoney(int n) {\n        int res = 0;\n        for (int i = 1, c = 1; i <= n; i++, c++) {\n            res += c;\n            c = i % 7 ? c : (i / 7);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Burst Balloons",
        "algo_input": "You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.\n\nIf you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.\n\nReturn the maximum coins you can collect by bursting the balloons wisely.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,1,5,8]\nOutput: 167\nExplanation:\nnums = [3,1,5,8] --&gt; [3,5,8] --&gt; [3,8] --&gt; [8] --&gt; []\ncoins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167\n\nExample 2:\n\nInput: nums = [1,5]\nOutput: 10\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 300\n\t0 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "from functools import cache\n\nclass Solution:\n    def maxCoins(self, nums: List[int]) -> int:\n        nums = [1] + nums + [1]\n        length = len(nums)\n        dp = [[None]*(length+1) for i in range(length+1)]\n        \n        @cache\n        def dfs(l,r):\n            if l>r: return 0\n            if dp[l][r] is not None: return dp[l][r]\n            dp[l][r] = 0\n            for i in range(l,r+1):\n                coins = dfs(l, i-1) + dfs(i+1, r) + nums[l-1]*nums[i]*nums[r+1]\n                dp[l][r] = max(dp[l][r], coins)\n            return dp[l][r]\n        return dfs(1, length-2)",
        "solution_js": "var rec = function(i,j,arr,dp){\n    if(i>j)return 0;\n    if(dp[i][j] !== -1)return dp[i][j];\n    let max = Number.MIN_VALUE;\n    for(let k=i;k<=j;k++){\n        let cost = arr[i-1] * arr[k] * arr[j+1] + rec(i,k-1,arr,dp)+rec(k+1,j,arr,dp);\n        if(cost>max){\n            max = cost\n        }\n    }\n    return dp[i][j] = max\n}\nvar maxCoins = function(nums) {\n    let n = nums.length;\n    let sol = [];\n    for(let i=0;i<n+1;i++){\n        sol[i] = Array(n+1).fill(-1)\n    }\n    nums.unshift(1);\n    nums.push(1)\n    return rec(1,n,nums,sol)\n};",
        "solution_java": "class Solution {\n    public int maxCoins(int[] nums) {\n        int n = nums.length;\n        \n//         adding 1 to the front and back\n        int[] temp = new int[n + 2];  \n        temp[0] = 1;\n        for(int i = 1; i < temp.length - 1; i++){\n            temp[i] = nums[i-1];\n        }\n        temp[temp.length - 1] = 1;\n        nums = temp;\n        \n//         memoization\n        int[][] dp = new int[n+1][n+1];\n        for(int[] row : dp){\n            Arrays.fill(row, -1);\n        }\n        \n//         result\n        return f(1, n, nums, dp);\n    }\n    \n    int f(int i, int j, int[] a, int[][] dp){\n        if(i > j) return 0;\n        if(dp[i][j] != -1) return dp[i][j];\n        \n        int max = Integer.MIN_VALUE;\n        for(int n = i; n <= j; n++){\n            int coins = a[i-1] * a[n] * a[j+1] + f(i, n-1, a, dp) + f(n+1, j, a, dp);\n            max = Math.max(max, coins);\n        }\n        return dp[i][j] = max;\n    }\n}\n\n// Time Complexity: O(N * N * N) ~ O(N^3);\n// Space Complexity: O(N^2) + O(N);",
        "solution_c": "class Solution {\npublic:\n    //topDown+memoization\n    int solve(int i,int j,vector<int>& nums,vector<vector<int>>& dp){\n        if(i>j) return 0;\n        if(dp[i][j]!=-1) return dp[i][j];\n        \n        int maxcost = INT_MIN;\n        for(int k = i;k<=j;k++){\n            int cost = nums[i-1]*nums[k]*nums[j+1]+solve(i,k-1,nums,dp)+solve(k+1,j,nums,dp);\n            maxcost = max(maxcost,cost);\n        }\n        return dp[i][j] = maxcost;\n    }\n    \n    int maxCoins(vector<int>& nums) {\n        nums.insert(nums.begin(),1);\n        nums.push_back(1);\n        int n = nums.size();\n        vector<vector<int>> dp(n+1,vector<int>(n+1,-1));\n        return solve(1,n-2,nums,dp);\n    }\n    \n    //bottomUp dp\n    int maxCoins(vector<int>& nums) {\n        //including the nums[-1] == 1 and nums[n] == 1\n        int n = nums.size();\n        nums.insert(nums.begin(),1);\n        nums.push_back(1);\n        vector<vector<int>> dp(nums.size()+1,vector<int>(nums.size()+1,0));\n        \n        for (int len = 1; len <= n; ++len)\n            for (int left = 1; left <= n - len + 1; ++left) {\n                int right = left + len - 1;\n                for (int k = left; k <= right; ++k)\n                    dp[left][right] = max(dp[left][right], nums[left-1]*nums[k]*nums[right+1] + dp[left][k-1] + dp[k+1][right]);\n            }\n        return dp[1][n];\n    }\n};"
    },
    {
        "title": "Count Elements With Strictly Smaller and Greater Elements",
        "algo_input": "Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [11,7,2,15]\nOutput: 2\nExplanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n\n\nExample 2:\n\nInput: nums = [-3,3,3,90]\nOutput: 2\nExplanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def countElements(self, nums: List[int]) -> int:\n        M = max(nums)\n        m = min(nums)\n        return sum(1 for i in nums if m<i<M)",
        "solution_js": "var countElements = function(nums) {\n    let map = {}, total = 0;\n\n    // adding elements to map\n    for(let i of nums) map[i] ? map[i]++ : map[i] = 1;\n\n    // Removing repeated elements\n    let newNums = [... new Set(nums)];\n\n    // If length of array after removing repeated nums is less than three return 0;\n    if(newNums.length < 3) return 0;\n\n    // sort the newNums array and remove the first and last element.\n    // for all the remaining elements check their number in map and add it to total variable\n    newNums.sort((a,b) => a-b).slice(1, newNums.length-1).forEach(num => total += map[num]);\n\n    // return total variable\n    return total;\n};",
        "solution_java": "class Solution {\n    public int countElements(int[] nums) {\n        int nmin=Integer.MAX_VALUE;\n        int nmax=Integer.MIN_VALUE;\n        for(int a:nums)\n        {\n            nmin=Math.min(a,nmin);\n            nmax=Math.max(a,nmax);\n        }\n        int count=0;\n        for(int a:nums)\n        {\n            if(a>nmin && a<nmax)\n                count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countElements(vector<int>& nums) {\n        int M = *max_element(nums.begin(), nums.end()); \n        int m = *min_element(nums.begin(), nums.end()); \n        int res = 0;\n        for(int i = 0; i < nums.size(); i++){\n            if(nums[i] > m && nums[i] < M) res++;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Redundant Connection",
        "algo_input": "In this problem, a tree is an undirected graph that is connected and has no cycles.\n\nYou are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.\n\nReturn an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.\n\n&nbsp;\nExample 1:\n\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\n\nExample 2:\n\nInput: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput: [1,4]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == edges.length\n\t3 &lt;= n &lt;= 1000\n\tedges[i].length == 2\n\t1 &lt;= ai &lt; bi &lt;= edges.length\n\tai != bi\n\tThere are no repeated edges.\n\tThe given graph is connected.\n\n",
        "solution_py": "class UnionFind:\n    \n    def __init__(self, size):\n        \n        self.parent = [-1 for _ in range(size)]\n        self.rank = [-1 for _ in range(size)]\n        \n    def find(self, i):\n        \n        if self.parent[i] == -1:\n            return i\n        \n        k = self.find(self.parent[i])\n        self.parent[i] = k\n        return k\n    \n    def union(self, x, y):\n        \n        x = self.find(x)\n        y = self.find(y)\n        \n        if x == y:\n            return -1\n        else:\n            \n            if self.rank[x] > self.rank[y]:\n                self.parent[y] = x\n            \n            elif self.rank[x] < self.rank[y]:\n                self.parent[x] = y\n                \n            else:\n                self.rank[x] += 1\n                self.parent[y] = x\n\nclass Solution:\n    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n   \n        vertex_set = set()\n    \n        for edge in edges:\n            vertex_set.add(edge[0])\n            vertex_set.add(edge[1])\n        \n        \n        union_find = UnionFind(len(vertex_set))\n        \n        for edge in edges:\n            \n            new_edge = [edge[0]-1, edge[1]-1]\n            \n            if union_find.union(new_edge[0], new_edge[1]) == -1:\n                return edge\n        \n        return []",
        "solution_js": "var findRedundantConnection = function(edges) {\n    const root = [];\n    const find = (index) => {\n        const next = root[index];\n        return next ? find(next) : index;\n    };\n\n    for (const [a, b] of edges) {\n        const x = find(a);\n        const y = find(b);\n\n        if (x === y) return [a, b];\n        root[x] = y;\n    }\n};",
        "solution_java": "class Solution {\n    public int[] findRedundantConnection(int[][] edges) {\n        UnionFind uf = new UnionFind(edges.length);\n        for (int[] edge : edges) {\n            if (!uf.union(edge[0], edge[1])) {\n                return new int[]{edge[0], edge[1]};\n            }\n        }\n        return null;\n    }\n\n    private class UnionFind {\n        int[] rank;\n        int[] root;\n\n        UnionFind(int n) {\n            rank = new int[n + 1];\n            root = new int[n + 1];\n            for (int i = 1; i <= n; i++) {\n                root[i] = i;\n                rank[i] = 1;\n            }\n        }\n\n        int find(int x) {\n            if (x == root[x]) {\n                return x;\n            }\n            return root[x] = find(root[x]);\n        }\n\n        boolean union(int x, int y) {\n            int rootX = find(x);\n            int rootY = find(y);\n            if (rootX != rootY) {\n                if (rank[rootX] > rank[rootY]) {\n                    root[rootY] = root[rootX];\n                } else if (rank[rootY] > rank[rootX]) {\n                    root[rootX] = root[rootY];\n                } else {\n                    root[rootY] = root[rootX];\n                    rank[rootX]++;\n                }\n                return true;\n            }\n            return false;\n        }\n    }\n}",
        "solution_c": "class UnionFind {\n    public:\n\n    int* parent;\n    int* rank;\n\n    UnionFind(int n){\n        rank = new int[n];\n        parent = new int[n];\n\n        for(int i=0; i<n; i++){\n            parent[i] = i;\n            rank[i] = 0;\n        }\n    }\n\n    // collapsing find\n    int Find(int node){\n        // if parent of node is itself\n        if(parent[node] == node){\n            return node;\n        }\n        return parent[node] = Find(parent[node]);\n    }\n\n    // union by rank\n    void Union(int u, int v){\n        // find the parent nodes of u and v\n        u = Find(u);\n        v = Find(v);\n\n        // if u and v don't belong to the same set\n        if(u != v){\n            if(rank[u]<rank[v]){\n                swap(u,v);\n            }\n\n            // attaching the lower rank tree with the higher rank one\n            parent[v] = u;\n\n            // if ranks are equal increase the rank of u\n            if(rank[u]==rank[v]){\n                rank[u]++;\n            }\n        }\n    }\n};\n\nclass Solution {\npublic:\n    vector<int> findRedundantConnection(vector<vector<int>>& edges) {\n        UnionFind UF = UnionFind(1001);\n\n        for(vector<int>& edge : edges){\n            int u = edge[0];\n            int v = edge[1];\n\n            // if adding this edge creates a cycle\n            if(UF.Find(u) == UF.Find(v)){\n                return {u,v};\n            }\n\n            // add u and v to the same set\n            UF.Union(u,v);\n        }\n\n        // if no cycle was found\n        return {-1};\n    }\n};"
    },
    {
        "title": "Knight Dialer",
        "algo_input": "The chess knight has a unique movement,&nbsp;it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:\n\nA chess knight can move as indicated in the chess diagram below:\n\nWe have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell&nbsp;(i.e. blue cell).\n\nGiven an integer n, return how many distinct phone numbers of length n we can dial.\n\nYou are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.\n\nAs the answer may be very large, return the answer modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 10\nExplanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 20\nExplanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\n\n\nExample 3:\n\nInput: n = 3131\nOutput: 136006598\nExplanation: Please take care of the mod.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 5000\n\n",
        "solution_py": "class Solution:\n    def knightDialer(self, n: int) -> int:\n        # Sum elements of matrix modulo mod subroutine\n        def sum_mat(matrix, mod):\n            return sum(sum(row) % mod for row in matrix) % mod\n        \n        # Matrix multiplication subroutine\n        def mult_mat(a, b):\n            return [[sum(a[i][k]*b[k][j] for k in range(10)) for j in range(10)] for i in range(10)]\n        \n        # Matrix exponentiation subroutine\n        def pow_mat(matrix, k, dp):\n            if k not in dp:\n                if k == 0:\n                    dp[k] = [[(1 if i == j else 0) for j in range(10)] for i in range(10)]\n                else:\n                    dp[k] = pow_mat(matrix, k//2, dp)\n                    dp[k] = mult_mat(dp[k], dp[k])\n                    if k % 2:\n                        dp[k] = mult_mat(dp[k], matrix)\n            return dp[k]\n       \n        # Create matrix\n        edges = [(1, 6), (1, 8), (2, 9), (2, 7), (3, 4), (3, 8), (4, 0), (4, 9), (6, 1), (6, 0), (6, 7)]\n        matrix =  [[0 for j in range(10)] for i in range(10)]\n        for i, j in edges:\n            matrix[i][j] = 1\n            matrix[j][i] = 1\n        \n\t\t# Solve\n        mod = 10**9 + 7\n        return sum_mat(pow_mat(matrix, n-1, {}), mod)",
        "solution_js": "var knightDialer = function(n) {\n\n    let dp = Array(10).fill(1)\n    let MOD = 10**9 + 7\n\n    for(let i = 2; i <= n ; i++) {\n        oldDp = [...dp]\n        dp[0] = (oldDp[4] + oldDp[6]) % MOD\n        dp[1] = (oldDp[8] + oldDp[6]) % MOD\n        dp[2] = (oldDp[9] + oldDp[7]) % MOD\n        dp[3] = (oldDp[8] + oldDp[4]) % MOD\n        dp[4] = (oldDp[3] + oldDp[9] + oldDp[0]) % MOD\n        dp[5] = 0\n        dp[6] = (oldDp[0] + oldDp[7] + oldDp[1]) % MOD\n        dp[7] = (oldDp[6] + oldDp[2]) % MOD\n        dp[8] = (oldDp[3] + oldDp[1]) % MOD\n        dp[9] = (oldDp[4] + oldDp[2]) % MOD\n    }\n\n    return dp.reduce((ans, ele) => ans += ele, 0) % MOD\n};",
        "solution_java": "class Solution {\n    public int knightDialer(int n) {\n        var dp = new long[10];\n        var tmp = new long[10];\n        Arrays.fill(dp, 1);\n        for (int i = 1; i < n; i++) {\n            tmp[1] = dp[6]+dp[8];\n            tmp[2] = dp[7]+dp[9];\n            tmp[3] = dp[4]+dp[8];\n            tmp[4] = dp[0]+dp[3]+dp[9];\n            tmp[5] = 0;\n            tmp[6] = dp[0]+dp[1]+dp[7];\n            tmp[7] = dp[2]+dp[6];\n            tmp[8] = dp[1]+dp[3];\n            tmp[9] = dp[2]+dp[4];\n            tmp[0] = dp[4]+dp[6];\n            for (int j = 0; j < 10; j++) tmp[j] = tmp[j] % 1000000007;\n            var arr = dp;\n            dp = tmp;\n            tmp = arr;\n        }\n        long res = 0;\n        for (int i = 0; i < 10; i++) {\n            res = (res+dp[i]) % 1000000007;\n        }\n        return (int)res;\n    }\n}",
        "solution_c": "class Solution {\n    int MOD=1e9+7;\npublic:\n    int knightDialer(int n) {\n        if(n==1) return 10;\n        int a=2, b=2, c=3, d=2; //a{2,8} b{1,3,7,9} c{4,6} d{0}\n        for(int i=3; i<=n; i++){\n            int w, x, y, z;\n            w = 2ll*b%MOD;\n            x = (1ll*a + 1ll*c)%MOD;\n            y = (2ll*b + 1ll*d)%MOD;\n            z = 2ll*c%MOD;\n            a = w; b = x; c = y; d = z;\n        }\n        int ans = (2ll*a + 4ll*b + 2ll*c + d)%MOD;\n        return ans;\n    }\n};"
    },
    {
        "title": "Find the Longest Substring Containing Vowels in Even Counts",
        "algo_input": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n\n&nbsp;\nExample 1:\n\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\n\nExample 2:\n\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\n\n\nExample 3:\n\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 x 10^5\n\ts&nbsp;contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findTheLongestSubstring(self, s: str) -> int:\n        integrals = [(False, False, False, False, False)] # integrals[10][mapping[\"a\"]] == False means we have seen \"a\" appears even times before index 10\n        mapping = {\n            \"a\": 0,\n            \"i\": 1,\n            \"u\": 2,\n            \"e\": 3,\n            \"o\": 4\n        }\n\n        for v in s:\n            vector = list(integrals[-1])\n            if v in mapping: # if v is a vowel\n                vector[mapping[v]] = not vector[mapping[v]] # toggle that dimension, because if v had appeared even times before, it becomes odd times now\n            integrals.append(tuple(vector))\n\n        seen = {}\n        res = 0\n\n        for i, v in enumerate(integrals):\n            if v in seen: # we have seen this vector before\n                res = max(res, i - seen[v]) # compare its substring length\n            else:\n                seen[v] = i # just record the first time each vector appears\n\n        return res",
        "solution_js": "var findTheLongestSubstring = function(s) {\n    // u o i e a\n    // 0 0 0 0 0 => initial state, all are even letters\n    // s = \"abcab\"\n    // 0 0 0 0 1 => at index 0, only a is odd count\n    // 0 0 0 0 1 => at index 1, max = 1\n    // 0 0 0 0 1 => at index 2, max = 2\n    // 0 0 0 0 0 => at index 3, max = 4\n    // 0 0 0 0 0 => at index 4, max = 5\n\n    // valid condition: same state in previous index, then it means we have a even count for all letters within the middle substring.\n    var mask = 0;\n    var t = \"aeiou\";\n    var count = new Map(); // <mask, first_idx>\n    count.set(0,-1);\n    var res = 0;\n    for(var i = 0; i<s.length; i++)\n    {\n        if(t.indexOf(s[i])>=0)\n        {\n            var j = t.indexOf(s[i]);\n            mask = mask ^ (1 << j);\n        }\n        if(!count.has(mask))\n        {\n            count.set(mask,i);\n        }\n        else\n        {\n            // substring is from [prevIdx+1, i];\n            res = Math.max(res, i - count.get(mask));\n        }\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n     public int findTheLongestSubstring(String s) {\n        int res = 0 , mask = 0, n = s.length();\n        HashMap<Integer, Integer> seen = new HashMap<>();// key--> Mask, value--> Index\n        seen.put(0, -1);\n        for (int i = 0; i < n; ++i) {\n            if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){ // check only vowels and skip consonant\n                int c=s.charAt(i);\n                mask=mask ^ c;\n                seen.putIfAbsent(mask, i);\n            }            \n            res = Math.max(res, i - seen.get(mask));\n        }\n        return res;\n    }\n}",
        "solution_c": "//When the xor of all the even times numbers are done it results in 0. The xor of the vowels are done by indicating\n//them with a single digit and the xor value is stored in a map\nclass Solution {\npublic:\n    int findTheLongestSubstring(string s) {\n        int x= 0;\n        unordered_map<int,int>mp;\n        mp[0]=-1;\n        int n=0;\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u'){\n                x^= (s[i]-'a'+1);\n               if(mp.find(x)==mp.end())\n                  mp[x]=i;\n            }\n            if(mp.find(x)!=mp.end())\n                n= max(n,i-mp[x]);\n        }\n        return n;\n    }\n};"
    },
    {
        "title": "Describe the Painting",
        "algo_input": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color.\n\nThe colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.\n\n\n\tFor example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}.\n\n\nFor the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.\n\nYou want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj.\n\n\n\tFor example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because:\n\n\t\n\t\t[1,4) is colored {5,7} (with a sum of 12) from both the first and second segments.\n\t\t[4,7) is colored {7} from only the second segment.\n\t\n\t\n\n\nReturn the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.\n\nA half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.\n\n&nbsp;\nExample 1:\n\nInput: segments = [[1,4,5],[4,7,7],[1,7,9]]\nOutput: [[1,4,14],[4,7,16]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.\n\n\nExample 2:\n\nInput: segments = [[1,7,9],[6,8,15],[8,10,7]]\nOutput: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation: The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.\n\n\nExample 3:\n\nInput: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput: [[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= segments.length &lt;= 2 * 104\n\tsegments[i].length == 3\n\t1 &lt;= starti &lt; endi &lt;= 105\n\t1 &lt;= colori &lt;= 109\n\tEach colori is distinct.\n\n",
        "solution_py": "class Solution:\n    def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n        mix, res, last_i = DefaultDict(int), [], 0\n        for start, end, color in segments:\n            mix[start] += color\n            mix[end] -= color\n        for i in sorted(mix.keys()):\n            if last_i in mix and mix[last_i]:\n                res.append([last_i, i, mix[last_i]])\n                mix[i] += mix[last_i]\n            last_i = i\n        return res",
        "solution_js": "/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n    const arr = [];\n    segments.forEach(([start, end, val])=>{\n        arr.push([start, val]);\n        arr.push([end, -val]);\n    });\n    arr.sort((i,j)=>i[0]-j[0]);\n\n    const ans = [];\n    let currVal = 0, prevTime;\n    arr.forEach(([time, val])=>{\n        if(prevTime !== undefined && currVal && prevTime !== time) ans.push([prevTime, time, currVal]);\n        currVal += val;\n        prevTime = time;\n    })\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    //class for segments \n    class Seg{\n        int val,end;\n        int color;\n        boolean isStart;\n        public Seg(int val,int end,int color, boolean isStart){\n            this.val = val;\n            this.end = end;\n            this.color = color;\n            this.isStart = isStart; \n        }\n        public String toString(){\n            return \"[\" + val+\" \"+end+\" \"+color+\" \"+isStart+\"]\";\n        }\n    }\n    public List<List<Long>> splitPainting(int[][] segments) {\n        List<List<Long>> res = new ArrayList();\n        \n        List<Seg> list = new ArrayList();\n        \n        //making a list of segments\n        for(int[] segment : segments){\n            list.add(new Seg(segment[0],segment[1],segment[2],true));\n            list.add(new Seg(segment[1],segment[1],segment[2],false));            \n        }\n        \n        //Sorting the segments\n        Collections.sort(list,(a,b)->{return a.val-b.val;});\n        \n        //System.out.println(list);\n        \n        //Iterating over list to combine the elements\n        for(Seg curr: list){\n            int len = res.size();\n            if(curr.isStart){\n                //if the segment is starting there could be three ways \n                if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n                    //if starting point of two things is same\n                    List<Long> temp = res.get(len-1);\n                    temp.set(1,Math.max(temp.get(1),curr.end));\n                    temp.set(2,(long)(temp.get(2)+curr.color));\n                }else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n                    //if there is a start in between create a new segment of different color \n                    List<Long> prev = res.get(len-1);\n                    prev.set(1,(long)curr.val);\n                    List<Long> temp = new ArrayList();\n                    temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)(prev.get(2)+curr.color));\n                    res.add(temp);\n                }else{\n                    //Add a new value if nothing is present in result\n                    List<Long> temp = new ArrayList();\n                    temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)curr.color);\n                    res.add(temp);\n                }\n            }else{\n                if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n                    //if ending point of 2 segments is same\n                    Long prevColor = res.get(len-1).get(2);\n                    res.get(len-1).set(2,(long)(prevColor-curr.color));\n                }\n                else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n                    //if there is a ending in between create a new segment of different color \n                    Long prevColor = res.get(len-1).get(2);\n                    Long prevEnd = res.get(len-1).get(1);\n                    res.get(len-1).set(1,(long)curr.val);\n                    \n                    List<Long> temp = new ArrayList();\n                    temp.add((long)curr.val); temp.add((long)prevEnd); temp.add((long)(prevColor-curr.color));\n                    res.add(temp);\n                }\n            }\n            //System.out.println(res+\" \"+curr);\n            \n        }\n        //System.out.println(res);\n        return res; \n        \n    }\n}",
        "solution_c": "typedef long long ll;\n\nclass Solution {\npublic:\n    vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n        vector<vector<ll> > ans;\n        map<int,ll> um;\n        \n        for(auto s : segments){\n            um[s[0]] += s[2];\n            um[s[1]] -= s[2];\n        }\n        bool flag = false;\n        pair<int,ll> prev;\n        ll curr = 0;\n        \n        for(auto x : um){\n            if(flag == false){\n                prev = x;\n                curr += x.second;\n                flag = true;\n                continue;\n            }\n            \n            vector<ll> v = {prev.first,x.first,curr};\n            prev = x;\n            if(curr)\n                ans.push_back(v);\n            curr += x.second;\n            \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Substring With Largest Variance",
        "algo_input": "The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.\n\nGiven a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aababbb\"\nOutput: 3\nExplanation:\nAll possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings \"a\", \"aa\", \"ab\", \"abab\", \"aababb\", \"ba\", \"b\", \"bb\", and \"bbb\".\n- Variance 1 for substrings \"aab\", \"aba\", \"abb\", \"aabab\", \"ababb\", \"aababbb\", and \"bab\".\n- Variance 2 for substrings \"aaba\", \"ababbb\", \"abbb\", and \"babb\".\n- Variance 3 for substring \"babbb\".\nSince the largest possible variance is 3, we return it.\n\n\nExample 2:\n\nInput: s = \"abcde\"\nOutput: 0\nExplanation:\nNo letter occurs more than once in s, so the variance of every substring is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    class Solution:\n    def largestVariance(self, s: str) -> int:\n        \n        def maxSubArray(nums: List[int]):\n            ans=-float('inf')\n            runningSum=0\n            seen=False\n            for x in (nums):\n                if x<0:\n                    seen=True\n                runningSum+=x\n                if seen:\n                    ans=max(ans,runningSum)\n                else:\n                    ans=max(ans,runningSum-1)\n                if runningSum<0:\n                    runningSum=0\n                    seen=False\n            return ans\n        \n        f=set()\n        a=''\n        for x in s:\n            if x not in f:\n                a+=x\n                f.add(x)\n       \n        n=len(s)\n        res=0\n        for j in range(len(a)-1):\n            for k in range(j+1,len(a)):\n                x=a[j]\n                y=a[k]\n                arr=[]\n                for i in range(n):\n                    if s[i]!=x and s[i]!=y:\n                        continue\n                    elif s[i]==x:\n                        arr.append(1)\n                    else:\n                        arr.append(-1)\n                \n                res=max(res,maxSubArray(arr),maxSubArray([-x for x in arr]))\n                \n        return res\n                \n                \n                \n                ",
        "solution_js": "var largestVariance = function(s) {\n  let chars = new Set(s.split(\"\")), maxDiff = 0;\n  for (let l of chars) {\n    for (let r of chars) {\n      if (l === r) continue;\n      let lCount = 0, rCount = 0, hasRight = false;\n      for (let char of s) {\n        lCount += char === l ? 1 : 0;\n        rCount += char === r ? 1 : 0;\n        if (rCount > 0 && lCount > rCount) { // has both characters and positive difference\n          maxDiff = Math.max(maxDiff, lCount - rCount);\n        }\n        if (lCount > rCount && hasRight) { // has positive difference and a previous \"right\" character we can add to the start\n          maxDiff = Math.max(maxDiff, lCount - rCount - 1);\n        }\n        if (lCount < rCount) {\n          lCount = 0, rCount = 0;\n          hasRight = true;\n        }\n      }\n    }\n  }\n  return maxDiff;\n};",
        "solution_java": "class Solution {\n    public int largestVariance(String s) {\n        \n        int [] freq = new int[26];\n        for(int i = 0 ; i < s.length() ; i++)\n            freq[(int)(s.charAt(i) - 'a')]++;\n        \n        int maxVariance = 0;\n        for(int a = 0 ; a < 26 ; a++){\n            for(int b = 0 ; b < 26 ; b++){\n                int remainingA = freq[a];\n                int remainingB = freq[b];\n                if(a == b || remainingA == 0 || remainingB == 0) continue;\n                \n\t\t\t\t// run kadanes on each possible character pairs (A & B)\n                int currBFreq = 0, currAFreq = 0;\n                for(int i = 0 ; i < s.length() ; i++){\n                    int c =  (int)(s.charAt(i) - 'a');\n                    \n                    if(c == b) currBFreq++;\n                    if(c == a) {\n                        currAFreq++;\n                        remainingA--;\n                    }\n                    \n                    if(currAFreq > 0)\n                        maxVariance = Math.max(maxVariance, currBFreq - currAFreq);\n                    \n                    if(currBFreq < currAFreq &&  remainingA >= 1){\n                        currBFreq = 0;\n                        currAFreq = 0;\n                    }\n                }\n            }\n        }\n        \n        return maxVariance;\n    }\n}",
        "solution_c": "/*\n    Time: O(26*26*n)\n    Space: O(1)\n    Tag: Kadane's Algorithm\n    Difficulty: H (Logic) | E(Implementation)\n*/\n\nclass Solution {\npublic:\n    int largestVariance(string s) {\n        int res = 0;\n        for (int i = 0; i < 26; i++) {\n            for (int j = 0; j < 26; j++) {\n                if (i == j) continue;\n                int highFreq = 0;\n                int lowFreq = 0;\n                bool prevHadLowFreqChar = false;\n                for (char ch : s) {\n                    if (ch - 'a' == i)\n                        highFreq++;\n                    else if (ch - 'a' == j)\n                        lowFreq++;\n                    if (lowFreq > 0)\n                        res = max(res, highFreq - lowFreq);\n                    else if (prevHadLowFreqChar)\n                        res = max(res, highFreq - 1);\n                    if (highFreq - lowFreq < 0) {\n                        highFreq = 0;\n                        lowFreq = 0;\n                        prevHadLowFreqChar = true;\n                    }\n                }\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Rectangle Area",
        "algo_input": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.\n\nThe first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).\n\nThe second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).\n\n&nbsp;\nExample 1:\n\nInput: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput: 45\n\n\nExample 2:\n\nInput: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput: 16\n\n\n&nbsp;\nConstraints:\n\n\n\t-104 &lt;= ax1 &lt;= ax2 &lt;= 104\n\t-104 &lt;= ay1 &lt;= ay2 &lt;= 104\n\t-104 &lt;= bx1 &lt;= bx2 &lt;= 104\n\t-104 &lt;= by1 &lt;= by2 &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n        def segment(ax1,ax2,bx1,bx2):\n            return min(ax2,bx2) - max(ax1, bx1) if max(ax1, bx1) < min(ax2, bx2) else 0\n        return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - segment(ax1,ax2,bx1,bx2)*segment(ay1,ay2,by1,by2)",
        "solution_js": "var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {\n    let area1 = (ax2-ax1)*(ay2-ay1)\n    let area2 = (bx2-bx1)*(by2-by1)\n    let overlap = (by1>ay2 || by2<ay1 || bx1>ax2 || bx2<ax1) ? 0 : Math.abs((Math.min(ax2,bx2) - Math.max(ax1, bx1))*(Math.min(ay2,by2) - Math.max(ay1, by1)))\n    \n    return area1 + area2 - overlap\n};",
        "solution_java": "class Solution {\n    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n        int x1 = Math.max(ax1,bx1);\n        int y1 = Math.max(ay1,by1);\n        int x2 = Math.min(ax2,bx2);\n        int y2 = Math.min(ay2,by2);\n\n        int area = 0;\n        int R1 = (ax2-ax1)*(ay2-ay1);\n        int R2 = (bx2-bx1)*(by2-by1);\n        area = R1 + R2;\n\n        if(x2 > x1 && y2 > y1){\n            int overlap = (x2-x1)*(y2-y1);\n            area = area - overlap;\n        }\n\n        return area;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n        int rec1=abs(ax2-ax1)*abs(ay2-ay1); //Area(Rectangle 1)\n        int rec2=abs(bx2-bx1)*abs(by2-by1); //Area(Rectangle 2)\n\n        //As explained above, if intervals overlap, max(x1,x3) < min(x2,x4) and overlapped interval\n        //is ( max(x1,x3) , min(x2,x4) ).\n\n        int ox1=(max(ax1,bx1)-min(ax2,bx2)); //if ox1 is negative, abs(ox1) is the length of overlapped rectangle, else rectangles do not overlap.\n        int oy1=(max(ay1,by1)-min(ay2,by2)); //breadth of overlapped rectangle\n\n        int rec3=0; //if rectangles do not overlap, area of overlapped rectangle is zero.\n        if(ox1<0&&oy1<0) //if both ox1 and oy2 are negative, two rectangles overlap.\n            rec3=ox1*oy1;\n        return rec1+rec2-rec3; //Area(Rectangle 1) + Area(Rectangle 2) - Area(Overlapped triangle)\n    }\n};"
    },
    {
        "title": "Maximum Split of Positive Even Integers",
        "algo_input": "You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.\n\n\n\tFor example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique.\n\n\nReturn a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.\n\n&nbsp;\nExample 1:\n\nInput: finalSum = 12\nOutput: [2,4,6]\nExplanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.\n\n\nExample 2:\n\nInput: finalSum = 7\nOutput: []\nExplanation: There are no valid splits for the given finalSum.\nThus, we return an empty array.\n\n\nExample 3:\n\nInput: finalSum = 28\nOutput: [6,8,2,12]\nExplanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). \n(6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= finalSum &lt;= 1010\n\n",
        "solution_py": "class Solution:\n    def maximumEvenSplit(self, finalSum: int) -> List[int]:\n        l=[]\n        if finalSum%2!=0:\n            return l\n        else:\n            s=0\n            i=2 # even pointer 2, 4, 6, 8, 10, 12...........\n            while(s<finalSum):\n                s+=i #sum\n                l.append(i) # append the i in list\n                i+=2\n            if s==finalSum: #if sum s is equal to finalSum then no modidfication required\n                return l\n            else:\n                l.pop(l.index(s-finalSum)) #Deleting the element which makes s greater than finalSum\n            return l",
        "solution_js": " var maximumEvenSplit = function(finalSum) {\n\n    if(finalSum % 2) return [];\n\n    const set = new Set();\n\n    let n = 2, sum = 0;\n\n    while(sum < finalSum) {\n        sum += n;\n        set.add(n);\n        n += 2;\n    }\n\n    set.delete(sum - finalSum);\n\n    return [...set];\n};",
        "solution_java": "class Solution {\n    public List<Long> maximumEvenSplit(long finalSum) {\n        List<Long> res = new ArrayList<Long>();\n        //odd sum cannot be divided into even numbers\n        if(finalSum % 2 != 0) {\n            return res;\n        }\n        //Greedy approach, try to build the total sum using minimum unique even nos\n        long currNum = 2;\n        long remainingSum = finalSum;\n        //as long as we can add subtract this number from remaining sum\n        while(currNum <= remainingSum) {\n            res.add(currNum);\n            remainingSum -= currNum;//reducing remaining sum\n            currNum += 2;//next even number\n        }\n        //now, remaining sum cannot be fulfilled by any larger even number\n        //so extract the largest even number we added to the last index of res, and make it even larger by adding this current remaining sum\n        //add remaining sum to the last element\n        long last = res.remove(res.size()-1);\n        res.add(last+remainingSum);\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    using ll = long long;\n\n    ll bs(ll low , ll high, ll fs){\n\n        ll ans = 1;\n        while(low<=high){\n            ll mid = low + (high-low)/2;\n            if(mid*(mid+1)>fs){\n                high = mid-1; // If sum till index equal to 'mid' > fs then make high = mid-1\n            }\n            else if(mid*(mid+1)==fs){\n                return mid; // If sum till index equal to 'mid == fs, return 'mid'\n            }\n            else{\n                ans = mid; // If sum till index equal to 'mid' < fs, update answer\n                low = mid+1; // check for better answer\n            }\n        }\n        return ans;\n    }\n\n    vector<long long> maximumEvenSplit(long long finalSum) {\n        // ****some base cases / corner cases****\n        if(finalSum&1) return {};\n        if(finalSum==4) return {4};\n        if(finalSum==8) return {2,6};\n\n        vector<ll> ans;\n\n        // assume that we are giving indices to even numbers\n        // EVEN NUMBERS -> 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 ..............\n        // THEIR INDICES-> 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ..............\n\n        // 'idx' is the index of that EVEN number uptil which the total sum of all even numbers <= finalSum\n        ll idx = bs(1,finalSum/2,finalSum);\n\n        //Consequently, 'end' is that EVEN number uptil which the total sum of all even numbers <= finalSum\n        ll start = 2, end = idx*2;\n\n        //Now, we add all the even numbers from index 1 to index 'idx-1'\n        // 2 + 4 + 6 + 8 ........................... + (end-2) + end\n        // 1 2 3 4 ........................... idx-1 idx\n        for(int i = start; i<= (idx-1)*2; i+=2){\n            ans.push_back(i);\n        }\n\n        // We do not add the last even number yet, so that we can modify it and add it later to make the (totalSumSoFar) == finalSum\n        // 'totalSumSoFar' can be easily calculated by using the formula ( totalSumSoFar = idx*(idx+1) )\n\n        // increasing the last even number 'end' by the difference of (finalSum and totalSumSoFar)\n        if(idx*(idx+1)<finalSum){\n            end = end + abs(finalSum - idx*(idx+1));\n        }\n\n        // adding the last even number after increasing it with the required factor\n        ans.push_back(end);\n        return ans;\n    }\n};"
    },
    {
        "title": "Sort an Array",
        "algo_input": "Given an array of integers nums, sort the array in ascending order.\n\n&nbsp;\nExample 1:\nInput: nums = [5,2,3,1]\nOutput: [1,2,3,5]\nExample 2:\nInput: nums = [5,1,1,2,0,0]\nOutput: [0,0,1,1,2,5]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t-5 * 104 &lt;= nums[i] &lt;= 5 * 104\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def sortArray(self, nums: List[int]) -> List[int]:\n        \n        h = {}\n        for i in nums:\n            if i in h:\n                h[i]+=1\n            else:\n                h[i]=1\n        \n        heap = []\n        for i in h:\n            heap.append([i,h[i]])\n        \n        heapq.heapify(heap)\n        ans = []\n        \n        while heap:\n            x = heapq.heappop(heap)\n            ans.append(x[0])\n            if x[1]>1:\n                heapq.heappush(heap,[x[0],x[1]-1])\n                \n        return ans",
        "solution_js": "var sortArray = function(nums) {\n    return quickSort(nums, 0, nums.length - 1);\n};\n\nconst quickSort = (arr, start, end) => {\n    // base case\n    if (start >= end) return arr;\n\n    // return pivot index to divide array into 2 sub-arrays.\n    const pivotIdx = partition(arr, start, end);\n    // sort sub-array to the left and right of pivot index.\n    quickSort(arr, start, pivotIdx - 1);\n    quickSort(arr, pivotIdx + 1, end);\n\n    return arr;\n}\n\nconst partition = (arr, start, end) => {\n    // select a random pivot index, and swap pivot value with end value.\n    const pivotIdx = Math.floor(Math.random() * (end - start + 1)) + start;\n    [arr[pivotIdx], arr[end]] = [arr[end], arr[pivotIdx]];\n\n    const pivotVal = arr[end];\n    // loop from start to before end index (because pivot is stored at end index).\n    for (let i = start; i < end; i++) {\n        if (arr[i] < pivotVal) {\n            // swap smaller-than-pivot value (at i) with the value at the start index.\n            // This ensures all values to the left of start index will be less than pivot.\n            [arr[i], arr[start]] = [arr[start], arr[i]];\n            start++;\n        }\n    }\n\n    // swap pivot (which was stored at end index) with value at start index.\n    // This puts the pivot in its correct place.\n    [arr[start], arr[end]] = [arr[end], arr[start]];\n    return start;\n}\n\n/*\nNote: Instead of always picking a fixed index as the pivot (ie. start or end index),\nThe pivot was randomly selected to mitigate the odds of achieving worst case TC and SC.\nTC:\nBest and avg case: O(nlogn)\nworst case: O(n^2)\n\nSC:\nSince algo done in-place, space comes from recursive call stack.\nbest and avg case: O(logn)\nworst case: O(n)\n*/",
        "solution_java": "class Solution {\n\n        public void downHeapify(int[] nums, int startIndex, int lastIndex){\n\n        int parentIndex = startIndex;\n        int leftChildIndex = 2*parentIndex + 1;\n        int rightChildIndex = 2*parentIndex + 2;\n\n        while(leftChildIndex <= lastIndex){\n            int maxIndex = parentIndex;\n            if(nums[leftChildIndex] > nums[maxIndex]){\n                maxIndex = leftChildIndex;\n            }\n            if(rightChildIndex <= lastIndex && nums[rightChildIndex] > nums[maxIndex]){\n                maxIndex = rightChildIndex;\n            }\n            if(maxIndex == parentIndex){\n                return;\n            }\n            int temp = nums[maxIndex];\n            nums[maxIndex] = nums[parentIndex];\n            nums[parentIndex] = temp;\n            parentIndex = maxIndex;\n            leftChildIndex = 2*parentIndex + 1;\n            rightChildIndex = 2*parentIndex + 2;\n        }\n        return;\n    }\n\n    public int[] sortArray(int[] nums) {\n        int len = nums.length;\n        //building a heap - O(n) time\n        for(int i=(len/2)-1;i>=0;i--){\n            downHeapify(nums,i,len-1);\n        }\n        //sorting element - nlogn(n) time\n        for(int i=len -1 ;i>0;i--){\n             int temp = nums[i];\n             nums[i] = nums[0];\n             nums[0] = temp;\n             downHeapify(nums,0,i-1);\n        }\n        return nums;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> sortArray(vector<int>& nums) {\n        priority_queue<int, vector<int>, greater<int>>pq;\n        for(auto it : nums)\n        {\n            pq.push(it);\n        }\n        vector<int>ans;\n        while(!pq.empty())\n        {\n            ans.push_back(pq.top());\n            pq.pop();\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Min Cost Climbing Stairs",
        "algo_input": "You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.\n\nYou can either start from the step with index 0, or the step with index 1.\n\nReturn the minimum cost to reach the top of the floor.\n\n&nbsp;\nExample 1:\n\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n\n\nExample 2:\n\nInput: cost = [1,100,1,1,1,100,1,1,100,1]\nOutput: 6\nExplanation: You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= cost.length &lt;= 1000\n\t0 &lt;= cost[i] &lt;= 999\n\n",
        "solution_py": "class Solution:\n    def minCostClimbingStairs(self, cost: List[int]) -> int:\n        n = len(cost)\n        dp = cost[:2] + [0]*(n-2)\n        for i in range(2, n):\n            dp[i] = min(dp[i-1], dp[i-2]) + cost[i]\n        return min(dp[-1], dp[-2])",
        "solution_js": "var minCostClimbingStairs = function(cost) {\n    //this array will be populated with the minimum cost of each step starting from the top\n    let minCostArray = [];\n    //append a 0 at end to represent reaching the 'top'\n    minCostArray[cost.length] = 0;\n    //append the last stair to the end of the array\n    minCostArray[cost.length - 1] = cost[cost.length - 1];\n    \n    //starts at -2 the length since we already have two elements in our array\n    for (let i = cost.length - 2; i > -1; i--) {\n        //checks which minimum cost is lower and assigns the value at that index accordingly\n        if (minCostArray[i + 1] < minCostArray[i + 2]) minCostArray[i] = cost[i] + minCostArray[i + 1];\n        else minCostArray[i] = cost[i] + minCostArray[i + 2];\n    }\n    //checks which of the first two options is the lowest cost\n    return minCostArray[0] > minCostArray[1] ? minCostArray[1] : minCostArray[0];\n};",
        "solution_java": "class Solution {\n    public int minCostClimbingStairs(int[] cost) {\n        int a[] = new int[cost.length+1];\n        a[0]=0;\n        a[1]=0;\n        \n        for(int i=2;i<=cost.length;i++)\n        {\n            a[i]= Math.min(cost[i-1]+a[i-1], cost[i-2]+a[i-2]);\n        }\n        return a[cost.length];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minCostClimbingStairs(vector<int>& cost) {\n        /* Minimize cost of steps, where you can take one or two steps.\n           \n           At each step, store the minimum of the current step plus the step previous\n           or the step two previous. At the last step we can either take the last\n           element or leave it off.\n        */\n        int n = cost.size();\n        for(int i = 2; i < n; i++) {\n            cost[i] = min(cost[i] + cost[i-2], cost[i] + cost[i-1]);    \n        }\n        \n        return min(cost[n-1], cost[n-2]);\n    }\n};"
    },
    {
        "title": "Watering Plants II",
        "algo_input": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.\n\nEach plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:\n\n\n\tAlice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously.\n\tIt takes the same amount of time to water each plant regardless of how much water it needs.\n\tAlice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.\n\tIn case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant.\n\n\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.\n\n&nbsp;\nExample 1:\n\nInput: plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput: 1\nExplanation:\n- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.\n\n\nExample 2:\n\nInput: plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput: 2\nExplanation:\n- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.\n\n\nExample 3:\n\nInput: plants = [5], capacityA = 10, capacityB = 8\nOutput: 0\nExplanation:\n- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == plants.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= plants[i] &lt;= 106\n\tmax(plants[i]) &lt;= capacityA, capacityB &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n        \n        Alice , Bob  = capacityA, capacityB\n        \n        res, i, j = 0, 0, len(plants)-1\n        \n        while i < j:\n            if Alice >= plants[i]:\n                Alice -= plants[i]\n            else:\n                res += 1\n                Alice = capacityA - plants[i]\n            \n            if Bob >= plants[j]:\n                Bob -= plants[j]\n            else:\n                res += 1\n                Bob = capacityB - plants[j]\n                \n            i += 1    \n            j -= 1\n        \n        return res + 1 if i == j and Alice < plants[i] and Bob < plants[i] else res\n\t\t",
        "solution_js": "var minimumRefill = function(plants, capacityA, capacityB) {\n    const n = plants.length;\n\n    let left = 0;\n    let right = n - 1;\n\n    let remA = capacityA;\n    let remB = capacityB;\n\n    let refills = 0;\n\n    while (left < right) {\n        const leftAmount = plants[left++];\n        const rightAmount = plants[right--];\n\n        if (leftAmount > remA) {\n            ++refills;\n            remA = capacityA;\n        }\n        remA -= leftAmount;\n\n        if (rightAmount > remB) {\n            ++refills;\n            remB = capacityB;\n        }\n        remB -= rightAmount;\n\n    }\n\n    if (left === right) {\n        const midAmount = plants[left];\n\n        if (remB > remA) {\n            if (remB < midAmount) ++refills;\n        }\n        else {\n            if (remA < midAmount) ++refills;\n        }\n    }\n\n    return refills;\n};",
        "solution_java": "class Solution {\n    public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n        int count=0;\n        int c1=capacityA,c2=capacityB;\n        for(int start=0,end=plants.length-1;start<=plants.length/2&&end>=plants.length/2;start++,end--){\n            if(start==end||start>end)break;\n            if(c1>=plants[start]){\n                c1-=plants[start];\n            }\n            else{\n                count++;\n                c1=capacityA;\n                c1-=plants[start];\n            }\n            if(c2>=plants[end]){\n                c2-=plants[end];\n            }\n            else{\n                count++;\n                c2=capacityB;\n                c2-=plants[end];\n            }\n        }\n        if((c1>c2||c1==c2)&&plants.length%2!=0){\n            if(plants[plants.length/2]>c1)count++;\n        }\n        else if(c1<c2&&plants.length%2!=0){\n            if(plants[plants.length/2]>c2)count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n     \n        int n(plants.size()), res(0), aliceC(capacityA), bobC(capacityB), alice(0), bob(n-1);\n        \n        while (alice < bob)\n        {\n            if (alice == bob)\n            {\n                if (aliceC < plants[alice] and bobC < plants[bob]) res++;\n                break;\n            }\n            if (aliceC < plants[alice]) aliceC = capacityA, res++;\n            if (bobC < plants[bob]) bobC = capacityB, res++;\n            aliceC -= plants[alice++];\n            bobC -= plants[bob--];\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Largest Multiple of Three",
        "algo_input": "Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.\n\nSince the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.\n\n&nbsp;\nExample 1:\n\nInput: digits = [8,1,9]\nOutput: \"981\"\n\n\nExample 2:\n\nInput: digits = [8,6,7,1,0]\nOutput: \"8760\"\n\n\nExample 3:\n\nInput: digits = [1]\nOutput: \"\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= digits.length &lt;= 104\n\t0 &lt;= digits[i] &lt;= 9\n\n",
        "solution_py": "class Solution:\n\tdef largestMultipleOfThree(self, digits: List[int]) -> str:\n\t\tA = digits\n\t\tA.sort()\n\t\tA.reverse()\n\n\t\t@cache\n\t\tdef DP(i, r): # max number whose remainder is r using subarray [0:i] (inclusive) \n\t\t\tif i == 0:\n\t\t\t\tif A[0] % 3 == r:\n\t\t\t\t\treturn A[0]\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\n\t\t\tRa = DP(i-1, r)\n\t\t\tRb = [ x for j in range(3) \\\n\t\t\t\t  for x in ( DP(i-1,j) * 10 + A[i] ,)\n\t\t\t\t  if x % 3 == r ]\n\n\t\t\treturn max([Ra, *Rb])\n\n\t\tans = DP(len(A) - 1, 0)\n\n\t\tif ans == 0 and 0 not in A:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn str(ans)",
        "solution_js": "/**\n * @param {number[]} digits\n * @return {string}\n */\nvar largestMultipleOfThree = function(digits) {\n    // highest digit first\n    digits.sort((l, r) => r - l);\n    \n    // what is the remainder of the total sum?\n    const sumRemainder = digits.reduce((a, c) => a + c, 0) % 3;\n    \n    if (sumRemainder) {\n        let targetIndex = 0, i = digits.length - 1;\n        \n        // try to find what is the smallest number that can be removed\n        for (; i >= 0; i--) {\n            if ((digits[i] - sumRemainder) % 3 === 0) {\n                targetIndex = i;\n                break;\n            }\n        }\n\n        if (i < 0) {\n            // iterated the whole loop, couldn't find a single number to remove\n            // remove everything but multiples of 3\n            digits = digits.filter(v => v % 3 === 0);\n        } else {\n            digits.splice(targetIndex, 1);\n        }\n    }\n    \n    return (digits[0] === 0) ? '0' : digits.join('');\n};",
        "solution_java": "class Solution {\n    public String largestMultipleOfThree(int[] digits) {\n        int n=digits.length;\n        Arrays.sort(digits);\n        \n        if(digits[digits.length-1]==0){\n            return \"0\";\n        }\n        \n        int sum=0;\n        \n        for(int i=0;i<digits.length;i++){\n            sum+=digits[i];\n        }\n        \n        if(sum%3==0){\n            StringBuilder sb=new StringBuilder(\"\");\n            \n            for(int i=n-1;i>=0;i--){\n                sb.append(digits[i]);\n            }\n            \n            return sb.toString();\n        }else if(sum%3==1){\n            int modOne=-1;\n            \n            for(int i=0;i<n;i++){\n                if(digits[i]%3==1){\n                    modOne=i;\n                    break;\n                }\n            }\n            \n            if(modOne==-1){\n                int []idx=new int[2];\n                Arrays.fill(idx,-1);\n                \n                for(int i=0;i<n;i++){\n                    if(digits[i]%3==2){\n                        if(idx[0]==-1){\n                            idx[0]=i;\n                        }else{\n                            idx[1]=i;\n                            break;\n                        }\n                    }\n                }\n                \n                if(idx[1]==-1){\n                    return \"\";\n                }else{\n                    digits[idx[0]]=-1;\n                    digits[idx[1]]=-1;\n                }\n            }else{\n                digits[modOne]=-1;\n            }\n        }else{\n            int modTwo=-1;\n            \n            for(int i=0;i<n;i++){\n                if(digits[i]%3==2){\n                    modTwo=i;\n                    break;\n                }\n            }\n            \n            if(modTwo==-1){\n                int []idx=new int[2];\n                Arrays.fill(idx,-1);\n                \n                for(int i=0;i<n;i++){\n                    if(digits[i]%3==1){\n                        if(idx[0]==-1){\n                            idx[0]=i;\n                        }else{\n                            idx[1]=i;\n                            break;\n                        }\n                    }\n                }\n                \n                if(idx[1]==-1){\n                    return \"\";\n                }else{\n                    digits[idx[0]]=-1;\n                    digits[idx[1]]=-1;\n                }\n            }else{\n                digits[modTwo]=-1;\n            }\n        }\n        \n        StringBuilder sb=new StringBuilder(\"\");\n        \n        for(int i=n-1;i>=0;i--){\n            if(digits[i]!=-1){\n                sb.append(digits[i]);\n            }\n            \n        }\n        \n        if(sb.length()>0 && sb.toString().charAt(0)=='0'){\n            return \"0\";\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    vector<int> ans;\n\n    void calculate(vector<int>& count,int no,vector<int>& temp){\n\n        if(no==0){\n            int flag=0,sum1=0,sum2=0,validSum=0;\n            for(int j=1;j<10;j++){\n                sum1+=temp[j];\n                sum2+=ans[j];\n                validSum+=(temp[j]*j);\n            }\n            if(validSum%3!=0){\n                return ;\n            }\n\n            if(sum2>sum1)\n                return;\n            else if(sum1>sum2){\n             for(int i=1;i<10;i++){\n              ans[i]=temp[i];\n             }\n                return ;\n            }\n            int j=9;\n            while(j>0){\n                if(ans[j]<temp[j])\n                {\n                    flag=1;\n                    break;\n                }else if(ans[j]>temp[j])\n                    break;\n                j--;\n            }\n            if (flag==1){\n             for(int i=1;i<10;i++){\n              ans[i]=temp[i];\n             }\n            }\n            return ;\n        }\n\n        int targetCount=count[no]-2;\n\n        if(targetCount<0)\n            targetCount=0;\n\n        int co=count[no];\n\n        do{\n            temp[no]=co;\n\n            calculate(count,no-1,temp);\n\n            co--;\n        }\n        while(co>=targetCount);\n\n    }\n\n    string largestMultipleOfThree(vector<int>& digits) {\n        vector<int> count(10,0);\n        int n=digits.size();\n        for(int i=0;i<n;i++){\n            count[digits[i]]++;\n        }\n        vector<int> temp(10,0);\n        ans.resize(10,0);\n        calculate(count,9,temp);\n\n        string res=\"\";\n        ans[0]=count[0];\n        for(int i=9;i>=0;i--){\n            for(int j=1;j<=ans[i];j++){\n                res+=('0'+i);\n            }\n        }\n        if(res.size()>=2 && res[0]=='0' && res[1]=='0')\n            return \"0\";\n        return res;\n    }\n};"
    },
    {
        "title": "Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit",
        "algo_input": "Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.\n\n&nbsp;\nExample 1:\n\nInput: nums = [8,2,4,7], limit = 4\nOutput: 2 \nExplanation: All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 &lt;= 4.\n[8,2] with maximum absolute diff |8-2| = 6 &gt; 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 &gt; 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 &gt; 4.\n[2] with maximum absolute diff |2-2| = 0 &lt;= 4.\n[2,4] with maximum absolute diff |2-4| = 2 &lt;= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 &gt; 4.\n[4] with maximum absolute diff |4-4| = 0 &lt;= 4.\n[4,7] with maximum absolute diff |4-7| = 3 &lt;= 4.\n[7] with maximum absolute diff |7-7| = 0 &lt;= 4. \nTherefore, the size of the longest subarray is 2.\n\n\nExample 2:\n\nInput: nums = [10,1,2,4,7,2], limit = 5\nOutput: 4 \nExplanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 &lt;= 5.\n\n\nExample 3:\n\nInput: nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\t0 &lt;= limit &lt;= 109\n\n",
        "solution_py": "# max absolte diff within a subarray is subarray max substracted by subarray min\nclass Solution:\n    def longestSubarray(self, nums: List[int], limit: int) -> int:\n        q = collections.deque() # monotonic decreasing deque to compute subarray max, index of\n        q2 = collections.deque() # monotonic increasing deque to compute subarray min, index of\n        \n        # sliding window\n        res = left = 0\n        for right in range(len(nums)):\n            # pop monotocity-violating numbers from right end\n            while q and nums[q[-1]] <= nums[right]:\n                q.pop()\n            q.append(right)\n            \n            # pop monotocity-violating numbers from right end\n            while q2 and nums[q2[-1]] >= nums[right]:\n                q2.pop()\n            q2.append(right)\n            \n            # sliding window\n            while left < right and q and q2 and nums[q[0]] - nums[q2[0]] > limit:\n                # compress window from left pointer\n                if q and q[0] == left:\n                    q.popleft()\n                \n                # compress left pointer\n                if q2 and q2[0] == left:\n                    q2.popleft()\n                    \n                left += 1\n            \n            if nums[q[0]] - nums[q2[0]] <= limit:\n                res = max(res, right - left + 1)\n        \n        return res",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nvar longestSubarray = function(nums, limit) {\n    const maxQueue = [];\n    const minQueue = [];\n    let start = 0;\n    let res = 0;\n    for(let end = 0; end < nums.length; end ++) {\n        const num = nums[end];\n        while(maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < num) {\n            maxQueue.pop();\n        }\n\n        while(minQueue.length > 0 && minQueue[minQueue.length - 1] > num) {\n            minQueue.pop();\n        }\n        maxQueue.push(num);\n        minQueue.push(num);\n        if(maxQueue[0] - minQueue[0] > limit) {\n            if(maxQueue[0] === nums[start]) {\n                maxQueue.shift();\n            }\n\n            if(minQueue[0] === nums[start]) {\n                minQueue.shift();\n            }\n\n            start +=1;\n        }\n        res = Math.max(res, end - start + 1);\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    \n    public int longestSubarray(int[] nums, int limit) {\n        \n        Deque<Integer> increasing = new LinkedList<Integer>(); // To keep track of Max_value index\n        Deque<Integer> decreasing = new LinkedList<Integer>(); // To keep track of Min_value index\n        \n        int i = 0 ;\n        int j = 0 ;\n        int max_length = 0 ;\n        \n        while(j < nums.length){\n            \n            while(!increasing.isEmpty() && nums[increasing.peekLast()] >= nums[j]){\n                increasing.pollLast() ;\n            }\n            \n            increasing.add(j);\n            \n            while(!decreasing.isEmpty() && nums[decreasing.peekLast()] <= nums[j]){\n                decreasing.pollLast() ;\n            }\n            \n            decreasing.add(j);\n            \n            int max_val = nums[decreasing.peekFirst()] ;\n            int min_val = nums[increasing.peekFirst()] ;\n            \n            if(max_val-min_val <= limit){\n                max_length = Math.max(max_length , j-i+1);\n            }else{\n                \n                // If maximum absolute diff > limit , then remove from dequeue and increase i\n                while(i<=j  && nums[decreasing.peekFirst()] - nums[increasing.peekFirst()] > limit ){\n                    \n                    if(!increasing.isEmpty() && increasing.peekFirst() == i){\n                        increasing.pollFirst() ;\n                    }\n                \n                    if(!decreasing.isEmpty() && decreasing.peekFirst() == i){\n                        decreasing.pollFirst() ;\n                    }\n                \n                    i++ ; \n                }                \n                               \n            }\n            \n            \n            j++ ;\n        }\n        \n        return max_length ;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestSubarray(vector<int>& nums, int limit) {\n\n        int max_ans = 0;\n        map <int, int> mp;\n        int j = 0;\n        for(int i = 0 ; i < nums.size() ; i++) {\n\n            mp[nums[i]] ++;\n\n            while( mp.size() > 0 && abs(mp.rbegin()->first - mp.begin()->first) > limit)\n            {\n\n                if(mp[nums[j]] > 0) {\n                    mp[nums[j]] --;\n                }\n\n                if(mp[nums[j]] == 0) {\n\n                    mp.erase(nums[j]);\n                }\n\n                j++;\n            }\n\n            max_ans = max(max_ans, i - j + 1);\n        }\n\n        return max_ans;\n    }\n};"
    },
    {
        "title": "Parsing A Boolean Expression",
        "algo_input": "Return the result of evaluating a given boolean expression, represented as a string.\n\nAn expression can either be:\n\n\n\t\"t\", evaluating to True;\n\t\"f\", evaluating to False;\n\t\"!(expr)\", evaluating to the logical NOT of the inner expression expr;\n\t\"&amp;(expr1,expr2,...)\", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;\n\t\"|(expr1,expr2,...)\", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...\n\n\n&nbsp;\nExample 1:\n\nInput: expression = \"!(f)\"\nOutput: true\n\n\nExample 2:\n\nInput: expression = \"|(f,t)\"\nOutput: true\n\n\nExample 3:\n\nInput: expression = \"&amp;(t,f)\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= expression.length &lt;= 2 * 104\n\texpression[i] consists of characters in {'(', ')', '&amp;', '|', '!', 't', 'f', ','}.\n\texpression is a valid expression representing a boolean, as given in the description.\n\n",
        "solution_py": "class Solution:\n    def parseBoolExpr(self, expression: str) -> bool:\n        \n        # expresssion map\n        opMap = {\"!\" : \"!\", \"|\" : \"|\" , \"&\" : \"&\"}\n        expMap = {\"t\" : True, \"f\" : False}\n        expStack = []\n        opStack = []\n        ans = 0\n        i = 0\n        \n        while i < len(expression):\n            \n            if expression[i] in opMap:\n                opStack.append(opMap[expression[i]])\n            \n            elif expression[i] in expMap:\n                expStack.append(expMap[expression[i]])\n                \n            elif expression[i] == \"(\":\n                expStack.append(\"(\")\n            \n            # strat performing operations\n            elif expression[i] == \")\":\n                op = opStack.pop()\n                ans = [] # evaluator arr\n                \n                # To Check\n                # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"outer WHILE\")\n                \n                # Performing serries of operation on exp inside a ()\n                while expStack[-1] != \"(\":\n                    \n                    # To check \n                    # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"OPerator :- \",op, \"INNER WHILE\")\n    \n                    # Not single operation only\n                    if op == \"!\":\n                        ans.append(not expStack.pop())\n                    else:\n                        ans.append(expStack.pop())\n                \n                # Operation evaluation for more then 1 exp inside () for &, or\n                while len(ans) > 1:\n                    # or\n                    if op == \"|\":\n                        exp1, exp2 = ans.pop(), ans.pop()\n                        res = exp1 or exp2\n                        ans.append(res)\n                    # and\n                    elif op == \"&\":\n                        exp1, exp2 = ans.pop(), ans.pop()\n                        res = exp1 and exp2\n                        ans.append(res)\n                    \n                # poping \")\" and adding the res of operation done above\n                expStack.pop() # poping \")\"\n                expStack.append(ans[-1])\n                        \n            # increment i   \n            i += 1\n                \n        return expStack[-1]\n    \n    \n\"\"\"\nTC : O(n * m) | n = len(expression), m = no of expression inside a prenthesis\nSc : O(n)\n\"\"\"",
        "solution_js": "var parseBoolExpr = function(expression) {\n    let sol, stack = [],\n        op={t:true, f:false};\n    for(let i=0; i<expression.length; i++){\n        if(expression[i] != \")\"){\n            if(expression[i]!==\",\")stack.push(expression[i]);\n        }else{\n            let findings = [], ko;;\n             while(stack.slice(-1)[0] !== \"(\"){\n                findings.push(stack.pop());\n            }\n            stack.pop();\n            let operator = stack.pop();\n            if(operator == '|'){\n                ko=findings.reduce((a,b)=>(op[a]||op[b]) === true?'t':'f');\n            }\n            if(operator == '&'){\n                ko=findings.reduce((a,b)=>(op[a]&&op[b]) === true?'t':'f');\n            }\n            if(operator == '!'){\n                ko=findings.pop()==='f'?'t':'f';\n            }\n            stack.push(ko);\n        }\n\n    }\n    return stack.pop()=='f'?false:true;\n};",
        "solution_java": "class Solution {\n    \n    int pos = 0;\n    \n    public boolean parseBoolExpr(String s) {\n        pos = 0;\n        return solve(s, '-');\n    }\n    \n    public boolean solve(String s, char prev_sign) {\n       \n        boolean res = s.charAt(pos) == 'f' ? false : true;\n        char cur_sign = ' ';\n        int flag_res_init = 0;\n        while(pos < s.length()) {\n            \n            char cur_char = s.charAt(pos++);\n            \n            if(isExpr(cur_char)){\n                res = eval(cur_char == 't'?true:false, res , prev_sign);\n            }\n            else if(isSign(cur_char)){\n                cur_sign = cur_char;\n            }\n            else if(cur_char == '('){\n                if(flag_res_init == 1 || prev_sign == '!')\n                    res = eval(solve(s, cur_sign), res, prev_sign);\n                else {\n                    res = solve(s, cur_sign);\n                    flag_res_init = 1;\n                }\n            }\n            else if(cur_char == ')'){\n                 return res;\n            }\n            \n        }\n       return res;\n    }\n    \n    public boolean isExpr(char c){\n        return (c == 'f' || c == 't');\n    }\n    \n    public boolean isSign(char c){\n        return (c == '!' || c == '&' || c == '|');\n    }\n    \n    public boolean eval(boolean e1, boolean e2, char sign) {\n     \n        boolean res = false;\n        if(sign == '!')\n            res = !e1;\n        \n        else if(sign == '|')\n            res = e1 | e2;\n        \n        else if(sign == '&')\n            res = e1&e2;\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\n    pair<bool,int> dfs(string &e, int idx){\n        bool res;\n        if(e[idx]=='!'){\n            auto [a,b]=dfs(e, idx+2);\n            return {!a,b+3};\n        }else if(e[idx]=='&'){\n            int len=2;\n            res=true;\n            idx+=2;\n            while(e[idx]!=')'){\n                if(e[idx]==','){\n                    idx++;len++;\n                }\n                auto [a,b]=dfs(e,idx);\n                res&=a;\n                idx+=b;\n                len+=b;\n            }\n            return {res,len+1};\n        }else if(e[idx]=='|'){\n            int len=2;\n            res=false;\n            idx+=2;\n            while(e[idx]!=')'){\n                if(e[idx]==','){\n                    idx++;len++;\n                }\n                auto [a,b]=dfs(e,idx);\n                res|=a;\n                idx+=b;\n                len+=b;\n            }\n            return {res,len+1};\n        }else{\n            return {e[idx]=='t',1};\n        }\n    }\npublic:\n    bool parseBoolExpr(string expression) {\n        return dfs(expression, 0).first;\n    }\n};"
    },
    {
        "title": "Design a Stack With Increment Operation",
        "algo_input": "Design a stack which supports the following operations.\n\nImplement the CustomStack class:\n\n\n\tCustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.\n\tvoid push(int x)&nbsp;Adds x to the top of the stack if the stack hasn't reached the maxSize.\n\tint pop()&nbsp;Pops and returns the top of stack or -1 if the stack is empty.\n\tvoid inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]\nOutput\n[null,null,null,2,null,null,null,null,null,103,202,201,-1]\nExplanation\nCustomStack customStack = new CustomStack(3); // Stack is Empty []\ncustomStack.push(1);                          // stack becomes [1]\ncustomStack.push(2);                          // stack becomes [1, 2]\ncustomStack.pop();                            // return 2 --&gt; Return top of the stack 2, stack becomes [1]\ncustomStack.push(2);                          // stack becomes [1, 2]\ncustomStack.push(3);                          // stack becomes [1, 2, 3]\ncustomStack.push(4);                          // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100);                // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100);                // stack becomes [201, 202, 103]\ncustomStack.pop();                            // return 103 --&gt; Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop();                            // return 202 --&gt; Return top of the stack 102, stack becomes [201]\ncustomStack.pop();                            // return 201 --&gt; Return top of the stack 101, stack becomes []\ncustomStack.pop();                            // return -1 --&gt; Stack is empty return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= maxSize &lt;= 1000\n\t1 &lt;= x &lt;= 1000\n\t1 &lt;= k &lt;= 1000\n\t0 &lt;= val &lt;= 100\n\tAt most&nbsp;1000&nbsp;calls will be made to each method of increment, push and pop each separately.\n\n",
        "solution_py": "\tclass CustomStack:\n\n\t\tdef __init__(self, maxSize: int):\n\t\t\tself.size = maxSize\n\t\t\tself.stack = []\n\n\t\tdef push(self, x: int) -> None:\n\t\t\tif self.size > len(self.stack):\n\t\t\t\tself.stack.append(x)\n\n\t\tdef pop(self) -> int:\n\t\t\tif self.stack:\n\t\t\t\treturn self.stack.pop()\n\t\t\treturn -1\n\n\t\tdef increment(self, k: int, val: int) -> None:\n\t\t\tlen_stack = len(self.stack)\n\n\t\t\tif len_stack < k:\n\t\t\t\tself.stack[:] = [i + val for i in self.stack]\n\t\t\t\treturn\n\n\t\t\tfor i in range(k):\n\t\t\t\tself.stack[i] += val",
        "solution_js": "var CustomStack = function(maxSize) {\n    this.stack = new Array(maxSize).fill(-1);\n    this.maxSize = maxSize;\n    this.size = 0;\n};\n\nCustomStack.prototype.push = function(x) {\n    if(this.size < this.maxSize){\n        this.stack[this.size] = x;\n        this.size++;\n    }\n};\n\nCustomStack.prototype.pop = function() {\n    if(this.size > 0){\n        this.size--;\n        return this.stack[this.size];\n    }\n    return -1;\n};\n\nCustomStack.prototype.increment = function(k, val) {\n    let count = k >= this.size ? this.size-1 : k-1;\n\n    while(count >= 0){\n        this.stack[count] += val;\n        count--;\n    }\n};",
        "solution_java": "class CustomStack {\n\n    int[] stack;\n    int top;\n\n    public CustomStack(int maxSize) {\n\n        //intialise the stack and the top\n         stack= new int[maxSize];\n        top=-1;\n    }\n\n    public void push(int x) {\n\n        // if the stack is full just skip\n        if( top==stack.length-1) return;\n\n        //add to the stack\n        top++;\n        stack[top]=x;\n    }\n\n    public int pop() {\n\n        //if stack is empty return -1\n        if( top==-1) return -1;\n\n        //remove/pop the top element\n        top--;\n        return stack[top+1];\n\n    }\n\n    public void increment(int k, int val) {\n\n        //got to increment the min of the elements present in the stack and k\n        int n= Math.min(top+1,k);\n\n        for( int i=0; i<n ; i++){\n            stack[i]+=val;\n        }\n\n    }\n}",
        "solution_c": "class CustomStack {\n    int *data;\n    int nextIndex;\n    int capacity;\npublic:\n    CustomStack(int maxSize) {\n        data = new int[maxSize];\n        nextIndex = 0;\n        capacity = maxSize;\n    }\n\n    void push(int x) {\n        if(nextIndex == capacity){\n            return;\n        }\n        data[nextIndex] = x;\n        nextIndex++;\n    }\n\n    int pop() {\n        if(nextIndex == 0){\n            return -1;\n        }\n        int temp = data[nextIndex-1];\n        nextIndex--;\n        return temp;\n    }\n\n    void increment(int k, int val) {\n        //loop will run upto nextIndex if k >= nextIndex else runt upto k only\n        int n = (k >= nextIndex) ? nextIndex : k;\n        for(int i = 0; i < n; i++){\n            data[i] = data[i] + val;\n        }\n    }\n};"
    },
    {
        "title": "Ambiguous Coordinates",
        "algo_input": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s.\n\n\n\tFor example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\".\n\n\nReturn a list of strings representing all possibilities for what our original coordinates could have been.\n\nOur original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\".\n\nThe final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)\n\n&nbsp;\nExample 1:\n\nInput: s = \"(123)\"\nOutput: [\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]\n\n\nExample 2:\n\nInput: s = \"(0123)\"\nOutput: [\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\nExplanation: 0.0, 00, 0001 or 00.01 are not allowed.\n\n\nExample 3:\n\nInput: s = \"(00011)\"\nOutput: [\"(0, 0.011)\",\"(0.001, 1)\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t4 &lt;= s.length &lt;= 12\n\ts[0] == '(' and s[s.length - 1] == ')'.\n\tThe rest of s are digits.\n\n",
        "solution_py": "class Solution(object):\n    def ambiguousCoordinates(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: List[str]\n        \"\"\"\n        def _isValidSplit(s):\n            return False if len(s)>1 and re.match('/^[0]+$/',s) else True\n\n        def _isValidNum(ipart,fpart):\n            return False if (len(ipart)>1 and ipart[0]=='0') or (fpart and fpart[-1]=='0') else True\n\n        def _splitToNums(s):\n            rets=[]\n            if len(s)==1:return [s]\n            for i in range(1,len(s)+1):\n                a,b=s[:i],s[i:]\n                if _isValidNum(a,b):rets.append(\"%s.%s\"%(a,b) if b else \"%s\"%(a))\n            return rets\n\n        ans,s=[],s[1:-1]\n        for i in range(1,len(s)):\n            a,b=s[:i],s[i:]\n            if not _isValidSplit(a) or not _isValidSplit(b):continue\n            for c1,c2 in itertools.product(_splitToNums(a),_splitToNums(b)):ans.append(\"(%s, %s)\"%(c1,c2))\n        return ans",
        "solution_js": "var ambiguousCoordinates = function(S) {\n    let ans = [], xPoss\n    const process = (str, xy) => {\n        if (xy)\n            for (let x of xPoss)\n                ans.push(`(${x}, ${str})`)\n        else xPoss.push(str)\n    }\n    const parse = (str, xy) => {\n        if (str.length === 1 || str[0] !== \"0\")\n            process(str, xy)\n        if (str.length > 1 && str[str.length-1] !== \"0\")\n            process(str.slice(0,1) + \".\" + str.slice(1), xy)\n        if (str.length > 2 && str[0] !== \"0\" && str[str.length-1] !== \"0\")\n            for (let i = 2; i < str.length; i++)\n                process(str.slice(0,i) + \".\" + str.slice(i), xy)\n    }\n    for (let i = 2; i < S.length - 1; i++) {\n        let strs = [S.slice(1,i), S.slice(i, S.length - 1)]\n        xPoss = []\n        for (let j = 0; j < 2; j++)\n            if (xPoss.length || !j) parse(strs[j], j)\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public List<String> ret;\n    public List<String> ans;\n    public List<String> ambiguousCoordinates(String s) {\n        ret=new ArrayList<>();\n        ans=new ArrayList<>();\n        String start=s.substring(0,2);\n        util(s,1);\n        fun();\n        return ans;\n    }\n    \n    //putting comma\n    void util(String s,int idx) {\n        if(idx==s.length()-2) {\n            return;\n        }\n        \n        String ns=s.substring(0,idx+1)+\", \"+s.substring(idx+1);\n        ret.add(ns);\n        util(s,idx+1);\n    }\n    \n    //helper function for puting decimals after comma\n    void fun() {\n        for(String s:ret) {\n            int cIndex=0;\n            for(int i=0;i<s.length();i++) {\n                if(s.charAt(i)==',') {\n                    cIndex=i;\n                    break;\n                }\n            }\n            String a=s.substring(1,cIndex);\n            String b=s.substring(cIndex+2,s.length()-1);\n            List<String> n1=dot(a);\n            List<String> n2=dot(b);\n            if(n1==null || n2==null) { //invalid strings\n                continue;\n            }else { //valid strings\n                for(String fir:n1) {\n                    for(String sec:n2) {\n                        ans.add(\"(\"+fir+\", \"+sec+\")\");\n                    }\n                }\n            }\n        }\n    }\n    \n    //putting decimal point\n    List<String> dot(String n) {\n        List<String> li=new ArrayList<>();\n        if(n.length()==1) {\n            li.add(n);\n        }else {\n            \n            //just checking for first and last zeroes and making conditions accordingly\n\n            if(n.charAt(n.length()-1)=='0') {\n                if(n.charAt(0)=='0') {\n                    return null;\n                }else {\n                    li.add(n);\n                }\n            }else if(n.charAt(0)=='0') {\n                li.add(\"0.\"+n.substring(1));\n            }else {\n                for(int i=0;i<n.length()-1;i++) {\n                    li.add(n.substring(0,i+1)+\".\"+n.substring(i+1));\n                }\n                li.add(n);  //without any decimal\n            }\n        }\n        return li;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> check(string s){\n        int n = s.size();\n        vector<string> res;\n        if(s[0] == '0'){\n            if(n == 1)\n                res.push_back(s);\n            else{\n                if(s[n-1] == '0')\n                    return res;\n                \n                s.insert(1, \".\");\n                res.push_back(s);\n            }\n        }\n        else{\n            if(s[n-1] == '0'){\n                res.push_back(s);\n                return res;\n            }\n            \n            for(int i=1; i<n; i++){\n                string t = s.substr(0, i) + \".\" + s.substr(i, n-i);\n                res.push_back(t);\n            }\n            res.push_back(s);\n        }\n        \n        return res;\n    }\n    vector<string> ambiguousCoordinates(string s) {\n        int n = s.size();\n        vector<string> res;\n        \n        for(int i=2; i<n-1; i++){\n            vector<string> left = check(s.substr(1, i-1));\n            vector<string> right = check(s.substr(i, n-i-1));\n            for(int j=0; j<left.size(); j++){\n                for(int k=0; k<right.size(); k++){\n                    string t = \"(\" + left[j] + \", \" + right[k] + \")\";\n                    res.push_back(t);\n                }\n            }\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Shuffle String",
        "algo_input": "You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.\n\nReturn the shuffled string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\nOutput: \"leetcode\"\nExplanation: As shown, \"codeleet\" becomes \"leetcode\" after shuffling.\n\n\nExample 2:\n\nInput: s = \"abc\", indices = [0,1,2]\nOutput: \"abc\"\nExplanation: After shuffling, each character remains in its position.\n\n\n&nbsp;\nConstraints:\n\n\n\ts.length == indices.length == n\n\t1 &lt;= n &lt;= 100\n\ts consists of only lowercase English letters.\n\t0 &lt;= indices[i] &lt; n\n\tAll values of indices are unique.\n\n",
        "solution_py": "class Solution:\n    def restoreString(self, s: str, indices: List[int]) -> str:\n        dec = {}\n        c = 0\n        res=''\n        for i in indices:\n            dec[i] = s[c]\n            c += 1\n        # dec = {\"4\":\"c\",\"5\":\"o\",\"6\":\"d\",\"7\":\"e\",\"0\":\"l\",\"2\":\"e\",\"1\":\"e\",\"3\":\"t\"}\n        for x in range(len(indices)):\n            res += dec[x]\n            # x in range 0, 1, 2,....... len *indices or s*\n        return res",
        "solution_js": "var restoreString = function(s, indices) {\n    const result = []\n    \n    for(let i=0; i<s.length; i++) {\n        const letter = s[i]\n        const index = indices[i]\n        result[index] = letter\n    }\n    \n    return result.join('')\n};",
        "solution_java": "class Solution {\n    public String restoreString(String s, int[] indices) {\n        char[] ch = new char[s.length()];\n        for(int i = 0 ; i< s.length() ; i ++){\n            ch[indices[i]]=s.charAt(i);\n        }\n        return new String (ch);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string restoreString(string s, vector<int>& indices) {\n\n        string ans = s;\n\n        for(int i=0 ; i<s.size() ; i++){\n            ans[indices[i]] = s[i];\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Build an Array With Stack Operations",
        "algo_input": "You are given an integer array target and an integer n.\n\nYou have an empty stack with the two following operations:\n\n\n\t\"Push\": pushes an integer to the top of the stack.\n\t\"Pop\": removes the integer on the top of the stack.\n\n\nYou also have a stream of the integers in the range [1, n].\n\nUse the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:\n\n\n\tIf the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.\n\tIf the stack is not empty, pop the integer at the top of the stack.\n\tIf, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.\n\n\nReturn the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.\n\n&nbsp;\nExample 1:\n\nInput: target = [1,3], n = 3\nOutput: [\"Push\",\"Push\",\"Pop\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].\n\n\nExample 2:\n\nInput: target = [1,2,3], n = 3\nOutput: [\"Push\",\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].\n\n\nExample 3:\n\nInput: target = [1,2], n = 4\nOutput: [\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target.length &lt;= 100\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= target[i] &lt;= n\n\ttarget is strictly increasing.\n\n",
        "solution_py": "class Solution:\n    def buildArray(self, target: List[int], n: int) -> List[str]:\n        temp = []\n        result = []\n        x = target[-1]\n        for i in range(1,x+1):\n            temp.append(i)\n        for i in range(len(temp)):\n            if temp[i] in target:\n                result.append(\"Push\")\n            elif temp[i] not in target:\n                result.append(\"Push\")\n                result.append(\"Pop\")\n        return result",
        "solution_js": "/**\n * @param {number[]} target\n * @param {number} n\n * @return {string[]}\n */\nvar buildArray = function(target, n) {\n    let arr = [];\n    let index = 0;\n    for(let i = 1; i <= target[target.length-1];i++){\n        if(target[index] == i){\n            arr.push('Push');\n            index++;\n        }else{\n            arr.push('Push');\n            arr.push('Pop');\n        }\n    }\n    return arr;\n};",
        "solution_java": "class Solution {\n    public List<String> buildArray(int[] target, int n) {\n      List<String> result=new ArrayList<>();\n        int i=1,j=0;\n        while(j<target.length)\n        {\n            result.add(\"Push\");\n            if(i==target[j]){\n                j++;\n            }else{\n                result.add(\"Pop\");\n            }\n            i++;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> buildArray(vector<int>& target, int n) {\n        vector<string>ans;\n        int l=target.size(), count=0,ind=0; // ind is index of the target array\n\n        for(int i=1;i<=n;i++){\n            if(count==l) break;\n            if(target[ind]!=i){\n                ans.push_back(\"Push\");\n                ans.push_back(\"Pop\");\n            }\n            else{\n                ans.push_back(\"Push\");\n                count++;\n                ind++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Delete Node in a BST",
        "algo_input": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.\n\nBasically, the deletion can be divided into two stages:\n\n\n\tSearch for a node to remove.\n\tIf the node is found, delete the node.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [5,3,6,2,4,null,7], key = 3\nOutput: [5,4,6,2,null,null,7]\nExplanation: Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.\n\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,7], key = 0\nOutput: [5,3,6,2,4,null,7]\nExplanation: The tree does not contain a node with value = 0.\n\n\nExample 3:\n\nInput: root = [], key = 0\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\tEach node has a unique value.\n\troot is a valid binary search tree.\n\t-105 &lt;= key &lt;= 105\n\n\n&nbsp;\nFollow up: Could you solve it with time complexity O(height of tree)?\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\ndef deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n\ndef find_inorder(root, key):\n\n\tif root is None :\n\t\treturn []\n\n\treturn find_inorder(root.left, key) + [root.val] + find_inorder(root.right, key)\n\ndef find_preorder(root, key):\n\n\tif root is None:\n\t\treturn []\n\n\treturn [root.val] + find_preorder(root.left,key) + find_preorder(root.right, key)\n\npreorder = find_preorder(root, key)\n\ntry:\n\tpreorder.remove(key)\nexcept:\n\treturn root\n\ninorder = find_inorder(root, key)\n\ninorder.remove(key)\n\n\n\n\nhashmap = {}\n\nfor i in range(len(inorder)):\n\tkey = inorder[i]\n\thashmap[key] = i\n\ndef buildTree(left, right):\n\n\tif left > right:\n\t\treturn \n\n\tval = inorder[left]\n\troot = TreeNode(val)\n\n\tindex = hashmap[val]\n\n\troot.left = buildTree(left, index-1)\n\troot.right = buildTree(index+1, right)\n\n\treturn root\n\nN = len(inorder)\nnew_tree = buildTree(0,N-1)\n\nreturn new_tree",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n\nconst getLeftMostNode=(root)=>{\n    if(!root)return null;\n    let node=getLeftMostNode(root.left);\n    return node?node:root;\n}\n/**\n * @param {TreeNode} root\n * @param {number} key\n * @return {TreeNode}\n */\n\n\nvar deleteNode = function(root, key) {\n    if(!root)return null;\n    if(root.val>key){\n    root.left=deleteNode(root.left,key);\n    }else if(root.val<key){\n    root.right= deleteNode(root.right,key);\n    }else{\n        if(!root.left)return root.right;\n        if(!root.right)return root.left;\n        let succ_node=getLeftMostNode(root.right);\n        root.val=succ_node.val;\n        root.right= deleteNode(root.right,succ_node.val);\n        \n    }\n    return root;\n\n};",
        "solution_java": "class Solution {\n    public TreeNode deleteNode(TreeNode root, int key) {\n        if(root==null) return null;\n        \n        if(key<root.val){                            \n            root.left = deleteNode(root.left,key);\n            return root;\n        }\n        \n        else if(key>root.val){\n            root.right = deleteNode(root.right,key);\n            return root;\n        }\n        \n        else{\n            if(root.left==null){\n                return root.right;\n            }\n            else if(root.right==null){\n                return root.left;\n            }\n            else{\n                TreeNode min = root.right;\n                while(min.left!=null){\n                    min = min.left;\n                }\n                \n                root.val = min.val;\n                root.right = deleteNode(root.right,min.val);\n                return root;\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* deleteNode(TreeNode* root, int key) {\n        if(root) \n            if(key < root->val) root->left = deleteNode(root->left, key);     //We frecursively call the function until we find the target node\n            else if(key > root->val) root->right = deleteNode(root->right, key);       \n            else{\n                if(!root->left && !root->right) return NULL;          //No child condition\n                if (!root->left || !root->right)\n                    return root->left ? root->left : root->right;    //One child contion -> replace the node with it's child\n\t\t\t\t\t                                                //Two child condition   \n                TreeNode* temp = root->left;                        //(or) TreeNode *temp = root->right;\n                while(temp->right != NULL) temp = temp->right;     //      while(temp->left != NULL) temp = temp->left;\n                root->val = temp->val;                            //       root->val = temp->val;\n                root->left = deleteNode(root->left, temp->val);  //        root->right = deleteNode(root->right, temp);\t\t\n            }\n        return root;\n    }   \n};"
    },
    {
        "title": "Relative Ranks",
        "algo_input": "You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.\n\nThe athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:\n\n\n\tThe 1st place athlete's rank is \"Gold Medal\".\n\tThe 2nd place athlete's rank is \"Silver Medal\".\n\tThe 3rd place athlete's rank is \"Bronze Medal\".\n\tFor the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is \"x\").\n\n\nReturn an array answer of size n where answer[i] is the rank of the ith athlete.\n\n&nbsp;\nExample 1:\n\nInput: score = [5,4,3,2,1]\nOutput: [\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\nExplanation: The placements are [1st, 2nd, 3rd, 4th, 5th].\n\nExample 2:\n\nInput: score = [10,3,8,9,4]\nOutput: [\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\nExplanation: The placements are [1st, 5th, 3rd, 2nd, 4th].\n\n\n\n&nbsp;\nConstraints:\n\n\n\tn == score.length\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= score[i] &lt;= 106\n\tAll the values in score are unique.\n\n",
        "solution_py": "class Solution:\n    def findRelativeRanks(self, score: List[int]) -> List[str]:\n        scores_ids = []\n        for i in range(len(score)):\n            scores_ids.append((score[i], i))\n        scores_ids.sort(reverse=True)\n\n        ans = [0] * len(scores_ids)\n        for i in range(len(scores_ids)):\n            ans[scores_ids[i][1]] = str(i+1)\n\n        try:\n            ans[scores_ids[0][1]] = \"Gold Medal\"\n            ans[scores_ids[1][1]] = \"Silver Medal\"\n            ans[scores_ids[2][1]] = \"Bronze Medal\"\n        except:\n            pass\n\n        return ans",
        "solution_js": "var findRelativeRanks = function(score) {\n    let output=score.slice(0);\n    let map={};\n    score.sort((a,b)=>b-a).forEach((v,i)=>map[v]=i+1);\n    for(let item in map){\n        if(map[item]==1){map[item]=\"Gold Medal\"};\n        if(map[item]==2){map[item]=\"Silver Medal\"};\n        if(map[item]==3){map[item]=\"Bronze Medal\"};\n    }\n    return output.map(v=>map[v]+\"\"); // +\"\": num=>str.\n};",
        "solution_java": "class Solution {\n    public String[] findRelativeRanks(int[] score) {\n        String[] res = new String[score.length];\n        TreeMap<Integer, Integer> map = new TreeMap<>();\n        for(int i = 0; i < score.length; i++)   map.put(score[i], i);\n        int rank = score.length;\n        for(Map.Entry<Integer, Integer> p: map.entrySet()){\n            if(rank == 1)   res[p.getValue()] = \"Gold Medal\";\n            else if(rank == 2)   res[p.getValue()] = \"Silver Medal\";\n            else if(rank == 3)   res[p.getValue()] = \"Bronze Medal\";\n            else    res[p.getValue()] = String.valueOf(rank);\n            rank--;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> findRelativeRanks(vector<int>& score) {\n        int n=score.size();\n        vector<string> vs(n);\n        unordered_map<int,int> mp;\n        for(int i=0; i<score.size(); i++){\n            mp[score[i]]=i;\n        }\n        sort(score.begin(),score.end(),greater<int>());\n        for(int i=0; i<score.size(); i++){\n            int temp=mp[score[i]];\n            if(i==0){\n                vs[temp]=\"Gold Medal\";\n                continue;\n            }\n            if(i==1){\n                vs[temp]=\"Silver Medal\";\n                continue;\n            }\n            if(i==2){\n                 vs[temp]=\"Bronze Medal\";\n                 continue;\n            }\n            int t=i+1;\n            string st= to_string(t);\n            vs[temp]=st;\n        }\n        return vs;\n    }\n};"
    },
    {
        "title": "Number of Smooth Descent Periods of a Stock",
        "algo_input": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.\n\nA smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule.\n\nReturn the number of smooth descent periods.\n\n&nbsp;\nExample 1:\n\nInput: prices = [3,2,1,4]\nOutput: 7\nExplanation: There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition.\n\n\nExample 2:\n\nInput: prices = [8,6,7,7]\nOutput: 4\nExplanation: There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.\n\n\nExample 3:\n\nInput: prices = [1]\nOutput: 1\nExplanation: There is 1 smooth descent period: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 105\n\t1 &lt;= prices[i] &lt;= 105\n\n",
        "solution_py": "import sys\nclass Solution:\n    def getDescentPeriods(self, prices: List[int]) -> int: \n        def calculate(k,ans):\n            if k>1:\n                ans+=((k-1)*(k))//2 \n\t\t\t\t#Sum of Natural Numbers\n                return ans\n            else:\n                return ans\n        end = 0\n        start = 0\n        prev= sys.maxsize\n        k= 0\n        ans = 0\n        while end<len(prices):     \n            if prev- prices[end]==1 or prev == sys.maxsize:\n                k+=1\n                prev = prices[end]\n                end+=1    \n            else:             \n                ans = calculate(k,ans)\n                start = end\n                if end<len(prices):\n                    prev = sys.maxsize\n                k=0\n        if k>1:\n            ans = calculate(k,ans)\n\t\t\t\n        return ans+len(prices)",
        "solution_js": "var getDescentPeriods = function(prices) {\n    const n = prices.length;\n\n    let left = 0;\n    let totRes = 0;\n\n    while (left < n) {\n        let count = 1;\n\n        let right = left + 1;\n\n        while (right < n && prices[right] + 1 === prices[right - 1]) {\n            count += (right - left + 1);\n            ++right;\n        }\n\n        totRes += count;\n\n        left = right;\n    }\n\n    return totRes;\n};",
        "solution_java": "class Solution {\n    public long getDescentPeriods(int[] prices) {\n        int i=0;\n        int j=1;\n        long ans=1;\n        while(j<prices.length){\n            if( prices[j-1]-prices[j]==1){\n            //It means that j(current element) can be part of previous subarrays (j-i)\n            //and can also start a subarray from me (+1). So add (j-i+1) in total Subarrays\n                int count=j-i+1;\n                ans+=count;\n            }else{\n            //It means that j cannot be part of previous subarrays but can start subarray from me. So, ans+=1\n                i=j;\n                ans+=1;\n            }\n            j++;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long getDescentPeriods(vector<int>& prices) {\n        long long ans = 0;\n        long long temp = 0;\n        for(int i=1; i<prices.size(); i++){\n            if(prices[i - 1] - prices[i] == 1){\n                temp++;\n                ans += temp;\n            }\n            else{\n                temp = 0;\n            }\n        }\n        ans += prices.size();\n        return ans;\n    }\n};"
    },
    {
        "title": "Reachable Nodes In Subdivided Graph",
        "algo_input": "You are given an undirected graph (the \"original graph\") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.\n\nThe graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.\n\nTo subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].\n\nIn this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.\n\nGiven the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.\n\n&nbsp;\nExample 1:\n\nInput: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\nOutput: 13\nExplanation: The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.\n\n\nExample 2:\n\nInput: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\nOutput: 23\n\n\nExample 3:\n\nInput: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\nOutput: 1\nExplanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= edges.length &lt;= min(n * (n - 1) / 2, 104)\n\tedges[i].length == 3\n\t0 &lt;= ui &lt; vi &lt; n\n\tThere are no multiple edges in the graph.\n\t0 &lt;= cnti &lt;= 104\n\t0 &lt;= maxMoves &lt;= 109\n\t1 &lt;= n &lt;= 3000\n\n",
        "solution_py": "class Solution:\n    def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n        m = defaultdict(list)\n        for a, b, p in edges:\n            m[a].append((p, b))\n            m[b].append((p, a))\n\n        vis = set()\n        queue = []\n        heappush(queue, (0, 0))\n        edgevis = set()\n        edgeofl = defaultdict(lambda: 0)\n        ans = 0\n        while queue:\n            # print(queue)\n            cost, cur = heappop(queue)\n            vis.add(cur)\n            for p, nxt in m[cur]:\n                if p < maxMoves - cost:\n                    if (cur, nxt) not in edgevis and (nxt, cur) not in edgevis:\n                        ans += p\n                        # if nxt in vis:\n                        # ans -= 1\n                        edgevis.add((cur, nxt))\n                        edgevis.add((nxt, cur))\n                        if nxt not in vis:\n                            heappush(queue, (cost + p + 1, nxt))\n                else:\n                    bal = maxMoves - cost\n                    if (cur, nxt) in edgevis:\n                        continue\n                    if bal <= edgeofl[(cur, nxt)]:\n                        continue\n                    if bal + edgeofl[(nxt, cur)] < p:\n                        ans += bal - edgeofl[(cur, nxt)]\n                        edgeofl[(cur, nxt)] = bal\n                    else:\n                        ans += p - edgeofl[(nxt, cur)] - edgeofl[(cur, nxt)]\n                        edgevis.add((cur, nxt))\n                        edgevis.add((nxt, cur))\n        return ans + len(vis)",
        "solution_js": "var reachableNodes = function(edges, maxMoves, n) {\n    const g = Array.from({length: n}, () => []);\n    \n    for(let [u, v, cnt] of edges) {\n        g[u].push([v, cnt + 1]);\n        g[v].push([u, cnt + 1]);\n    }\n    \n    // find min budget to reach from 0 to all nodes\n    const budget = new Array(n).fill(Infinity);\n    budget[0] = 0;\n    const dijkstra = () => {\n        // heap will be collection [node, weight]\n        const heap = new MinPriorityQueue({ priority: (x) => x[1] });\n        heap.enqueue([0, 0]);\n        while(heap.size()) {\n            const [n, c] = heap.dequeue().element;\n            for(let [nextNode, cost] of g[n]) {\n                let temp = c + cost;\n                if(budget[nextNode] > temp) {\n                    budget[nextNode] = temp;\n                    heap.enqueue([nextNode, temp]);\n                }\n            }\n        }\n    };\n    dijkstra();\n    \n    // add to sum all reachable nodes from 0 with max move\n    let vis = 0;\n    for(let w of budget) vis += w <= maxMoves;\n\n    // add intermediate nodes between edges with available budget\n    for(let [a, b, c] of edges) {\n        let [availableFromA, availableFromB] = [maxMoves - budget[a], maxMoves - budget[b]];\n        if(availableFromA < 0 || availableFromB < 0) {\n            vis += Math.max(availableFromA, 0) + Math.max(availableFromB, 0);\n        } else {\n            const total = availableFromA + availableFromB;\n            vis += total - Math.max(total - c, 0);\n        }\n    }\n    \n    return vis;\n};",
        "solution_java": "class Solution {\n    public int reachableNodes(int[][] edges, int maxMoves, int n) {\n        int[][] graph = new int[n][n];\n        for ( int[] t: graph ) {\n            Arrays.fill(t, -1);\n        }\n        for ( int[] t: edges ) {\n            graph[t[0]][t[1]] = t[2];\n            graph[t[1]][t[0]] = t[2];\n        }\n        PriorityQueue<int[]> heap = new PriorityQueue<>( (a, b) -> b[1]-a[1] );\n        int ans = 0;\n        boolean[] vis = new boolean[n];\n        heap.offer(new int[]{0, maxMoves});\n        while ( !heap.isEmpty() ) {\n            int[] info = heap.poll();\n            int nearestNodeId = info[0];\n            int maxMovesRemaining = info[1];\n            if ( vis[nearestNodeId] ) {\n                continue;\n            }\n            // visiting the current node\n            vis[nearestNodeId] = true;\n            // since we visited this node we increment our counter\n            ans++;\n            for ( int i=0; i<n; i++ ) {\n                // checking if we do have an edge\n                if ( graph[nearestNodeId][i]!=-1 ) {\n                    if ( !vis[i] && maxMovesRemaining>=graph[nearestNodeId][i]+1 ) {\n                        heap.offer( new int[] {i, maxMovesRemaining-graph[nearestNodeId][i]-1} );\n                    }\n                    int movesTaken = Math.min(maxMovesRemaining, graph[nearestNodeId][i]);\n                    graph[nearestNodeId][i] -= movesTaken;\n                    graph[i][nearestNodeId] -= movesTaken;\n                    ans += movesTaken;\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "  class Solution {\n  public:\n  int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {\n  const int INF = 1e8;\n  vector<vector<pair<int,int>> g(n);\n  for(auto i: edges){\n  g[i[0]].push_back({i[1],i[2]});\n  g[i[1]].push_back({i[0],i[2]});\n  }\n  \n  priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > pq;\n  pq.push({0, 0}); //distance,node\n  vector<int> d(n, INF);\n  d[0] = 0;\n  \n  while(!pq.empty()){\n       int dist = pq.top().first;\n       int node = pq.top().second;\n       pq.pop();\n       //if(d[u.second]!=u.first) continue;\n       for(auto it:g[node]){\n           if(d[it.first]>dist+it.second+1)  //since number of edges=nodes in between+1\n           {\n               d[it.first]=dist+it.second+1;\n               pq.push({d[it.first], it.first});\n           }\n       }\n  }\n  //now we have minimum distances to reach each node, so check how many reachable with minMoves\n  int ans = 0;\n  for(int i = 0; i < n; ++i) { // add 1 for nodes that can be visited\n      if(d[i] <= maxMoves) \n        ans++;   \n   } \n  \n\n  /*\n  Now add for intermediate newly added nodes\n  Eg. 0->1 and 10 in between\n\n  Visitable from 0 -> maxMoves-(dist/moves already covered by 0 (from source)) \n  Visitable from 1 -> maxMoves-(dist/moves already covered by 1 (from source))\n  \n  To calculate Extra nodes I can visit we follow above\n  */\n  for(auto i : edges) {\n      int src=i[0],dest=i[1], between=i[2];\n      int x = max(0, (maxMoves - d[src])); // nodes visited using edge e[0]->e[1]\n      int y = max(0, (maxMoves - d[dest])); // nodes visited using edge e[1]->e[0]\n      ans += min(between, x + y); //minimum to avoid overlapping in counting\n  }\n  return ans;"
    },
    {
        "title": "Random Pick with Weight",
        "algo_input": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.\n\nYou need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).\n\n\n\tFor example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\",\"pickIndex\"]\n[[[1]],[]]\nOutput\n[null,0]\n\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n\n\nExample 2:\n\nInput\n[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\n\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= w.length &lt;= 104\n\t1 &lt;= w[i] &lt;= 105\n\tpickIndex will be called at most 104 times.\n\n",
        "solution_py": "class Solution(object):\n\tdef __init__(self, w):\n\t\t\"\"\"\n\t\t:type w: List[int]\n\t\t\"\"\"\n\t\t#Cumulative sum\n\t\tself.list = [0] * len(w)\n\n\t\ts = 0\n\t\tfor i, n in enumerate(w):\n\t\t\ts += n\n\t\t\tself.list[i] = s\n\n\n\tdef pickIndex(self):\n\t\t\"\"\"\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()",
        "solution_js": "class Solution {\n    constructor(nums) {\n        this.map = new Map();\n        this.sum = 0;\n        \n        nums.forEach((num, i) => {\n            this.sum += num;\n            this.map.set(this.sum, i);\n        })\n    }\n    pickIndex = function() {\n        const random_sum = Math.floor(Math.random() * this.sum);\n        return this.fetchIndexUsingBS(random_sum);\n    }\n    fetchIndexUsingBS = function(target) {\n        const sums = Array.from(this.map.keys());\n        let lo = 0,\n            hi = sums.length - 1,\n            mid;\n        \n        while(lo <= hi) {\n            mid = Math.floor((hi - lo)/2) + lo;\n            // if((mid === 0 || sums[mid - 1] < target) && sums[mid] >= target) {\n            //     return this.map.get(sums[mid]);\n            // }\n            if(sums[mid] > target) {\n                hi = mid - 1;\n            } else {\n                lo = mid + 1;\n            }\n        }\n        return lo;\n    }\n}",
        "solution_java": "class Solution {\n\n    private int[] prefixSum;\n    private Random random;\n\n    public Solution(int[] w) {\n        for (int i = 1; i < w.length; i++)\n            w[i] += w[i - 1];\n        prefixSum = w;\n        random = new Random();\n    }\n\n    public int pickIndex() {\n        int num = 1 + random.nextInt(prefixSum[prefixSum.length - 1]); // Generate random number between 1 and total sum of weights\n        int left = 0;\n        int right = prefixSum.length - 1;\n\n        while (left < right) {\n            int mid = (left + right) / 2;\n            if (num == prefixSum[mid])\n                return mid;\n            else if (num < prefixSum[mid])\n                right = mid;\n            else\n                left = mid + 1;\n        }\n        return left;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> cumW;  \n    Solution(vector<int>& w) {\n        // initialising random seeder\n        srand(time(NULL));\n        // populating the cumulative weights vector\n        cumW.resize(w.size());\n        cumW[0] = w[0];\n        for (int i = 1; i < w.size(); i++) cumW[i] = cumW[i - 1] + w[i];\n    }\n    \n    int pickIndex() {\n        return upper_bound(begin(cumW), end(cumW), rand() % cumW.back()) - begin(cumW);\n    }\n};"
    },
    {
        "title": "Beautiful Arrangement II",
        "algo_input": "Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:\n\n\n\tSuppose this list is answer =&nbsp;[a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.\n\n\nReturn the list answer. If there multiple valid answers, return any of them.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, k = 1\nOutput: [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n\n\nExample 2:\n\nInput: n = 3, k = 2\nOutput: [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt; n &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def constructArray(self, n: int, k: int) -> List[int]:\n        # n = 8, k = 5\n        # 1 2 3 8 4 7 5 6\n        # 1 1 5 4 3 2 1\n        res = list(range(1,n-k+1))\n        sign, val = 1, k\n        for i in range(k):\n            res.append(res[-1]+sign*val)\n            sign *= -1\n            val -= 1\n        return res",
        "solution_js": "var constructArray = function(n, k) {\n    const result = [];\n    let left = 1;\n    let right = n;\n\n    for (let index = 0; index < n; index++) {\n        if (k === 1) {\n            result.push(left++);\n            continue;\n        }\n        const num = k & 1 ? left++ : right--;\n        result.push(num);\n        k -= 1;\n    }\n\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] constructArray(int n, int k) {\n        int [] result = new int[n];\n        result[0] = 1;\n        int sign = 1;\n        for(int i = 1 ; i < n; i++, k--){\n            if(k > 0){\n                result[i] = result[i-1] + k * sign;\n                sign *= -1;\n            }\n            else{\n                result[i] = i+1;\n            }\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> constructArray(int n, int k) {\n        int diff = n - k;\n        int lo = 1;\n        int hi = n;\n        vector<int> out;\n        int i = 0; \n\t\t// we generate a difference of 1 between subsequent elements for the first n-k times.\n        while(i < diff){\n            out.push_back(lo);\n            lo++;\n            i++;\n        }\n        bool flag = true;\n\t\t//Now we go zig zag to generate k unique differences, the last one will be automatically taken care\n\t\t//as the difference between last two elements will be one which we have already generated above.\n        for(int i = out.size()   ; i < n ; i++){\n           //flag to alternatively zig zag\n\t\t   if(flag){\n                out.push_back(hi);\n                hi--;\n                flag = false;\n            }\n            else{\n                out.push_back(lo);\n                lo++;\n                flag = true;\n            }\n        }\n        return out;\n    }\n};"
    },
    {
        "title": "Longest Consecutive Sequence",
        "algo_input": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.\n\nYou must write an algorithm that runs in&nbsp;O(n)&nbsp;time.\n\n&nbsp;\nExample 1:\n\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\n\n\nExample 2:\n\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution(object):\n    def longestConsecutive(self, nums):\n        ans=0\n        nums=set(nums)\n        count=0\n        for i in nums:\n            if i-1 not in nums:\n                j=i\n                count=0\n                while j in nums:\n                    count+=1\n                    j+=1\n                ans=max(ans,count)            \n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestConsecutive = function(nums) {\n  if(nums.length === 1){\n    return 1\n  }\n  if(nums.length === 0){\n    return 0\n  }\n  nums.sort((a, b) => a - b)\n  let result = 1\n  let streak = 1\n  let i = 0\n  while(i < nums.length - 1){\n    if(nums[i] == nums[i + 1]) {\n      i++ \n      continue\n    }\n    if(nums[i] == nums[i + 1] - 1){\n      streak++\n       if(streak > result){\n         result = streak\n       }\n    } else {\n      streak = 1\n    }\n    i++\n  }\n  return result\n};",
        "solution_java": "class Solution {\n    public int longestConsecutive(int[] nums) {\n        Set<Integer> storage = new HashSet();\n        \n        for(int i = 0; i < nums.length; i++){\n            storage.add(nums[i]);\n        }\n        \n        int maxL = 0;\n        \n        for(int i = 0; i < nums.length; i++){\n            \n            //check if nums[i] id present in set or not\n            //since after checking in set we remove the element from \n            //set, there is no double calculation for same sequence \n            if(storage.contains(nums[i])){\n                storage.remove(nums[i]);\n                \n                int dec = nums[i]-1;\n                int inc = nums[i]+1;\n                int tempL = 1;\n                \n                //check both ways from nums[i] and calculate \n                //tempL. since we are removing elements from \n                //set we only calculate once for every sequence.\n                \n                while(storage.contains(dec)){\n                    storage.remove(dec);\n                    dec--;\n                    tempL++;\n                }\n                \n                while(storage.contains(inc)){\n                    storage.remove(inc);\n                    inc++;\n                    tempL++;\n                }\n                \n                \n                maxL = Math.max(maxL, tempL);\n                \n            }\n        }\n        \n        return maxL;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        \n        set<int> hashSet;\n        \n        int longestConsecutiveSequence = 0; \n        \n        for(auto it : nums){\n            hashSet.insert(it);\n        }\n        \n        for(auto it : nums){\n            \n            if(!hashSet.count(it-1)){\n                \n                int count = 1;\n                \n                while(hashSet.count(it+count)) ++count;\n                \n                longestConsecutiveSequence = max(count,longestConsecutiveSequence);\n                \n            }\n            \n        }\n        \n        return longestConsecutiveSequence;\n    }\n};"
    },
    {
        "title": "Remove Digit From Number to Maximize Result",
        "algo_input": "You are given a string number representing a positive integer and a character digit.\n\nReturn the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.\n\n&nbsp;\nExample 1:\n\nInput: number = \"123\", digit = \"3\"\nOutput: \"12\"\nExplanation: There is only one '3' in \"123\". After removing '3', the result is \"12\".\n\n\nExample 2:\n\nInput: number = \"1231\", digit = \"1\"\nOutput: \"231\"\nExplanation: We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 &gt; 123, we return \"231\".\n\n\nExample 3:\n\nInput: number = \"551\", digit = \"5\"\nOutput: \"51\"\nExplanation: We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= number.length &lt;= 100\n\tnumber consists of digits from '1' to '9'.\n\tdigit is a digit from '1' to '9'.\n\tdigit occurs at least once in number.\n\n",
        "solution_py": "class Solution:\n    def removeDigit(self, number: str, digit: str) -> str:\n        \n        # Initializing the last index as zero\n        last_index = 0\n        \n        #iterating each number to find the occurences, \\\n        # and to find if the number is greater than the next element \\ \n\n        for num in range(1, len(number)):\n            \n            # Handling [case 1] and [case 2]\n            if number[num-1] == digit:\n                if int(number[num]) > int(number[num-1]):\n                    return number[:num-1] + number[num:]\n                else:\n                    last_index = num - 1\n        \n        # If digit is the last number (last occurence) in the string [case 3]\n        if number[-1] == digit:\n            last_index = len(number) - 1\n\n        return number[:last_index] + number[last_index + 1:]",
        "solution_js": "/**\n * @param {string} number\n * @param {character} digit\n * @return {string}\n */\nvar removeDigit = function(number, digit) {\n\n    let str = [];\n    let flag = 0;\n    for (let i = 0; i < number.length; i++) {\n        if (number[i] == digit ) {\n            let temp = number.substring(0, i) + number.substring(i+1);\n            str.push(temp);\n        }\n    }\n\n    str.sort();\n    return str[str.length-1];\n};",
        "solution_java": "class Solution {\n    public String removeDigit(String number, char digit) {\n        List<String> digits = new ArrayList<>();\n        for (int i = 0; i < number.length(); i++) {\n            if (number.charAt(i) == digit) {\n                String stringWithoutDigit = number.substring(0, i) + number.substring(i + 1);\n                digits.add(stringWithoutDigit);\n            }\n        }\n        Collections.sort(digits);\n        return digits.get(digits.size() - 1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string removeDigit(string number, char digit) {\n        string res = \"\";\n        for(int i=0; i<number.size(); i++){\n            if(number[i] == digit){\n                string temp = number.substr(0, i) + number.substr(i+1);\n                res = max(res, temp);\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Reverse Only Letters",
        "algo_input": "Given a string s, reverse the string according to the following rules:\n\n\n\tAll the characters that are not English letters remain in the same position.\n\tAll the English letters (lowercase or uppercase) should be reversed.\n\n\nReturn s after reversing it.\n\n&nbsp;\nExample 1:\nInput: s = \"ab-cd\"\nOutput: \"dc-ba\"\nExample 2:\nInput: s = \"a-bC-dEf-ghIj\"\nOutput: \"j-Ih-gfE-dCba\"\nExample 3:\nInput: s = \"Test1ng-Leet=code-Q!\"\nOutput: \"Qedo1ct-eeLg=ntse-T!\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of characters with ASCII values in the range [33, 122].\n\ts does not contain '\\\"' or '\\\\'.\n\n",
        "solution_py": "class Solution:\n    def reverseOnlyLetters(self, s: str) -> str:\n        st,sp=[],[]\n        for i,ch in enumerate(s):\n            if ch.isalpha():\n                st.append(ch)\n            else:\n                sp.append([i,ch])\n        st=st[::-1]\n        for i in sp:\n            st.insert(i[0],i[1])\n        return (''.join(st))",
        "solution_js": "var reverseOnlyLetters = function(s) {\n    let valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n    let arr = s.split('')\n    \n    let r = arr.length - 1;\n    let l = 0;\n    \n    while (l < r) {\n        while (!valid.includes(arr[l]) && l < r) {\n            l++;\n            continue;\n        }\n    \n        while (!valid.includes(arr[r]) && l < r) {\n            r--;\n            continue\n        }\n        \n        if (l >= r) break;\n        \n        [arr[l], arr[r]] = [arr[r], arr[l]];\n        l++;\n        r--;\n    }\n    \n    \n    return arr.join('')\n\t```",
        "solution_java": "class Solution {\n    public String reverseOnlyLetters(String s) {\n        // converting the string to the charArray...\n        char[] ch = s.toCharArray();\n\n        int start = 0;\n        int end = s.length()-1;\n\n        // Storing all the english alphabets in a hashmap so that the searching becomes easy...\n        HashMap<Character , Integer> hash = new HashMap<>();\n        for(int i=0 ; i<26 ;i++){\n            hash.put((char)(97+i) , 1);\n        }\n        for(int i=0 ; i<26 ; i++){\n            hash.put((char)(65+i) , 1);\n        }\n\n        // using two while loops ..since the constraints are too less thats why we can prefer nested loops approach..\n        while(start<end){\n\n            // interating untill start pointer reacher a good character\n            while(start<end&&!hash.containsKey(ch[start])){\n                start++;\n            }\n            // iterating untill the end pointer reaches the good character..\n            while(end>start&&!hash.containsKey(ch[end])){\n                end--;\n            }\n\n            // swapping the array elements..\n            char temp = ch[start];\n            ch[start] = ch[end];\n            ch[end] = temp;\n\n            start++;\n            end--;\n        }\n\n        // converting the charArray to the string again..\n        String ans = new String(ch);\n        return ans;\n\n        // Time Complexity : O(N) (since the loops will run only till the number of charcters in the string..)\n        // Space Complexity : O(N) since we used hashmap..\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reverseOnlyLetters(string s) {\n        int a=0,b=s.size()-1;\n        for(;a<b;)\n        {\n            if(((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n               {\n                   char z=s[a];\n                   s[a]=s[b];\n                   s[b]=z;\n                   a++;\n                   b--;\n               }\n               else if(!((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n                       {\n                           a++;\n                       }\n                       else if(((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&!((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n                       b--;\n                       else{\n                           a++;\n                           b--;\n                       }\n\n    }\n        return s;\n    }\n};"
    },
    {
        "title": "Sum of Beauty in the Array",
        "algo_input": "You are given a 0-indexed integer array nums. For each index i (1 &lt;= i &lt;= nums.length - 2) the beauty of nums[i] equals:\n\n\n\t2, if nums[j] &lt; nums[i] &lt; nums[k], for all 0 &lt;= j &lt; i and for all i &lt; k &lt;= nums.length - 1.\n\t1, if nums[i - 1] &lt; nums[i] &lt; nums[i + 1], and the previous condition is not satisfied.\n\t0, if none of the previous conditions holds.\n\n\nReturn the sum of beauty of all nums[i] where 1 &lt;= i &lt;= nums.length - 2.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: For each index i in the range 1 &lt;= i &lt;= 1:\n- The beauty of nums[1] equals 2.\n\n\nExample 2:\n\nInput: nums = [2,4,6,4]\nOutput: 1\nExplanation: For each index i in the range 1 &lt;= i &lt;= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.\n\n\nExample 3:\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: For each index i in the range 1 &lt;= i &lt;= 1:\n- The beauty of nums[1] equals 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def sumOfBeauties(self, nums: List[int]) -> int:\n        n = len(nums)\n        max_dp = [0] * n\n        min_dp = [float(inf)] * n\n        max_dp[0] = nums[0]\n        min_dp[-1] = nums[-1]\n        \n        for i in range(1, n):\n            max_dp[i] = max(nums[i], max_dp[i-1])\n            \n        for i in range(n-2, -1, -1):\n            min_dp[i] = min(nums[i], min_dp[i+1])\n        \n        ans = 0\n        for i in range(1, n-1):\n            if max_dp[i-1] < max_dp[i] and nums[i] < min_dp[i+1]:\n                ans += 2\n            elif nums[i-1] < nums[i] < nums[i+1]:\n                ans += 1\n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar sumOfBeauties = function(nums) {\n    let min = nums[0], max = Infinity, maxArr = [], total = 0;\n\n    // Creating an array, which will keep the record of minimum values from last index\n    for(let i=nums.length-1; i>1; i--) {\n        if(nums[i] < max) max = nums[i];\n        maxArr.push(max);\n    }\n\n    // iterating through array to check the given conditions\n    for(let i=1; i<nums.length-1; i++) {\n\n        // Keeping a record of max value from all index < i\n        if(nums[i-1] > min) min = nums[i-1];\n\n        // Checking conditions\n        if(nums[i] < maxArr.pop() && min < nums[i]) total += 2;\n        else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) total += 1;\n    }\n\n    return total;\n};",
        "solution_java": "class Solution {\n    public int sumOfBeauties(int[] nums) {\n        boolean[] left = new boolean[nums.length];\n        boolean[] right = new boolean[nums.length];\n\n        left[0] = true;\n        int leftMax = nums[0];\n        for(int i = 1; i < nums.length; i++) {\n            if(nums[i] > leftMax) {\n                left[i] = true;\n                leftMax = nums[i];\n            }\n        }\n\n        right[nums.length-1] = true;\n        int rightMin = nums[nums.length-1];\n        for(int i = nums.length-2; i >= 0; i--) {\n            if(nums[i] < rightMin) {\n                right[i] = true;\n                rightMin = nums[i];\n            }\n        }\n\n        int beautyCount = 0;\n        for(int i = 1; i < nums.length-1; i++) {\n            if(left[i] && right[i]) {\n                beautyCount += 2;\n            }\n\n            else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) {\n                beautyCount += 1;\n            }\n\n        }\n        return beautyCount;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumOfBeauties(vector<int>& nums) {\n        int n=nums.size();\n        vector<int>right;\n        vector<int>left;\n        int low=nums[0];\n        for(int i=0;i<nums.size();i++){\n            \n            left.push_back(low);\n            low=max(low,nums[i]);\n        }\n        low=nums[n-1];\n        for(int i=n-1;i>=0;i--){\n            \n            right.push_back(low);\n            low=min(low,nums[i]);\n        }\n        reverse(right.begin(),right.end());\n        int ans=0;\n        for(int i=1;i<n-1;i++){\n            if(nums[i]>left[i] && nums[i]<right[i]){\n                ans+=2;\n            }\n            else if(nums[i]>nums[i-1] && nums[i]<nums[i+1]){\n                ans+=1;\n            }\n            else{\n                ans+=0;\n            }\n        }\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Water and Jug Problem",
        "algo_input": "You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.\n\nIf targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.\n\nOperations allowed:\n\n\n\tFill any of the jugs with water.\n\tEmpty any of the jugs.\n\tPour water from one jug into another till the other jug is completely full, or the first jug itself is empty.\n\n\n&nbsp;\nExample 1:\n\nInput: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4\nOutput: true\nExplanation: The famous Die Hard example \n\n\nExample 2:\n\nInput: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5\nOutput: false\n\n\nExample 3:\n\nInput: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= jug1Capacity, jug2Capacity, targetCapacity &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:\n        n1, n2, t = jug1Capacity, jug2Capacity, targetCapacity\n        if n1 == t or n2 == t or n1 + n2 == t:\n            return True\n        if n1 + n2 < t:\n            return False\n        if n1 < n2:\n            n1, n2 = n2, n1\n        stack = []\n        visited = set()\n        d = n1 - n2\n        if d == t:\n            return True\n        while d > n2:\n            d -= n2\n            if d == t:\n                return True\n        stack.append(d)\n        while stack:\n            #print(stack)\n            d = stack.pop()\n            visited.add(d)\n            n = n1 + d\n            if n == t:\n                return True\n            n = n1 - d\n            if n == t:\n                return True\n            while n > n2:\n                n -= n2\n                if n == t:\n                    return True\n            if n < n2 and n not in visited:\n                stack.append(n)\n            n = n2 - d\n            if n == t:\n                return True\n            if n not in visited:\n                stack.append(n)\n        return False",
        "solution_js": "var canMeasureWater = function(jug1Capacity, jug2Capacity, targetCapacity) {\n\tconst gcd = (x, y) => y === 0 ? x : gcd(y, x % y);\n\n\treturn jug1Capacity + jug2Capacity >= targetCapacity && \n\t\ttargetCapacity % gcd(jug1Capacity, jug2Capacity) === 0;\n};",
        "solution_java": "class Solution {\n    private static int gcd(int a,int b){\n        if(b==0)return a;\n        return gcd(b,a%b);\n    }\n    public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n        if(targetCapacity>jug1Capacity+jug2Capacity){\n            return false;\n        }\n        int g=gcd(jug1Capacity,jug2Capacity);\n        return (targetCapacity%g==0);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n        \n        if(targetCapacity > jug1Capacity + jug2Capacity)\n            return false;\n        \n        vector<int> dp(jug1Capacity + jug2Capacity + 1, -1);\n        return helper(0, jug1Capacity, jug2Capacity, targetCapacity, dp);\n    }\n    \n    bool helper(int tmp, int &jug1Capacity, int &jug2Capacity, int &targetCapacity, vector<int> &dp)\n    {\n        if(tmp < 0 || tmp > jug1Capacity + jug2Capacity)\n            return false;\n        \n        if(tmp == targetCapacity)\n            return true;\n        \n        if(dp[tmp] != -1)\n            return dp[tmp];\n        \n        dp[tmp] = false;            \n        if(helper(tmp + jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n            return dp[tmp] = true;\n        \n        if(helper(tmp - jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n            return dp[tmp] = true;\n        \n        if(helper(tmp + jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n            return dp[tmp] = true;\n        \n         if(helper(tmp - jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n            return dp[tmp] = true;\n            \n        return dp[tmp] = false;\n    }\n};"
    },
    {
        "title": "Majority Element II",
        "algo_input": "Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,2,3]\nOutput: [3]\n\n\nExample 2:\n\nInput: nums = [1]\nOutput: [1]\n\n\nExample 3:\n\nInput: nums = [1,2]\nOutput: [1,2]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t-109 &lt;= nums[i] &lt;= 109\n\n\n&nbsp;\nFollow up: Could you solve the problem in linear time and in O(1) space?\n",
        "solution_py": "class Solution:\n    def majorityElement(self, nums: List[int]) -> List[int]:\n        \n        #Boyer Moore Voting Algo (As used in ME1 ques) \n        #now we can observe that there cannot be more than two elements occuring more than n//3 times in an array\n        #so find two majority elements(me=majority element)\n        \n\n        n=len(nums)\n        req=n//3  #for an element to be ME required number of times present \n\n        c1=0 #count 1\n        c2=0 #count 2\n        me1=None #majority element 1\n        me2=None #majority element 2\n\n        for i in nums:\n            if i == me1:\n                c1+=1\n\n            elif i == me2:\n                c2+=1\n\n            elif c1 == 0:\n                me1=i\n                c1=1\n\n            elif c2 == 0:\n                me2=i\n                c2=1\n\n            else:\n                c1-=1\n                c2-=1\n        #here we have found our majority elements now check if the found majority element is ME\n        # print(me1,me2)\n\n        #check if the found majority element is ME\n        c1=0\n        c2=0\n        for i in nums:\n            if i==me1:\n                c1+=1\n            if i==me2:\n                c2+=1\n        # print(c1,c2)\n\n        if c1 > req  and c2 > req:\n\n            return [me1,me2]\n\n        elif c1> req :\n            return [me1]\n\n        elif c2> req :\n            return [me2]",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar majorityElement = function(nums) {\n    const objElement = {};\n    const timesVar = Math.floor(nums.length/3);\n    const resultSet = new Set();\n\n    for(var indexI=0; indexI<nums.length; indexI++){\n       if(objElement[nums[indexI]]) {\n               objElement[nums[indexI]] = objElement[nums[indexI]] + 1;\n        }\n       else objElement[nums[indexI]] = 1;\n\n       if(objElement[nums[indexI]]>timesVar) resultSet.add(nums[indexI]);\n    }\n\n    return [...resultSet];\n};",
        "solution_java": "class Solution {\n    public List<Integer> majorityElement(int[] nums) {\n        int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;\n        for(int i = 1; i < nums.length; i++){\n            if(val1 == nums[i]){\n                cnt1++;\n            } else if(val2 == nums[i]){\n                cnt2++;\n            } else{\n                if(cnt1 == 0){\n                    val1 = nums[i];\n                    cnt1++;\n                } else if(cnt2 == 0){\n                    val2 = nums[i];\n                    cnt2++;\n                } else{\n                    cnt1--;\n                    cnt2--;\n                }\n            }\n        }\n        int check1 = 0, check2 = 0;\n        for(int i = 0; i < nums.length; i++){\n            if(val1 == nums[i])check1++;\n            else if(val2 == nums[i])check2++;\n        }\n        List<Integer> ans = new ArrayList<>();\n        if(check1 > nums.length / 3) ans.add(val1);\n        if(check2 > nums.length / 3) ans.add(val2);\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> majorityElement(vector<int>& nums) {\n\n        int n = nums.size();\n\n        vector<int> result;\n\n        int num1 = -1 , num2 = -1 , count1 = 0 , count2 = 0;\n\n        for(auto it : nums){\n\n            if(num1 == it) ++count1;\n            else if(num2 == it) ++count2;\n            else if(count1 == 0){\n                num1 = it;\n                count1 = 1;\n            }\n            else if(count2 == 0){\n                num2 =it;\n                count2 = 1;\n            }\n            else{\n                --count1;\n                --count2;\n            }\n\n        }\n\n        count1 = 0;\n        count2 = 0;\n\n        for(auto it : nums){\n\n            if(it == num1) ++count1;\n            else if(it == num2) ++count2;\n\n        }\n\n        if(count1>(n/3)) result.push_back(num1);\n        if(count2>(n/3)) result.push_back(num2);\n\n        return result;\n\n    }\n};"
    },
    {
        "title": "Reformat Phone Number",
        "algo_input": "You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.\n\nYou would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:\n\n\n\t2 digits: A single block of length 2.\n\t3 digits: A single block of length 3.\n\t4 digits: Two blocks of length 2 each.\n\n\nThe blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.\n\nReturn the phone number after formatting.\n\n&nbsp;\nExample 1:\n\nInput: number = \"1-23-45 6\"\nOutput: \"123-456\"\nExplanation: The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".\n\n\nExample 2:\n\nInput: number = \"123 4-567\"\nOutput: \"123-45-67\"\nExplanation: The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".\n\n\nExample 3:\n\nInput: number = \"123 4-5678\"\nOutput: \"123-456-78\"\nExplanation: The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= number.length &lt;= 100\n\tnumber consists of digits and the characters '-' and ' '.\n\tThere are at least two digits in number.\n\n",
        "solution_py": "class Solution:\n    def reformatNumber(self, number: str) -> str:\n        s = number.replace(\" \", \"\").replace(\"-\", \"\")\n        pieces = list()\n        while s:\n            if len(s) == 2:\n                pieces.append(s)\n                break\n            elif len(s) == 4:\n                pieces.append(s[:2])\n                pieces.append(s[2:])\n                break\n            else:\n                pieces.append(s[:3])\n                s = s[3:]\n        return \"-\".join(pieces)",
        "solution_js": "var reformatNumber = function(number) {\n    let numArr = number.replace(/-/g,'').replace(/ /g,'').split('')\n    let res = ''\n    while(numArr.length >= 4){\n        numArr.length == 4 ?\n            res += numArr.splice(0,2).join('') +'-'+numArr.splice(0,2).join('') :\n            res += numArr.splice(0,3).join('') + '-'\n    }\n    res += numArr.join('')\n    return res\n};",
        "solution_java": "class Solution {\n    String modifiedNumber=\"\";\n    public String reformatNumber(String number) {\n        modifiedNumber=number.replace(\" \",\"\");\n        modifiedNumber=modifiedNumber.replace(\"-\",\"\");\n        int l=modifiedNumber.length();\n        if(l<=3){\n            return modifiedNumber;\n        } else if(l==4){\n            return modifiedNumber.substring(0,2)+\"-\"+ modifiedNumber.substring(2,4);\n        } else {\n            modifiedNumber=modifiedNumber.substring(0,3)+\"-\"+reformatNumber(modifiedNumber.substring(3,l));\n        }\n        return modifiedNumber;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reformatNumber(string number) {\n\n        string temp; // stores the digits from string number\n        string ans; //stores final answer\n        int n = number.size();\n\n        for(auto ch:number)\n            if(isdigit(ch)) temp += ch;\n\n        int len = temp.size();\n        int i = 0;\n\n        while(len>0){\n            //check for different values of \"len\"\n            if(len > 4){ //if len > 4 -> make grp of 3 digits\n                ans += temp.substr(i,i+3);\n                temp.erase(i,3);\n                len = len-3;\n                ans += \"-\";\n            }\n\n            else if(len == 3){ //if len == 3 -> make grp of 3 digits\n                ans += temp.substr(i,i+3);\n                temp.erase(i,3);\n                len = len-3;\n                ans += \"-\";\n            }\n\n            else if(len == 2){ //if len == 2 -> make grp of 2 digits\n                ans += temp.substr(i,i+2);\n                temp.erase(i,2);\n                len = len-2;\n                ans += \"-\";\n            }\n\n            else if(len == 4){ //if len == 4 -> make 1 grp of 2 digits & reduce the length by 2 units, in the next iteration it will automatically catch (len==2) condition\n                ans += temp.substr(i,i+2);\n                temp.erase(i,2);\n                ans += \"-\";\n                // ans += temp.substr(i,i+2); ------(1)\n                // temp.erase(i,2); ------(2)\n                // ans += \"-\"; ------(3)\n                len = len-2; // *len = len-4* can be edited to *len = len-2*------(4)\n\n            }\n\n        }\n\n        ans.pop_back();\n        return ans;\n    }\n};"
    },
    {
        "title": "Arithmetic Slices",
        "algo_input": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n\n\n\tFor example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.\n\n\nGiven an integer array nums, return the number of arithmetic subarrays of nums.\n\nA subarray is a contiguous subsequence of the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4]\nOutput: 3\nExplanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n\n\nExample 2:\n\nInput: nums = [1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t-1000 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "#Baraa\nclass Solution:\n    def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n        \"\"\"\n        what is (x * (x + 1)) // 2? this is series sum formula between n and 1\n\n        which means: n + (n - 1) + (n - 2) + (n - 3) .... + 1\n\n        when we have a total number of 10 elements that form an arithmetic sum\n        eg: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n        we can form subarrays up until count - 2\n        which means 1,2,3,4,5,6,7,8\n        if we take 7 for example --> [7, 8, 9, 10] or [7, 8, 9]\n\n        we cant take [9, 10] as subarray as its length < 3\n        \"\"\"\n\n        #this is done for termination only\n        nums += [-float(\"inf\")]\n        n = len(nums)\n        #base case\n        if n < 3:\n            return 0\n        res = 0\n        #store inital difference we have\n        prev_diff = nums[1] - nums[0]\n        #because we calculated an initial difference we store 2 inside count\n        #which represents number of elements\n        count = 2\n        for i in range(2, n):\n            diff = nums[i] - nums[i - 1]\n            if prev_diff != diff:\n                x = count - 2\n                res = res + (x * (x + 1)) // 2\n                prev_diff = diff\n                count = 2\n            else:\n                count += 1\n                prev_diff = diff\n        return res",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numberOfArithmeticSlices = function(nums) {\n    nums.push(-2000)\n    let count = 0  \n    let dist = nums[1]-nums[0]\n    let start = 0\n    \n    for (let i = 1; i < nums.length; i++) {\n        if (nums[i]-nums[i-1] !== dist) {\n            \n            let len =  i - start\n            start = i-1\n            dist = nums[i] - nums[i-1]\n            \n            // count the length of each largest AS and add to sum \n            // of len = 5 => the number of sub AS = 1 (len = 5) + 2 (len = 4) + 3 (len = 3)\n            for (let k = 3; k <=len; k++) {\n                count += len - k + 1\n            }\n            \n        }\n    }\n    \n    return count\n};",
        "solution_java": "class Solution {\n    public int numberOfArithmeticSlices(int[] nums) {\n        int n = nums.length;\n        if (n < 3) {\n            return 0;\n        }\n        int[] dp = new int[n - 1];\n        dp[0] = nums[1] - nums[0];\n        for (int i = 2; i < n; i++) {\n            dp[i - 1] = nums[i] - nums[i - 1];\n        }\n        int si = 0;\n        int count = 0;\n        for (int i = 1; i < n - 1; i++) {\n            if (dp[i] == dp[i - 1]) {\n                count += (i - si);\n            } else {\n                si = i;\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfArithmeticSlices(vector<int>& nums) {\n        int n=nums.size(),i,j,count=0,comm_diff;\n        for(i=0;i<=n-3;i++)\n        {\n            comm_diff = nums[i+1]-nums[i];\n            for(j=i+1;j<n;j++)\n            {\n                if(nums[j]-nums[j-1]==comm_diff)\n                {\n                    if((j-i+1)>=3)\n                    {\n                        count++;\n                    }\n                }\n                else\n                {\n                    break;\n                }\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Tiling a Rectangle with the Fewest Squares",
        "algo_input": "Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\n\nExample 2:\n\n\n\nInput: n = 5, m = 8\nOutput: 5\n\n\nExample 3:\n\n\n\nInput: n = 11, m = 13\nOutput: 6\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n, m &lt;= 13\n\n",
        "solution_py": "class Solution:\n    def tilingRectangle(self, n: int, m: int) -> int:\n      # try brute force backtracking?\n      board = [[0 for _ in range(n)] for _ in range(m)]\n\n      ans = math.inf\n      def bt(counts):\n        nonlocal ans\n        if counts >= ans:\n          return\n        \n        pos = None\n        found = False\n        for row in range(m):\n          for col in range(n):\n            if board[row][col] == 0:\n              pos = (row, col)\n              found = True\n              break\n          if found:\n            break\n        if not found:\n          ans = min(ans, counts)\n          return\n\n        # see how many difference size of squares we can place from this spot\n        r, c = pos\n        offset = 0\n        while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n          offset += 1\n        # max can place size is offset\n        for row in range(r, r + offset):\n          for col in range(c, c + offset):\n            board[row][col] = 1\n        # do bt and shrink\n        while offset > 0:\n          bt(counts + 1)\n          # shrink\n          for row in range(r, r + offset):\n            board[row][c + offset - 1] = 0\n          for col in range(c, c + offset):\n            board[r + offset - 1][col] = 0\n          offset -= 1\n\n      bt(0)\n      return ans",
        "solution_js": "var tilingRectangle = function(n, m) {\n  const queue = [[new Array(n).fill(0), 0]];\n  while (true) {\n    const [curr, numSquares] = queue.shift();\n    let min = { height: Infinity, start: Infinity, end: Infinity }\n    for (let i = 0; i < n; i++) {\n      if (curr[i] < min.height) {\n        min.height = curr[i];\n        min.start = i;\n        min.end = i + 1;\n      } else if (curr[i] === min.height && min.end === i) {\n        min.end++\n      }\n    }\n    if (min.height === m) return numSquares;\n    const largestSquare = Math.min(m - min.height, min.end - min.start);\n    for (let sqWidth = largestSquare; sqWidth; sqWidth--) {\n      const next = curr.slice();\n      for (let i = min.start; i < min.start + sqWidth; i++) {\n        next[i] += sqWidth;\n      }\n      queue.push([next, numSquares + 1]);\n    }\n  }\n};",
        "solution_java": "class Solution {\n    int ret; // store the final result\n    int m, n; // m is the height, and n is the width\n\t\n\t// Note: original signature is changed from n,m to m,n\n    public int tilingRectangle(int m, int n) { \n        this.m = m;\n        this.n = n;\n        this.ret = m * n; // initilize the result as m*n if cut rectangle to be all 1*1 squares\n        int[][] mat = new int[m][n]; // record the status of every location, 0 means not covered, 1 means covered\n        backtrack(mat, 0); // start backtracking\n        return ret;\n    }\n    \n\t// the size means how many squares cut now\n    public void backtrack(int[][] mat, int size) {\n        if (size > ret) return; // if we already have more squares than the min result, no need to go forward\n        \n\t\t// find out the leftmost and topmost postion where is not covered yet\n        int x = -1, y = -1;\n        for(int i = 0; i < m; i++) {\n            for(int j = 0; j < n; j++) {\n                if (mat[i][j] == 0) {\n                    x = i;\n                    y = j;\n                    break;\n                }\n            }\n            if (x != -1 && y != -1) break;\n        }\n\t\t// if not found, we know that all positions are covered\n        if (x == -1 && y == -1) {\n\t\t    // update the result\n            ret = Math.min(size, ret);\n        }\n        else {\n            int len = findWidth(x, y, mat); // find the maximum width to cut the square\n            while(len >= 1) {\n                cover(x, y, len, mat, 1); // cover the current square\n                backtrack(mat, size + 1);\n                cover(x, y, len, mat, 0); // uncover the previous result\n                len--; // decrement the square width by 1\n            }\n        }\n    }\n    \n    public int findWidth(int x, int y, int[][] mat) {\n        int len = 1;\n        while(x + len < m && y + len < n) {\n            boolean flag = true; // flag means the len is reachable\n            for (int i = 0; i <= len; i++) {\n\t\t\t    // check the right i-th column and the bottom i-th row away from (x, y) \n                if (mat[x + i][y + len] == 1 || mat[x + len][y + i] == 1) {\n                    flag = false;\n                    break;\n                }\n            }\n            if (!flag) break;\n            len++;\n        }\n        return len;\n    }\n    \n    public void cover(int x, int y, int len, int[][] mat, int val) {\n        for (int i = x; i < x + len; i++) {\n            for (int j = y; j < y + len; j++) {\n                mat[i][j] = val;\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(int n, int m, vector<vector<int>>& dp) {\n        if(n<0 || m<0) return 0;\n        if(m==n) return 1;\n        \n        // this is special case\n        if((m==13 && n==11) || (m==11 && n==13)) return dp[n][m]=6;\n        \n        if(dp[n][m]!=0) return dp[n][m];\n        \n        int hz=1e9;\n        for(int i=1;i<=n/2;i++) {\n            hz = min(hz, solve(i,m,dp) + solve(n-i,m,dp));\n        }\n        \n        int vert = 1e9;\n        for(int i=1;i<=m/2;i++) {\n            vert = min(vert, solve(n,m-i,dp) + solve(n,i,dp));\n        }\n        \n        return dp[n][m] = min(hz,vert);\n    }\n    \n    int tilingRectangle(int n, int m) {\n        vector<vector<int>> dp (n+1,vector<int> (m+1,0));\n        return solve(n,m,dp);\n    }\n};"
    },
    {
        "title": "Minimum Moves to Convert String",
        "algo_input": "You are given a string s consisting of n characters which are either 'X' or 'O'.\n\nA move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.\n\nReturn the minimum number of moves required so that all the characters of s are converted to 'O'.\n\n&nbsp;\nExample 1:\n\nInput: s = \"XXX\"\nOutput: 1\nExplanation: XXX -&gt; OOO\nWe select all the 3 characters and convert them in one move.\n\n\nExample 2:\n\nInput: s = \"XXOX\"\nOutput: 2\nExplanation: XXOX -&gt; OOOX -&gt; OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's.\n\nExample 3:\n\nInput: s = \"OOOO\"\nOutput: 0\nExplanation: There are no 'X's in s to convert.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 1000\n\ts[i] is either 'X' or 'O'.\n\n",
        "solution_py": "class Solution:\n    def minimumMoves(self, s: str) -> int:\n        i, m = 0, 0\n        l = len(s)\n\n        while i < l:\n            if s[i] != 'X':\n                i += 1\n            elif 'X' not in s[i:i+1]:\n                i += 2\n            elif 'X' in s[i:i+2]:\n                m += 1\n                i += 3\n        return m",
        "solution_js": "var minimumMoves = function(s) {\n    let move = 0;\n    let i = 0;\n    while(i<s.length){\n        let char = s[i];\n        // incrementing the index if we already have 'O'\n        if(char== 'O'){\n            i++;\n        }\n        // incrementing the move and index by 3 (Per move = 3 characters)\n        if(char== 'X'){\n            i=i+3;\n            move++;\n        }\n    }\n    return move;\n};",
        "solution_java": "class Solution {\n    public int minimumMoves(String s) {\n        int i=0;\n        int step=0;\n        while(i<s.length()){\n            if(s.charAt(i)=='X'){\n                i=i+3;\n                step++;\n            }\n            else{\n                i++;\n            }\n        }\n        return step;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumMoves(string s) {\n        int count=0;\n        int i=0;\n        \n        for(int i=0;i<s.size();){\n            if(s[i]=='O'){\n             // continue;\n              i++;}\n            else{\n              count++;\n              i+=3;\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Find the Duplicate Number",
        "algo_input": "Given an array of integers nums containing&nbsp;n + 1 integers where each integer is in the range [1, n] inclusive.\n\nThere is only one repeated number in nums, return this&nbsp;repeated&nbsp;number.\n\nYou must solve the problem without modifying the array nums&nbsp;and uses only constant extra space.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,4,2,2]\nOutput: 2\n\n\nExample 2:\n\nInput: nums = [3,1,3,4,2]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\tnums.length == n + 1\n\t1 &lt;= nums[i] &lt;= n\n\tAll the integers in nums appear only once except for precisely one integer which appears two or more times.\n\n\n&nbsp;\nFollow up:\n\n\n\tHow can we prove that at least one duplicate number must exist in nums?\n\tCan you solve the problem in linear runtime complexity?\n\n",
        "solution_py": "class Solution:\n    def findDuplicate(self, nums: List[int]) -> int:\n\n        dictx = {}\n\n        for each in nums:\n            if each not in dictx:\n                dictx[each] = 1\n            else:\n                return each",
        "solution_js": "var findDuplicate = function(nums) {\n    let dup = new Map();\n\n    for(let val of nums){\n        if(dup.has(val)){\n            dup.set(val, dup.get(val) + 1);\n            return val;\n        }\n        else\n            dup.set(val, 1);\n    }\n};",
        "solution_java": "class Solution {\n    public int findDuplicate(int[] nums) {\n        int i = 0; \n         while (i < nums.length) {\n\n            if (nums[i] != i + 1) {\n                int correct = nums[i] - 1;\n                if (nums[i] != nums[correct]) {\n                    swap(nums, i , correct);\n                } else {\n                    return nums[i];\n                }\n            } else {\n                i++;\n            }\n        }\n        return -1;\n    }\n     static void swap(int[] arr, int first, int second) {\n        int temp = arr[first];\n        arr[first] = arr[second];\n        arr[second] = temp;\n    }\n   }",
        "solution_c": "                // Please upvote if it helps\nclass Solution {\npublic:\n    int findDuplicate(vector<int>& nums) {\n        int low = 1, high = nums.size() - 1, cnt;\n\n        while(low <= high)\n        {\n            int mid = low + (high - low) / 2;\n            cnt = 0;\n            // cnt number less than equal to mid\n            for(int n : nums)\n            {\n                if(n <= mid)\n                    ++cnt;\n            }\n            // binary search on left\n            if(cnt <= mid)\n                low = mid + 1;\n            else\n            // binary search on right\n                high = mid - 1;\n\n        }\n        return low;\n    }\n    // for github repository link go to my profile.\n};"
    },
    {
        "title": "Length of Last Word",
        "algo_input": "Given a string s consisting of words and spaces, return the length of the last word in the string.\n\nA word is a maximal substring consisting of non-space characters only.\n\n&nbsp;\nExample 1:\n\nInput: s = \"Hello World\"\nOutput: 5\nExplanation: The last word is \"World\" with length 5.\n\n\nExample 2:\n\nInput: s = \"   fly me   to   the moon  \"\nOutput: 4\nExplanation: The last word is \"moon\" with length 4.\n\n\nExample 3:\n\nInput: s = \"luffy is still joyboy\"\nOutput: 6\nExplanation: The last word is \"joyboy\" with length 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of only English letters and spaces ' '.\n\tThere will be at least one word in s.\n\n",
        "solution_py": "class Solution:\n    def lengthOfLastWord(self, s: str) -> int:\n        return len(s.strip().split()[-1])",
        "solution_js": "var lengthOfLastWord = function(s) {\n    s = s.split(\" \");\n    if(s[s.length-1] == ``)\n    {\n        for(var i = s.length-1; i >= 0; i-- )\n        {\n            if(s[i].length > 0)\n            {\n                return s[i].length;\n            }\n        }\n    }\n    else\n    {\n        return s[s.length-1].length;\n    }\n};",
        "solution_java": "class Solution {\n    public int lengthOfLastWord(String s) {\n        int j=s.length()-1,len=0; boolean flag=true;\n        while(j>=0 && (flag || (!flag && s.charAt(j)!=' ')))\n            if(s.charAt(j--)!=' '){\n                flag=false;\n                len++;\n            }\n        return len;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lengthOfLastWord(string s) {\n        int count = 0;\n        int n = s.size();\n        int i = n-1;\n        while(i>=0){\n            if(s[i]==' '){\n                i--;\n                if(count >0){\n                    break;\n                }\n            }\n            else{\n                count++;\n                i--;\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Minimum Average Difference",
        "algo_input": "You are given a 0-indexed integer array nums of length n.\n\nThe average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.\n\nReturn the index with the minimum average difference. If there are multiple such indices, return the smallest one.\n\nNote:\n\n\n\tThe absolute difference of two numbers is the absolute value of their difference.\n\tThe average of n elements is the sum of the n elements divided (integer division) by n.\n\tThe average of 0 elements is considered to be 0.\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,5,3,9,5,3]\nOutput: 3\nExplanation:\n- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.\n\n\nExample 2:\n\nInput: nums = [0]\nOutput: 0\nExplanation:\nThe only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "from itertools import accumulate\n\nclass Solution:\n    def minimumAverageDifference(self, nums: List[int]) -> int:\n        size = len(nums)\n\n        nums[::] = list(accumulate(nums))\n        total = nums[-1]\n        \n        min_tuple = [0, sys.maxsize]\n        \n        for (i, n) in enumerate(nums):\n            i = i + 1\n            avg_i = floor(n/i)\n            \n            diff = size - i\n            total_avg = floor((total - n) / (diff if diff>0 else 1))\n\n            avg = abs( avg_i - total_avg) \n            if min_tuple[1] > avg:\n                min_tuple[1] = avg\n                min_tuple[0] = i - 1\n            \n        return min_tuple[0]",
        "solution_js": "```/**\n * @param {number[]} nums\n * @return {number}\n */\n var minimumAverageDifference = function(nums) {\n    if (nums.length == 1) return 0;\n    let mins = 100000, resultIndex, leftTotal = 0;\n    let rightTotal = nums.reduce((a,b)=>a + b);\n    let numLength = nums.length;\n    nums.forEach((data, index)=> {\n        leftTotal += data;\n        rightTotal -= data;\n        let currentAverageDiff = Math.abs(Math.floor(leftTotal/(index+1)) - Math.floor(rightTotal/(numLength-index-1) || 0));\n        if (currentAverageDiff < mins) {\n            resultIndex = index;\n            mins = currentAverageDiff;\n        }\n    });\n    return resultIndex;\n};",
        "solution_java": "class Solution {\n    public int minimumAverageDifference(int[] nums) {\n        if(nums.length == 1){\n            return 0;\n        }\n        int idx = -1;\n        long min = Integer.MAX_VALUE;\n        long suml = nums[0];\n        long sumr = 0;\n        for(int i = 1; i < nums.length; i++){\n            sumr += nums[i];\n        }\n        int i = 1;\n        int calc = 0;\n        int left = 1;\n        int right = nums.length - left;\n        long[] arr = new long[nums.length];\n        while(i < nums.length){\n            long diff = Math.abs((suml/left) - (sumr/right));\n            arr[calc] = diff;\n            if(diff < min){\n                min = diff;\n                idx = calc;\n            }\n            suml += nums[i];\n            sumr -= nums[i];\n            left++;\n            right--;\n            calc++;\n            i++;\n        }\n        arr[calc] = suml/nums.length;\n        if(arr[calc] < min){\n            min = arr[calc];\n            idx = nums.length - 1;\n        }\n        // for(i = 0; i < nums.length; i++){\n        // System.out.println(arr[i]);\n        // }\n        return (int)idx;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumAverageDifference(vector<int>& nums) {\n\n        int n(size(nums)), minAverageDifference(INT_MAX), index;\n\n        long long sumFromFront(0), sumFromEnd(0);\n        for (auto& num : nums) sumFromEnd += num;\n\n        for (int i=0; i<n; i++) {\n            sumFromFront += nums[i];\n            sumFromEnd -= nums[i];\n            int a = sumFromFront / (i+1); // average of the first i + 1 elements.\n            int b = (i == n-1) ? 0 : sumFromEnd / (n-i-1); // average of the last n - i - 1 elements.\n\n            if (abs(a-b) < minAverageDifference) {\n                minAverageDifference = abs(a-b);\n                index = i;\n            }\n        }\n        return index;\n    }\n};"
    },
    {
        "title": "Linked List Components",
        "algo_input": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.\n\nReturn the number of connected components in nums where two values are connected if they appear consecutively in the linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [0,1,2,3], nums = [0,1,3]\nOutput: 2\nExplanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.\n\n\nExample 2:\n\nInput: head = [0,1,2,3,4], nums = [0,3,1,4]\nOutput: 2\nExplanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the linked list is n.\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= Node.val &lt; n\n\tAll the values Node.val are unique.\n\t1 &lt;= nums.length &lt;= n\n\t0 &lt;= nums[i] &lt; n\n\tAll the values of nums are unique.\n\n",
        "solution_py": "class Solution:\n    def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:\n        d,count={},0\n        for num in nums:\n            d[num] = 0\n\n        while head:\n            if head.val in d:\n                head = head.next\n                while head and head.val in d:\n                    head = head.next\n                count += 1\n            else:\n                head = head.next\n        return count",
        "solution_js": "var numComponents = function(head, nums) {\n    let broken = true, count = 0;\n\n    while (head) {\n        if (nums.includes(head.val) && broken) {\n            count++;\n            broken = false;\n        }\n        else if (!nums.includes(head.val)) {\n            broken = true;\n        }\n\n        // reset head as next\n        head = head.next\n    }\n\n    // result\n    return count;\n};",
        "solution_java": "class Solution {\n    public int numComponents(ListNode head, int[] nums) {\n        int count=0;\n        HashSet<Integer> set=new HashSet();\n        for(int i=0;i<nums.length;i++)\n        {\n            set.add(nums[i]);\n        }\n        while(head!=null)\n        {  \n            if(set.contains(head.val))\n            {\n                while(head.next!=null&&set.contains(head.next.val))\n                {\n                    head=head.next;\n\n                }\n                count++;\n            }\n            \n           \n                head=head.next;\n            \n            \n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numComponents(ListNode* head, vector<int>& nums)\n    {\n        unordered_set<int> s;\n        for(auto &x:nums)\n            s.insert(x);\n        int count=0;\n        while(head!=NULL)\n        {\n            if(s.find(head->val)!=s.end()) count++;\n            while(head!=NULL && s.find(head->val)!=s.end())\n            {\n                head=head->next;\n            }\n            if(head!=NULL)\n            head=head->next;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Replace All Digits with Characters",
        "algo_input": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.\n\nThere is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.\n\n\n\tFor example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.\n\n\nFor every odd&nbsp;index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).\n\nReturn s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.\n\n&nbsp;\nExample 1:\n\nInput: s = \"a1c1e1\"\nOutput: \"abcdef\"\nExplanation: The digits are replaced as follows:\n- s[1] -&gt; shift('a',1) = 'b'\n- s[3] -&gt; shift('c',1) = 'd'\n- s[5] -&gt; shift('e',1) = 'f'\n\nExample 2:\n\nInput: s = \"a1b2c3d4e\"\nOutput: \"abbdcfdhe\"\nExplanation: The digits are replaced as follows:\n- s[1] -&gt; shift('a',1) = 'b'\n- s[3] -&gt; shift('b',2) = 'd'\n- s[5] -&gt; shift('c',3) = 'f'\n- s[7] -&gt; shift('d',4) = 'h'\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists only of lowercase English letters and digits.\n\tshift(s[i-1], s[i]) &lt;= 'z' for all odd indices i.\n\n",
        "solution_py": "class Solution(object):\n    def replaceDigits(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: str\n        \"\"\"\n        res = []\n\n        for i in range(len(s)):\n            if i % 2 == 0:\n                res.append(s[i])\n            if i % 2 == 1:\n                res.append( chr(ord(s[i-1]) + int(s[i])) )\n\n        return ''.join(res)",
        "solution_js": "var replaceDigits = function(s) {\n    let res = ''\n    for(let i = 0; i < s.length; i++){\n        if(i % 2 !== 0){\n          res += String.fromCharCode(s[i - 1].charCodeAt() + parseInt(s[i]))\n        } else{\n            res += s[i]\n        }\n\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public String replaceDigits(String s) {\n        char[] str = s.toCharArray();\n\n        for(int i=0;i<str.length;i++){\n            if(Character.isDigit(str[i])){\n              str[i] = shift(str[i-1],str[i]);\n            }\n        }\n        return String.valueOf(str);\n    }\n\n    char shift(char letter, char number){\n        int a = Integer.parseInt(String.valueOf(number));\n        int asci = (int)letter;\n        char c = (char)(asci + a);\n        return c;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string replaceDigits(string s) {\n        for(int i=1;i<s.size();i+=2){\n            s[i]=s[i-1]+(s[i]-'0'); //or s[i] += s[i-1] - '0';\n        }\n        return s;\n    }\n};"
    },
    {
        "title": "Operations on Tree",
        "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 the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.\n\nThe data structure should support the following functions:\n\n\n\tLock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.\n\tUnlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.\n\tUpgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true:\n\t\n\t\tThe node is unlocked,\n\t\tIt has at least one locked descendant (by any user), and\n\t\tIt does not have any locked ancestors.\n\t\n\t\n\n\nImplement the LockingTree class:\n\n\n\tLockingTree(int[] parent) initializes the data structure with the parent array.\n\tlock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user.\n\tunlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked.\n\tupgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]\nOutput\n[null, true, false, true, true, true, false]\n\nExplanation\nLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2);    // return true because node 2 is unlocked.\n                           // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3);  // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2);  // return true because node 2 was previously locked by user 2.\n                           // Node 2 will now be unlocked.\nlockingTree.lock(4, 5);    // return true because node 4 is unlocked.\n                           // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n                           // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1);    // return false because node 0 is already locked.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == parent.length\n\t2 &lt;= n &lt;= 2000\n\t0 &lt;= parent[i] &lt;= n - 1 for i != 0\n\tparent[0] == -1\n\t0 &lt;= num &lt;= n - 1\n\t1 &lt;= user &lt;= 104\n\tparent represents a valid tree.\n\tAt most 2000 calls in total will be made to lock, unlock, and upgrade.\n\n",
        "solution_py": "class LockingTree:\n\n    def __init__(self, parent: List[int]):\n        self.p = collections.defaultdict(lambda: -2)\n        self.c = collections.defaultdict(list)\n        for i, p in enumerate(parent):\n            self.c[p].append(i)\n            self.p[i] = p\n        self.user = collections.defaultdict(set)\n        self.node = collections.defaultdict(lambda: -2)\n\n    def lock(self, num: int, user: int) -> bool:\n        if self.node[num] == -2:\n            self.user[user].add(num)\n            self.node[num] = user\n            return True\n        return False \n\n    def unlock(self, num: int, user: int) -> bool:\n        if self.node[num] == user: \n            del self.node[num]\n            self.user[user].remove(num)\n            return True\n        return False        \n\n    def upgrade(self, num: int, user: int) -> bool:\n        if self.node[num] != -2: return False\n        if not self.has_locked_descendant(num): return False\n        if self.has_locked_ancester(num): return False\n        self.lock(num, user)\n        self.unlock_descendant(num)\n        return True\n    \n    def has_locked_descendant(self, num):  #function to check if alteast one desendent is lock or not \n        has = False\n        for child in self.c[num]:\n            if self.node[child] != -2:\n                return True\n            has |= self.has_locked_descendant(child)\n        return has               \n        \n    def has_locked_ancester(self, num):   # function to check if no parent is locked \n        if num == -1: return False\n        if self.node[self.p[num]] != -2:\n            return True\n        return self.has_locked_ancester(self.p[num])\n\n    def unlock_descendant(self, num):   # function fro unlocking all desendents \n        for child in self.c[num]:\n            if child in self.node:\n                user = self.node[child]\n                del self.node[child]\n                if user in self.user:\n                    self.user[user].remove(child)\n            self.unlock_descendant(child)",
        "solution_js": "var LockingTree = function(parent) {\n    this.parents = parent;\n    this.children  = [];\n    this.locked = new Map();\n    \n    for (let i = 0; i < this.parents.length; ++i) {\n        this.children[i] = [];\n    }\n    \n    for (let i = 1; i < this.parents.length; ++i) {\n        const parent = this.parents[i];\n        \n        this.children[parent].push(i);\n    }\n};\n\nLockingTree.prototype.lock = function(num, user) {\n    if (this.locked.has(num)) return false;\n\n    this.locked.set(num, user);\n   \n    return true;\n};\n\nLockingTree.prototype.unlock = function(num, user) {\n    if (!this.locked.has(num) || this.locked.get(num) != user) return false;\n    \n    this.locked.delete(num);\n    \n    return true;\n};\n\nLockingTree.prototype.upgrade = function(num, user) {\n    let isLocked = traverseUp(num, this.parents, this.locked);\n\n    if (isLocked) return false;\n\n    const queue = [];\n\n    isLocked = false;\n\n    queue.push(num);\n\n    while (queue.length > 0) {\n        const node = queue.shift();\n\n        if (node != num && this.locked.has(node)) {\n            isLocked = true;\n            this.locked.delete(node);\n        }\n\n        for (let i = 0; i < this.children[node].length; ++i) {\n            queue.push(this.children[node][i]);\n        }\n    } \n\n    if (!isLocked) return false;\n\n    this.locked.set(num, user);\n\n    return true;\n\n\n    function traverseUp(num, parents, locked) {\n        if (locked.has(num)) return true;\n        if (num === 0) return false;\n\n        const parentIdx = parents[num];\n\n        return traverseUp(parentIdx, parents, locked);\n    }\n};",
        "solution_java": "class LockingTree {\n    int[] p;\n    Map<Integer, Integer> map = new HashMap<>();\n    Map<Integer, List<Integer>> children = new HashMap<>();\n    public LockingTree(int[] parent) {\n        p = parent;\n        for(int i = 0; i < p.length; i ++) {\n            children.put(i, new ArrayList<>());\n        }\n        for(int i = 1; i < p.length; i ++) {\n            children.get(p[i]).add(i);\n        }\n    }\n    \n    public boolean lock(int num, int user) {\n        if(!map.containsKey(num)) {\n            map.put(num, user);\n            return true;\n        } \n        return false;\n    }\n    \n    public boolean unlock(int num, int user) {\n        if(map.containsKey(num) && map.get(num) == user) {\n            map.remove(num);\n            return true;\n        }\n        return false;\n    }\n    \n    public boolean upgrade(int num, int user) {\n        //check the node\n        if(map.containsKey(num)) return false;\n        //check Ancestor\n        int ori = num;\n        while(p[num] != -1) {\n            if(map.get(p[num]) != null) return false;\n            num = p[num];\n        }\n        //check Decendant\n        Queue<Integer> q = new LinkedList<>();\n        List<Integer> child = children.get(ori);\n        if(child != null) {\n            for(int c : child) q.offer(c);\n        }\n        boolean lock = false;\n        while(!q.isEmpty()) {\n            int cur = q.poll();\n            if(map.get(cur) != null) {\n                lock = true;\n                map.remove(cur); // unlock\n            }\n            List<Integer> cc = children.get(cur);\n            if(cc != null) {\n                for(int c : cc) q.offer(c);\n            }\n        }        \n        if(!lock) return false;\n        map.put(ori, user); // lock the original node\n        return true;\n    }\n}",
        "solution_c": "class LockingTree {\npublic:\n    \n    unordered_map<int,int> locks_aquired;\n    vector<vector<int>> graph;\n    unordered_map<int,int> parents;\n    \n    LockingTree(vector<int>& parent)\n    {   \n        int n=parent.size();\n        graph =  vector<vector<int> >(n);\n        parents[0] = -1 ;   // since parent of node 0 is always -1 \n\n        for(int i=1; i<n; i++)\n        {\n            parents[i] = parent[i];  \n            graph[parent[i]].push_back(i);\n        }\n    }\n     \n    bool lock(int num, int user)    \n    {\n        if(locks_aquired.find(num) == locks_aquired.end())\n            { locks_aquired[num]=user; return 1;}\n        return 0;\n    }\n    \n    \n    bool unlock(int num, int user)      \n    {\n        if(locks_aquired.find(num) != locks_aquired.end() && locks_aquired[num]==user)\n            {   locks_aquired.erase(num); return 1;}\n        return 0;\n    }\n    \n    bool check_ans(int num)\n    {\n        while(num != -1)\n        {\n            if(locks_aquired.find(num) != locks_aquired.end()) return 0;\n            num = parents[num];   \n        }\n        return 1;\n    }\n    \n    bool dfs(int num)   // function to check if alteast one desendent is lock or not \n    {\n        for(int i=0; i<graph[num].size(); i++)\n        {\n            int x = graph[num][i]; \n            if( locks_aquired.find(x) != locks_aquired.end())\n                return 1;\n            if( dfs(x)) return 1;\n        }\n        return 0; \n    }\n    \n    void unlock_descendents(int num)   \n    {\n        for(int i=0; i<graph[num].size(); i++)\n        {\n            int x = graph[num][i]; \n            if( locks_aquired.find(x) != locks_aquired.end())\n                locks_aquired.erase(x);\n            dfs_des(x);\n        }\n    }\n    \n    bool upgrade(int num, int user) \n    {   \n        if( locks_aquired.find(num) != locks_aquired.end()) return 0;     // if current node is locked can't lock it again \n        \n        if( dfs(num) && check_ans(parents[num]))  \n        {\n            unlock_descendents(num); \n            locks_aquired[num]=user;\n            return 1;\n        }\n        return 0;\n    }\n};\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * LockingTree* obj = new LockingTree(parent);\n * bool param_1 = obj->lock(num,user);\n * bool param_2 = obj->unlock(num,user);\n * bool param_3 = obj->upgrade(num,user);\n */"
    },
    {
        "title": "Design Parking System",
        "algo_input": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.\n\nImplement the ParkingSystem class:\n\n\n\tParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.\n\tbool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]\nOutput\n[null, true, true, false, false]\n\nExplanation\nParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= big, medium, small &lt;= 1000\n\tcarType is 1, 2, or 3\n\tAt most 1000 calls will be made to addCar\n\n",
        "solution_py": "class ParkingSystem:\n    def __init__(self, big: int, medium: int, small: int):\n        self.vehicle  =[big,medium,small]\n\n    def addCar(self, carType: int) -> bool:\n        if carType == 1 :\n            if self.vehicle[0] > 0:\n                self.vehicle[0]-=1\n                return True\n        elif carType == 2:\n            if self.vehicle[1] > 0:\n                self.vehicle[1]-=1\n                return True\n        elif carType == 3:\n            if self.vehicle[2] > 0:\n                self.vehicle[2]-=1\n                return True\n        return False",
        "solution_js": "var ParkingSystem = function(big, medium, small) {\n    this.count = [big, medium, small];\n};\n\n/** \n * @param {number} carType\n * @return {boolean}\n */\nParkingSystem.prototype.addCar = function(carType) {\n  return this.count[carType - 1]-- > 0;\n};\n\n/** \n * Your ParkingSystem object will be instantiated and called as such:\n * var obj = new ParkingSystem(big, medium, small)\n * var param_1 = obj.addCar(carType)\n */",
        "solution_java": "class ParkingSystem {\n    private int[] size;\n    public ParkingSystem(int big, int medium, int small) {\n        this.size = new int[]{big, medium, small};\n    }\n    \n    public boolean addCar(int carType) {\n        return size[carType-1]-->0;\n    }\n}",
        "solution_c": "class ParkingSystem {\npublic: vector<int> vehicle;\npublic:\n    ParkingSystem(int big, int medium, int small) {\n        vehicle = {big, medium, small};\n    }\n\n    bool addCar(int carType) {\n        return vehicle[carType - 1]-- > 0;\n    }"
    },
    {
        "title": "Number of Good Pairs",
        "algo_input": "Given an array of integers nums, return the number of good pairs.\n\nA pair (i, j) is called good if nums[i] == nums[j] and i &lt; j.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,1,1,3]\nOutput: 4\nExplanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.\n\n\nExample 2:\n\nInput: nums = [1,1,1,1]\nOutput: 6\nExplanation: Each pair in the array are good.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "from itertools import combinations\nclass Solution:\n    def numIdenticalPairs(self, nums) -> int:\n        res = 0\n\t\tnums_set = set(nums)\n        nums_coppy = nums\n        for number in nums_set:\n            number_found = []\n            deleted = 0\n            while True:\n                try:\n                    found = nums_coppy.index(number)\n                    nums_coppy.remove(number)\n                    if deleted > 0:\n                        number_found.append(found + deleted)\n                    else:\n                        number_found.append(found + deleted)\n                    deleted += 1\n                except:\n                    comb = list(combinations(number_found, 2))\n                    res += len(comb)\n                    break\n        return res",
        "solution_js": "var numIdenticalPairs = function(nums) {\n    let counter = 0;\n    let map = {};\n    for(let num of nums) {\n        if(map[num]) {\n            counter += map[num];\n            map[num]++;\n        } else {\n            map[num] = 1;\n        }\n    }\n    return counter;\n};",
        "solution_java": "class Solution {\n    public int numIdenticalPairs(int[] nums) {\n        int len =nums.length;\n        int counter=0;\n        for (int i =0;i<len;i++){\n            for (int j=i+1;j<len;j++){\n                if(nums[i]==nums[j]){\n                    counter++; \n                }           \n            }\n            \n        }\n        return counter;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numIdenticalPairs(vector<int>& nums) {\n\n        int cnt = 0;\n        for(int i=0 ; i<nums.size() ; i++){\n            for(int j=i+1 ; j<nums.size() ; j++){\n                if(nums[i] == nums[j]){\n                    cnt++;\n                }\n            }\n        }\n\n        return cnt;\n    }\n};"
    },
    {
        "title": "Reverse Nodes in Even Length Groups",
        "algo_input": "You are given the head of a linked list.\n\nThe nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,\n\n\n\tThe 1st node is assigned to the first group.\n\tThe 2nd and the 3rd nodes are assigned to the second group.\n\tThe 4th, 5th, and 6th nodes are assigned to the third group, and so on.\n\n\nNote that the length of the last group may be less than or equal to 1 + the length of the second to last group.\n\nReverse the nodes in each group with an even length, and return the head of the modified linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [5,2,6,3,9,1,7,3,8,4]\nOutput: [5,6,2,3,9,1,4,8,3,7]\nExplanation:\n- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.\n\n\nExample 2:\n\nInput: head = [1,1,0,6]\nOutput: [1,0,1,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.\n\n\nExample 3:\n\nInput: head = [1,1,0,6,5]\nOutput: [1,0,1,5,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 105].\n\t0 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        group = 2\n        tail = head # tail of previous group\n        while tail and tail.next:\n            cnt = 1 # actual size of the current group\n            cur = tail.next # first node of the current group\n            while cur.next and cnt < group:\n                cur = cur.next\n                cnt += 1\n            pre, cur = tail, tail.next\n            if cnt % 2 == 0: # if group size is even\n                while cnt and cur:\n                    nxt = cur.next\n                    cur.next = pre\n                    pre = cur\n                    cur = nxt\n                    cnt -= 1\n                first = tail.next # first node of the original group\n                first.next = cur\n                tail.next = pre\n                tail = first\n            else:\n                while cnt and cur:\n                    pre, cur = cur, cur.next\n                    cnt -= 1\n                tail = pre\n            group += 1\n        return head",
        "solution_js": "var reverseEvenLengthGroups = function(head) {\n    let groupSize = 2;\n\n    let start = head;\n\n    let prev = head;\n    let curr = head.next;\n\n    let count = 0;\n    \n    while (curr != null) {\n        if (count === groupSize) {\n            if (groupSize % 2 === 0) { // we only reverse when it is even\n                const end = curr;\n                const tail = start.next; // the starting node of the reverse linked list will be the tail after the reverse takes place\n                reverseList(start, end, count); // we need to reverse everything in the middle of start and end \n                start = tail; // we set the new start to the end of the reversed linked list\n            }\n            else { // when groupSize is even we don't need to reverse, but need to set the new start to the prev node\n                start = prev;\n            }\n            count = 0; // whenever we reached the group size we need to reset our count and up our groupSize\n            ++groupSize;\n        }\n        else { // just a normal traversal when we haven't hit our groupSize\n            prev = curr;        \n            curr = curr.next;\n            ++count;\n        }\n    }\n   \n    if (count % 2 === 0) { // in the case where we ended early on even count\n         reverseList(start, null, count);\n    }\n    \n    return head;\n    \n    \n    function reverseList(start, end, count) {\n        if (start.next == null) return start; // for case when we have a single node\n        \n        let prev = start;\n        \n        let curr = start.next;\n        let tail = start.next;\n        \n        for (let i = 0; i < count; ++i) {\n            const next = curr.next;\n            curr.next = prev;\n            prev = curr;\n            curr = next;\n        }\n        \n        start.next = prev;\n        tail.next = end;\n        \n        return ;\n    }\n};",
        "solution_java": "// This Question can be solved easily using two standard methods of LinkedList\n// 1) addFirst (it adds node in front of the LinkedList)\n// 2) addLast (it adds node in end of the LinkedList)\n\nclass Solution {\n\n    static ListNode oh;\n    static ListNode ot;\n    static ListNode th;\n    static ListNode tt;\n\n    public ListNode reverseEvenLengthGroups(ListNode head) {\n\n        oh = null;\n        ot = null;\n        th = null;\n        tt = null;\n\n        if(head == null || head.next == null)\n            return head;\n\n        int size = length(head);\n        int idx = 1;\n        ListNode curr = head;\n        int group = 1;\n\n        while(curr!=null)\n        {\n            int temp = size - idx + 1;\n            if((temp>=group && group%2 == 0) || (temp<group && temp%2 == 0))\n            {\n                int k = group;\n                while(k-->0 && curr!=null)\n                {\n                    ListNode t = curr.next;\n                    curr.next = null;\n                    addFirst(curr);\n                    curr = t;\n                    idx++;\n                }\n            }\n            else\n            {\n                int k = group;\n                while(k-->0 && curr!=null)\n                {\n                    ListNode t = curr.next;\n                    curr.next = null;\n                    addLast(curr);\n                    curr = t;\n                    idx++;\n                }\n            }\n\n            if(oh==null && ot==null)\n            {\n                oh = th;\n                ot = tt;\n            }\n            else\n            {\n                ot.next = th;\n                ot = tt;\n            }\n\n            th = null;\n            tt = null;\n            group++;\n        }\n\n        return oh;\n    }\n\n    public int length (ListNode head)\n    {\n        if(head==null) return 0;\n        ListNode curr = head;\n        int k = 0;\n        while(curr!=null)\n        {\n             k++;\n            curr = curr.next;\n        }\n        return k;\n    }\n\n    public void addFirst(ListNode head)\n    {\n        if(tt == null && th == null)\n        {\n            th = head;\n            tt = head;\n        }\n        else\n        {\n            head.next = th;\n            th = head;\n        }\n    }\n\n    public void addLast(ListNode head)\n    {\n        if(tt == null && th == null)\n        {\n            th = head;\n            tt = head;\n        }\n        else\n        {\n            tt.next = head;\n            tt = head;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // Function to reverse a linked list\n    ListNode* reverseList(ListNode* head) {\n        if(!head)\n            return head;\n        ListNode* prev = NULL;\n        while(head) {\n            ListNode* temp = head -> next;\n            head -> next = prev;\n            prev = head;\n            head = temp;\n        }\n\n        return prev;\n    }\n\n    ListNode* reverseEvenLengthGroups(ListNode* head) {\n        // Creating a dummy node to avoid adding checks for the first node\n        ListNode* dummy = new ListNode();\n        dummy -> next = head;\n\n        ListNode* prev = dummy;\n\n        // Loop to determine the lengths of groups\n        for(int len = 1; len < 1e5 && head; len++) {\n            ListNode* tail = head;\n            ListNode* nextHead;\n\n            // Determining the length of the current group\n            // Its maximum length can be equal to len\n            int j = 1;\n            while(j < len && tail && tail -> next) {\n                tail = tail -> next;\n                j++;\n            }\n\n            // Head of the next group\n            nextHead = tail -> next;\n\n            if((j % 2) == 0) {\n                // If even sized group is found\n                // Reversing the group and setting prev and head appropriately\n                tail -> next = NULL;\n                prev -> next = reverseList(head);\n                prev = head;\n                head -> next = nextHead;\n                head = nextHead;\n            } else {\n                // If group is odd sized, then simply going towards the next group\n                prev = tail;\n                head = nextHead;\n            }\n        }\n\n        // Returning the head\n        return dummy -> next;\n    }\n};"
    },
    {
        "title": "Find the Highest Altitude",
        "algo_input": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.\n\nYou are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 &lt;= i &lt; n). Return the highest altitude of a point.\n\n&nbsp;\nExample 1:\n\nInput: gain = [-5,1,5,0,-7]\nOutput: 1\nExplanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\n\n\nExample 2:\n\nInput: gain = [-4,-3,-2,-1,4,3,2]\nOutput: 0\nExplanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == gain.length\n\t1 &lt;= n &lt;= 100\n\t-100 &lt;= gain[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def largestAltitude(self, gain: List[int]) -> int:\n        return max(accumulate([0]+gain))",
        "solution_js": "var largestAltitude = function(gain) {\n    let points = [0]\n    let highest = 0\n\n    for (let i = 0; i < gain.length; i++) {\n        let point = points[i] + gain[i]\n        points.push(point)\n        if (point > highest) highest = point\n    }\n\n    return highest\n};",
        "solution_java": "class Solution {\n    public int largestAltitude(int[] gain) {\n         int max_alt=0;\n        int curr_alt=0;\n        for(int i=0;i<gain.length;i++){\n            curr_alt+=gain[i];\n            max_alt=Math.max(curr_alt, max_alt);\n        }\n        return max_alt;\n    }\n}\n\n//TC: O(n), SC: O(1)",
        "solution_c": "class Solution {\npublic:\n    int largestAltitude(vector<int>& gain) {\n        int maxAltitude = 0;\n        int currentAltitude = 0;\n        \n        for (int i = 0; i < gain.size(); i++) {\n            currentAltitude += gain[i];\n            maxAltitude = max(maxAltitude, currentAltitude);\n        }\n        \n        return maxAltitude;\n    }\n};"
    },
    {
        "title": "Largest Plus Sign",
        "algo_input": "You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.\n\nReturn the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.\n\nAn axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, mines = [[4,2]]\nOutput: 2\nExplanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\n\n\nExample 2:\n\nInput: n = 1, mines = [[0,0]]\nOutput: 0\nExplanation: There is no plus sign, so return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 500\n\t1 &lt;= mines.length &lt;= 5000\n\t0 &lt;= xi, yi &lt; n\n\tAll the pairs (xi, yi) are unique.\n\n",
        "solution_py": "class Solution:\n\n    def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:\n        matrix = [1] * n\n        aux = {}\n        hasOne = False\n        for i in range(0,n):\n            matrix[i] = [1] * n\n        for mine in mines:\n            matrix[mine[0]][mine[1]] = 0\n        for i in range(0,n):\n            for j in range(0,n):\n                if(matrix[i][j] == 1):\n                    hasOne = True\n                if((i,j) not in aux):\n                    aux[(i,j)] = {\"t\":0,\"l\":0,\"r\":0,\"b\":0}\n                if(j>0 and matrix[i][j] == 1 and matrix[i][j-1] == 1):\n                    aux[(i,j)][\"l\"] = aux[(i,j-1)][\"l\"] + 1  \n                if(i>0 and matrix[i][j] == 1 and matrix[i-1][j] == 1):\n                    aux[(i,j)][\"t\"] = aux[(i-1,j)][\"t\"] + 1\n        \n        maxOrder = 0 \n        for i in range(n-1,-1,-1):\n            if(i<maxOrder):\n                    break\n            for j in range(n-1,-1,-1):\n                if(j<maxOrder):\n                    break\n                if(j<n-1 and matrix[i][j] == 1 and matrix[i][j+1] == 1):\n                    aux[(i,j)][\"r\"] = aux[(i,j+1)][\"r\"] + 1  \n                if(i<n-1 and matrix[i][j] == 1 and matrix[i+1][j]):\n                    aux[(i,j)][\"b\"] = aux[(i+1,j)][\"b\"] + 1\n                maxOrder = max(min(aux[(i,j)][\"b\"],aux[(i,j)][\"t\"],aux[(i,j)][\"r\"],aux[(i,j)][\"l\"]),maxOrder)\n \n        print(maxOrder+1)\n        return maxOrder + 1 ",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} mines\n * @return {number}\n */\nvar orderOfLargestPlusSign = function(n, mines) {\n    // create n * n as a table, and each grid fill the maximum number\n    const t = new Array(n).fill(0).map(() => new Array(n).fill(n));\n\n    // insert `0` to the grid in table according the position in mines\n    mines.forEach(a => t[a[0]][a[1]] = 0);\n\n    // loop each rows and cols\n    // - for rows: calculate non-zero grid from left to right\n    // - for cols: calculate non-zero grid from top to bottom\n    // - when the loop is completed, all of non-zero values will be calculated by four directions\n    // - and these grids value will be updated by comparing. then we can obtain the minimum value of the four directions caculation, which is the maximum of the grid\n    for (let i = 0; i < n; i++) {\n        // save the maximum value of non-zeros with for directions\n        let [l, r, u, d] = [0, 0, 0, 0];\n\n        // l: left,  loop row i from left to right\n        // r: right, loop row i from right to left\n        // u: up,    loop col i from top to bottom\n        // d: down,  loop col i from bottom to top\n        for (let j = 0, k = n - 1; j < n; j++, k--) {\n            // if the value is `0`, then set variable to `0`, and indicates it's broken\n            l = t[i][j] && l + 1;\n            r = t[i][k] && r + 1;\n            u = t[j][i] && u + 1;\n            d = t[k][i] && d + 1;\n\n            // if current value is less than origin value\n            // one possibility: the origin value is default\n            // another possibility: the length of non-zero in a centain direction is langer than in the current direction, which the minimum value we need\n            if (l < t[i][j]) t[i][j] = l;\n            if (r < t[i][k]) t[i][k] = r;\n            if (u < t[j][i]) t[j][i] = u;\n            if (d < t[k][i]) t[k][i] = d;\n        }\n    }\n\n    // return maximum value be saved by all cells\n    return Math.max(...t.map(v => Math.max(...v)));\n}",
        "solution_java": "class Solution {\n    public int orderOfLargestPlusSign(int n, int[][] mines) {\n        // Create the matrix\n        int[][] arr = new int[n][n];\n        for(int[] subArray : arr) {\n            Arrays.fill(subArray, 1);\n        }\n\n        for(int i = 0; i < mines.length; i++) {\n            arr[mines[i][0]][mines[i][1]] = 0;\n        }\n\n        // Prefix Count DP arrays\n        int[][] dpTop = new int[arr.length][arr.length];\n        int[][] dpLeft = new int[arr.length][arr.length];\n        int[][] dpRight = new int[arr.length][arr.length];\n        int[][] dpBottom = new int[arr.length][arr.length];\n\n        // Prefix count of 1 cells on top and left directions\n        for(int i = 0; i < arr.length; i++) {\n            for(int j = 0; j < arr.length; j++) {\n                if(i - 1 >= 0 && arr[i - 1][j] == 1) {\n                    dpTop[i][j] = 1 + dpTop[i - 1][j];\n                }\n\n                if(j - 1 >= 0 && arr[i][j - 1] == 1) {\n                    dpLeft[i][j] = 1 + dpLeft[i][j - 1];\n                }\n            }\n        }\n\n        // Prefix count of 1 cells on bottom and right directions\n        for(int i = arr.length - 1; i >= 0; i--) {\n            for(int j = arr.length - 1; j >= 0; j--) {\n                if(i + 1 < arr.length && arr[i + 1][j] == 1) {\n                    dpBottom[i][j] = 1 + dpBottom[i + 1][j];\n                }\n\n                if(j + 1 < arr.length && arr[i][j + 1] == 1) {\n                    dpRight[i][j] = 1 + dpRight[i][j + 1];\n                }\n            }\n        }\n\n        int maxPlusSignLength = 0;\n        for(int i = 0; i < arr.length; i++) {\n            for(int j = 0; j < arr.length; j++) {\n                if(arr[i][j] == 0) continue;\n\n                // Minimum adjacent 1 cell count from all four directions to ensure symmetry\n                int minAdjacentOnes = Math.min(Math.min(dpTop[i][j], dpBottom[i][j]), Math.min(dpLeft[i][j], dpRight[i][j]));\n                maxPlusSignLength = Math.max(maxPlusSignLength, minAdjacentOnes + 1);\n            }\n        }\n\n        return maxPlusSignLength;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {\n        //jai shri ram\n        int ans=0;\n        vector<bool>block(25*int(1e4)+1,0);\n        vector<vector<int>>dp(n,vector<int>(n,0));\n        for(auto x:mines){\n            int a=x[0],b=x[1];\n            block[a*n+b]=true;\n        }\n        for(int i=0;i<n;i++){\n            int sum=0;\n            for(int j=0;j<n;j++){\n                if(block[i*n+j]){\n                    sum=0;\n                }else {\n                    sum+=1;\n                }\n                dp[i][j]=sum;\n            }\n        }\n        for(int j=0;j<n;j++){\n            int sum=0;\n            for(int i=0;i<n;i++){\n                if(block[i*n+j]){\n                    sum=0;\n                }else sum+=1;\n                dp[i][j]=min(dp[i][j],sum);\n            }\n        }\n        for(int j=n-1;j>=0;j--){\n            int sum=0;\n            for(int i=n-1;i>=0;i--){\n                if(block[i*n+j]){\n                    sum=0;\n                }else sum+=1;\n                dp[i][j]=min(dp[i][j],sum);\n            }\n        }\n        for(int i=n-1;i>=0;i--){\n            int sum=0;\n            for(int j=n-1;j>=0;j--){\n                if(block[i*n+j]){\n                    sum=0;\n                }else sum+=1;\n                dp[i][j]=min(dp[i][j],sum);\n                ans=max(ans,dp[i][j]);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Target Indices After Sorting Array",
        "algo_input": "You are given a 0-indexed integer array nums and a target element target.\n\nA target index is an index i such that nums[i] == target.\n\nReturn a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,5,2,3], target = 2\nOutput: [1,2]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.\n\n\nExample 2:\n\nInput: nums = [1,2,5,2,3], target = 3\nOutput: [3]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.\n\n\nExample 3:\n\nInput: nums = [1,2,5,2,3], target = 5\nOutput: [4]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i], target &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def targetIndices(self, nums, target):\n        ans = []\n        for i,num in enumerate(sorted(nums)):\n            if num == target: ans.append(i)\n        return ans",
        "solution_js": "function binarySearch(lists, sorted, low, high, target){\n    if(low > high) return;\n\n    const mid = low + Math.floor((high - low) / 2);\n\n    if(sorted[mid] === target){\n    lists.push(mid);\n    }\n\n    binarySearch(lists, sorted, low, mid-1, target);\n    binarySearch(lists, sorted, mid+1, high, target);\n}\n\nvar targetIndices = function(nums, target) {\n    let result = [];\n    nums.sort((a,b)=>a-b);\n    if(!nums.includes(target)) return [];\n\n    binarySearch(result, nums, 0 , nums.length-1, target);\n    return result.sort((a,b) => a-b);\n}",
        "solution_java": "class Solution {\n    /** Algorithm:\n        - Parse the array once and count how many are lesser than target and how many are equal\n        - DO NOT sort the array as we don't need it sorted.\n          Just to know how many are lesser and how many are equal. O(N) better than O(NlogN - sorting)\n        - The response list will have a size = with the number of equal elements (as their positions)\n        - Loop from smaller to smaller+equal and add the values into the list. Return the list\n    */\n    public List<Integer> targetIndices(int[] nums, int target) {\n        int smaller = 0;\n        int equal = 0;\n        for (int num : nums) {\n            if (num < target) {\n                smaller++;\n            } else if (num == target) {\n                equal++;\n            }\n        }\n        List<Integer> indices = new ArrayList<>(equal);\n        for (int i = smaller; i < smaller + equal; i++) {\n            indices.add(i);\n        }\n        return indices;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> targetIndices(vector<int>& nums, int target) {\n        vector<int> result;\n        sort(nums.begin(),nums.end());\n        for(int i=0;i<nums.size();i++){\n            if(nums[i]==target) result.push_back(i);\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Smallest Number in Infinite Set",
        "algo_input": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].\n\nImplement the SmallestInfiniteSet class:\n\n\n\tSmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.\n\tint popSmallest() Removes and returns the smallest integer contained in the infinite set.\n\tvoid addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]\nOutput\n[null, null, 1, 2, 3, null, 1, 4, 5]\n\nExplanation\nSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2);    // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1);    // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n                                   // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 1000\n\tAt most 1000 calls will be made in total to popSmallest and addBack.\n\n",
        "solution_py": "class SmallestInfiniteSet:\n\n    def __init__(self):\n        self.index = 1\n        self.heap = []\n\n    def popSmallest(self) -> int:\n        if self.heap:\n            return heapq.heappop(self.heap)\n        self.index += 1\n        return self.index-1\n\n    def addBack(self, num: int) -> None:\n        if self.index > num and num not in self.heap:\n            heapq.heappush(self.heap,num)",
        "solution_js": "var SmallestInfiniteSet = function() {\n    const s = new Set();\n    this.s = s;\n    for(let i = 1; i <= 1000; i++) s.add(i);\n};\n\n/**\n * @return {number}\n */\nSmallestInfiniteSet.prototype.popSmallest = function() {\n    const min = Math.min(...Array.from(this.s));\n    this.s.delete(min);\n    return min;\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nSmallestInfiniteSet.prototype.addBack = function(num) {\n    this.s.add(num);\n};\n\n/**\n * Your SmallestInfiniteSet object will be instantiated and called as such:\n * var obj = new SmallestInfiniteSet()\n * var param_1 = obj.popSmallest()\n * obj.addBack(num)\n */",
        "solution_java": "class SmallestInfiniteSet {\n    private PriorityQueue<Integer> q;\n    private int index;\n    public SmallestInfiniteSet() {\n        q = new PriorityQueue<Integer>();\n        index = 1;\n    }\n    \n    public int popSmallest() {\n        if (q.size()>0){\n            return q.poll();\n        }\n        return index++;\n    }\n    \n    private boolean is_in_q(int num){\n        for(int i : q){\n            if (i == num){\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    public void addBack(int num) {\n        if( num < index && !is_in_q(num)){\n            q.add(num);\n        }\n    }\n}",
        "solution_c": "class SmallestInfiniteSet {\npublic:\n    int cur;\n    set<int> s;\n    SmallestInfiniteSet() {\n        cur=1;\n    }\n\n    int popSmallest() {\n        if(s.size()){\n            int res=*s.begin(); s.erase(res);\n            return res;\n        }else{\n            cur+=1;\n            return cur-1;\n        }\n    }\n\n    void addBack(int num) {\n        if(cur>num) s.insert(num);\n    }\n};"
    },
    {
        "title": "Transform to Chessboard",
        "algo_input": "You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.\n\nReturn the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.\n\nA chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.\n\n&nbsp;\nExample 1:\n\nInput: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput: 2\nExplanation: One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.\n\n\nExample 2:\n\nInput: board = [[0,1],[1,0]]\nOutput: 0\nExplanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\n\n\nExample 3:\n\nInput: board = [[1,0],[1,0]]\nOutput: -1\nExplanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == board.length\n\tn == board[i].length\n\t2 &lt;= n &lt;= 30\n\tboard[i][j] is either&nbsp;0 or 1.\n\n",
        "solution_py": "class Solution(object):\n    def movesToChessboard(self, board):\n        N = len(board)\n        ans = 0\n        # For each count of lines from {rows, columns}...\n        for count in (collections.Counter(map(tuple, board)),  # get row\n                      collections.Counter(zip(*board))): #get column\n\n            # If there are more than 2 kinds of lines,\n            # or if the number of kinds is not appropriate ...\n            if len(count) != 2 or sorted(count.values()) != [N/2, (N+1)/2]:\n                return -1\n\n            # If the lines are not opposite each other, impossible\n            line1, line2 = count\n            if not all(x ^ y for x, y in zip(line1, line2)):\n                return -1\n\n            # starts = what could be the starting value of line1\n            # If N is odd, then we have to start with the more\n            # frequent element\n            starts = [int(line1.count(1) * 2 > N)] if N%2 else [0, 1]\n\n            # To transform line1 into the ideal line [i%2 for i ...],\n            # we take the number of differences and divide by two\n            ans += min(sum((x-i) % 2 for i, x in enumerate(line1, start))\n                       for start in starts) / 2            \n\n        return ans",
        "solution_js": "/**\n * @param {number[][]} board\n * @return {number}\n */\nvar movesToChessboard = function(board) {\n    const boardSize = board.length;\n    const boardSizeIsEven = boardSize % 2 === 0;\n\n    if(!canBeTransformed(board)) return -1;\n\n    // to convert to 010101\n    let rowSwap = 0;\n    let colSwap = 0;\n\n    // to convert to 101010\n    let rowSwap2 = 0;\n    let colSwap2 = 0;\n\n    for(let i=0; i<boardSize; i++) {\n        if(board[i][0] === i % 2) {\n            rowSwap++;\n        } else {\n            rowSwap2++;\n        }\n        if(board[0][i] === i % 2) {\n            colSwap++;\n        } else {\n            colSwap2++;\n        }\n    }\n\n    // no need to swap anything\n    if((rowSwap + colSwap) === 0 || (rowSwap2 + colSwap2) === 0) return 0;\n\n    if(boardSizeIsEven) {\n        rowSwap = Math.min(rowSwap, rowSwap2);\n        colSwap = Math.min(colSwap, colSwap2);\n    } else {\n        rowSwap = rowSwap % 2 === 0 ? rowSwap : rowSwap2;\n        colSwap = colSwap % 2 === 0 ? colSwap : colSwap2;\n    }\n\n    return (rowSwap + colSwap) / 2;\n\n    function canBeTransformed(board) {\n        // number of 0 and 1 should be equal\n        let sum = board[0].reduce((a,b) => a+b);\n        if(boardSizeIsEven && sum != boardSize/2) return false;\n        if(!boardSizeIsEven && sum > ((boardSize + 1)/2)) return false;\n\n        let first = board[0].join('');\n        let opposite = board[0].map((item) => item === 1 ? 0 : 1).join('');\n        // each row should be equal to first or opposite\n        let counter = [0,0];\n        for(let i=0; i<boardSize; i++) {\n            let str = board[i].join('');\n            if(str == first) {\n                counter[0]++;\n            } else if(str == opposite) {\n                counter[1]++;\n            } else {\n                return false;\n            }\n        }\n        // for even board, two types of rows should be equal\n        if(boardSizeIsEven) {\n            return counter[0] == counter[1];\n        }\n        return Math.abs(counter[0] - counter[1]) === 1\n    }\n};",
        "solution_java": "class Solution {\n    public int movesToChessboard(int[][] board) {\n        int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n                    return -1;\n                }\n            }\n        }\n        for (int i = 0; i < N; i++) {\n            rowOneCnt += board[0][i];\n            colOneCnt += board[i][0];\n            if (board[i][0] == i % 2) {\n                rowToMove++;\n            }\n            if (board[0][i] == i % 2) {\n                colToMove++;\n            }\n        }\n        if (rowOneCnt < N / 2 || rowOneCnt > (N + 1) / 2) {\n            return -1;\n        }\n        if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {\n            return -1;\n        }\n        if (N % 2 == 1) {\n            // we cannot make it when ..ToMove is odd\n            if (colToMove % 2 == 1) {\n                colToMove = N - colToMove;\n            }\n            if (rowToMove % 2 == 1) {\n                rowToMove = N - rowToMove;\n            }\n        } else {\n            colToMove = Math.min(colToMove, N - colToMove);\n            rowToMove = Math.min(rowToMove, N - rowToMove);\n        }\n        return (colToMove + rowToMove) / 2;\n    }\n\n}",
        "solution_c": "class Solution {\n    const int inf = 1e9;\n    void transpose(vector<vector<int>>& board) {\n        const int n = board.size();\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < i; j++)\n                swap(board[i][j], board[j][i]);\n    }\n    \n    bool isSame(vector<int> &r1, vector<int>& r2) {\n        const int n = r1.size();\n        for (int i = 0; i < n; i++)\n            if (r1[i] != r2[i])\n                return false;\n        return true;\n    }\n    \n    bool isOpposite(vector<int> &r1, vector<int>& r2) {\n        const int n = r1.size();\n        for (int i = 0; i < n; i++)\n            if (r1[i] == r2[i])\n                return false;\n        return true;\n    }\n    \n    int getSteps(vector<vector<int>> &&confusionMatrix) {\n        int steps = inf;\n        \n        if (confusionMatrix[0][1] == confusionMatrix[1][0])\n            steps = confusionMatrix[0][1];\n        \n        if (confusionMatrix[0][0] == confusionMatrix[1][1])\n            steps = min(steps, confusionMatrix[0][0]);\n        \n        return steps;\n    }\n    \n    vector<vector<int>> getConfusionMatrix(vector<int>& rowType) {\n        const int n = rowType.size();\n        vector<vector<int>> confusionMatrix(2, vector<int>(2, 0));\n        for (int i = 0; i < n; i++)\n            confusionMatrix[rowType[i]][i & 1]++;\n        return confusionMatrix;\n    }\n    \n    int solve1d(vector<int> &arr) {\n        return getSteps(getConfusionMatrix(arr));\n    }\n    \n    int makeColumnsAlternating(vector<vector<int>>& board) {\n        const int n = board.size();\n        vector<int> rowType(n, 0);\n        for (int i = 1; i < n; i++)\n            if (isOpposite(board[0], board[i]))\n                rowType[i] = 1;\n            else if (!isSame(board[0], board[i]))\n                return inf;\n        return solve1d(rowType);\n    }\npublic:\n    int movesToChessboard(vector<vector<int>>& board) {\n        int steps = makeColumnsAlternating(board);\n        transpose(board);\n        steps += makeColumnsAlternating(board);\n        if (steps >= inf)\n            return -1;\n        return steps;\n    }\n};"
    },
    {
        "title": "Tree of Coprimes",
        "algo_input": "There is a tree (i.e.,&nbsp;a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.\n\nTo represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.\n\nTwo values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.\n\nAn ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.\n\nReturn an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n\n&nbsp;\nExample 1:\n\n\n\nInput: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput: [-1,0,0,1]\nExplanation: In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n  value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n  closest valid ancestor.\n\n\nExample 2:\n\n\n\nInput: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput: [-1,0,-1,0,0,0,-1]\n\n\n&nbsp;\nConstraints:\n\n\n\tnums.length == n\n\t1 &lt;= nums[i] &lt;= 50\n\t1 &lt;= n &lt;= 105\n\tedges.length == n - 1\n\tedges[j].length == 2\n\t0 &lt;= uj, vj &lt; n\n\tuj != vj\n\n",
        "solution_py": "class Solution:\n    def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n        \n        gcdset = [set() for i in range(51)]\n        for i in range(1,51):\n            for j in range(1,51):\n                if math.gcd(i,j) == 1:\n                    gcdset[i].add(j)\n                    gcdset[j].add(i)\n        \n        graph = defaultdict(list)\n        for v1, v2 in edges:\n            graph[v1].append(v2)\n            graph[v2].append(v1)\n        \n        ans = [-1]*len(nums)\n        q = [[0, {}]]\n        seen = set([0])\n        depth = 0\n        while q:\n            temp = []\n            for node, ancestors in q:\n                index_depth = (-1,-1)\n                for anc in list(ancestors.keys()):\n                    if anc in gcdset[nums[node]]:\n                        index, d = ancestors[anc]\n                        if d > index_depth[1]:\n                            index_depth = (index,d)\n                ans[node] = index_depth[0]\n                \n                copy = ancestors.copy()\n                copy[nums[node]] = (node,depth)\n                \n                for child in graph[node]:\n                    if child not in seen:\n                        seen.add(child)\n                        temp.append([child, copy])\n            q = temp\n            depth += 1\n        return ans",
        "solution_js": "var getCoprimes = function(nums, edges) {\n    \n    const node = {}\n    const ans = Array(nums.length).fill(null)\n    \n    function addNode(f, t){\n        if(!node[f]){\n            node[f]=[]\n        }\n        node[f].push(t)\n    }\n    \n    edges.forEach(([f, t])=>{\n        addNode(f, t)\n        addNode(t, f)\n    })\n    \n    function gcd(a, b){\n        while(b) [a, b] = [b, a % b];\n        return a;\n    }\n    \n    const map = []\n    for(let i=0; i<51; i++){\n        map[i]=[]\n        for(let j=0; j<51; j++){\n            map[i][j]= gcd(i,j)\n        }\n    }\n\n    let pi=-1\n    let path=Array(nums.length)\n    function check(v){\n        if(ans[v]!==null) return\n        ans[v] = -1\n        let a = nums[v]\n        for(let k=pi; k>=0; k--){\n            let b = nums[path[k]]\n            if(map[a][b]===1){\n                ans[v]=path[k]\n                break\n            }\n        }\n        if(node[v]) {\n            path[++pi]=v\n            node[v].forEach(child=>check(child))\n            pi--\n        }\n    }\n    \n    for(let i=0; i<nums.length; i++){\n        check(i)\n    }\n    \n    return ans    \n};",
        "solution_java": "class Solution {\n    //made TreeNode class for simple implementation in recurring function\n    class TreeNode{\n        int id;\n        int val;\n        List<TreeNode> child;\n        public TreeNode(int id,int val){\n            this.id=id;this.val=val;child=new ArrayList<>();\n        }\n    }\n    public int[] getCoprimes(int[] nums, int[][] edges) {\n        // making tree/graph with edges\n        TreeNode[] tr=new TreeNode[nums.length];\n        for(int i=0;i<nums.length;i++)tr[i]=new TreeNode(i,nums[i]);\n        for(int []x:edges){\n            tr[x[0]].child.add(tr[x[1]]);\n            tr[x[1]].child.add(tr[x[0]]);\n        }\n        // intializing answer array of length of tree's nodes which we will return\n        int [] ans=new int[nums.length];\n        Arrays.fill(ans,-1);\n        //creating gcd to not compute gcd everytime\n        boolean [][] gcd=new boolean[51][51];\n        for(int i=1;i<=50;i++){\n            for(int j=i;j<=50;j++){\n                if(find_gcd(i,j)==1){\n                    gcd[i][j]=true;\n                    gcd[j][i]=true;\n                }\n            }\n        }\n        int [][] latest= new int[51][2];\n\t\t//instead of latest[][] as 2d array we can also use 2 arrays, one for who is latest ancestor & one for storing id\n        // in [][0] we will store height of tree so latest ancestor will be called\n        // in [][1] we will store id of latest tree\n        // initializing all to -1\n        for(int i=0;i<=50;i++){latest[i][0]=-1;latest[i][1]=-1;}\n        find_closest_ancestor(tr[0],new TreeNode(-1,-1),ans,latest,gcd,0);\n        return ans;\n    }\n    public void find_closest_ancestor(TreeNode root,TreeNode parent, int[] ans,int [][] latest, boolean [][] gcd, int height){\n        int val=root.val;\n        int latest_id=0;\n        for(int i=1;i<=50;i++){\n            //if gcd [val][i] is true & latest[i][0] is latest ancestor i.e. it's height is more then save that id\n            if(gcd[val][i] && latest[latest_id][0] < latest[i][0])latest_id=i;\n        }\n        ans[root.id]=latest[latest_id][1];// even if no latest ancestor found latest[id][1] is -1 by default\n        \n        //this is must we will save before state & after calling all it's child we will make it as it was before calling\n        //like backtracking\n        int pre_height = latest[val][0],pre_id = latest[val][1];\n        latest[val][0]=height;  latest[val][1]=root.id;\n        \n        // we recur with all child\n        for(TreeNode root_child: root.child){\n            // we will check if we aren't going upward in tree so root.child!=parent then call function\n            if(root_child!=parent)find_closest_ancestor(root_child,root,ans,latest,gcd,height+1);\n        }\n        //as it was before we will put it back\n        latest[val][0]=pre_height;  latest[val][1]=pre_id;\n    }\n    //simple gcd code\n    public int find_gcd(int a, int b){\n        if(b==0)return a;\n        return find_gcd(b,a%b);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> adj[100009];\n    vector<int> d[55];\n    int dis[100009];\n    void dfs(vector<int>& nums,vector<int> &ans,int i,int p,int h1)\n    {\n        int h=nums[i];\n        dis[i]=h1;\n        ans[i]=-1;\n        int val=-1;\n        for(int w=1;w<=50;w++)\n        {\n            if(__gcd(h,w)==1)\n            {\n                if(d[w].size())\n                {\n                    int u=d[w].back();\n                    if(dis[u]>val)\n                    {\n                        val=dis[u];\n                        ans[i]=u;\n                    }\n                }\n            }\n        }\n        d[h].push_back(i);\n        for(auto x:adj[i])\n        {\n            if(x==p) continue;\n            dfs(nums,ans,x,i,h1+1);\n        }\n        d[h].pop_back();\n    }\n    vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {\n        int n=nums.size();\n        for(int i=0;i<n;i++)\n        {\n            adj[i].clear();\n        }\n        for(int i=0;i<n-1;i++)\n        {\n            adj[edges[i][0]].push_back(edges[i][1]);\n            adj[edges[i][1]].push_back(edges[i][0]);\n        }\n        vector<int> ans(n);\n        dfs(nums,ans,0,-1,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimized Maximum of Products Distributed to Any Store",
        "algo_input": "You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.\n\nYou need to distribute all products to the retail stores following these rules:\n\n\n\tA store can only be given at most one product type but can be given any amount of it.\n\tAfter distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.\n\n\nReturn the minimum possible x.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, quantities = [11,6]\nOutput: 3\nExplanation: One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.\n\n\nExample 2:\n\nInput: n = 7, quantities = [15,10,10]\nOutput: 5\nExplanation: One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.\n\n\nExample 3:\n\nInput: n = 1, quantities = [100000]\nOutput: 100000\nExplanation: The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == quantities.length\n\t1 &lt;= m &lt;= n &lt;= 105\n\t1 &lt;= quantities[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minimizedMaximum(self, n: int, quantities: List[int]) -> int:\n        def cond(m, n):\n            return sum([(q // m) + (q % m > 0) for q in quantities]) <= n\n        \n        l, r = 1, max(quantities)\n        while l < r:\n            m = (l + r) // 2\n            if cond(m, n):\n                r = m\n            else:\n                l = m + 1\n        return l",
        "solution_js": "var minimizedMaximum = function(n, quantities) {\n    const MAX = Number.MAX_SAFE_INTEGER;\n    const m = quantities.length;\n\n    let left = 1;\n    let right = quantities.reduce((acc, num) => acc + num, 0);\n\n    let minRes = MAX;\n\n    while (left <= right) {\n        const mid = (left + right) >> 1;\n\n        if (canDistribute(mid)) {\n            minRes = Math.min(minRes, mid);\n            right = mid - 1;\n        }\n        else {\n            left = mid + 1;\n        }\n    }\n\n    return minRes;\n\n    function canDistribute(minGiven) {\n        const clonedQ = [...quantities];\n\n        let j = 0;\n        let i = 0;\n\n        for (; i < n && j < m; ++i) {\n            const remQ = clonedQ[j];\n\n            if (remQ > minGiven) {\n                clonedQ[j] -= minGiven;\n            }\n            else {\n                ++j;\n            }\n        }\n\n        return j === m;\n    }\n};",
        "solution_java": "class Solution {\n    public int minimizedMaximum(int n, int[] quantities) {\n        \n        int lo = 1;\n        int hi = (int)1e5;\n        \n        int ans = -1;\n        \n        while(lo <= hi){\n            \n            int mid = (lo + hi)/2;\n            \n            if(isItPossible(mid, quantities, n)){\n                ans = mid;\n                hi = mid-1;\n            }else{\n                lo = mid+1;\n            }\n        }\n        \n        return ans;\n    }\n    \n    private boolean isItPossible(int x, int[] quantities, int n){\n        \n        // isItPossible to distribute <= x products to each of the n shops\n        for(int i=0; i<quantities.length; i++){\n            \n            int products = quantities[i];\n            \n            n -= Math.ceil(products/(x*1.0));\n            \n            if(n<0)     // means it requires more than n shops to distribute all products\n                return false; \n        }\n        \n        return true; // distributed all products to exactly n shops\n    }\n}",
        "solution_c": "class Solution {\npublic:\n  bool func(int N, int n, vector<int>& quantities){\n    int temp = 0;\n    for(int id = 0; temp <= n && id != quantities.size(); id++)\n      temp += quantities[id] / N + (quantities[id] % N ? 1 : 0);\n    \n    return temp <= n;\n  }\n  \n  int minimizedMaximum(int n, vector<int>& quantities) {\n    int l = 1, r = *max_element(quantities.begin(), quantities.end());\n    \n    for(int m = (l + r)>>1; l <= r; m = (l + r)>>1) \n      func(m, n , quantities) ? r = m - 1 : l = m + 1; \n    \n    return l;\n  }\n};"
    },
    {
        "title": "Linked List Random Node",
        "algo_input": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.\n\nImplement the Solution class:\n\n\n\tSolution(ListNode head) Initializes the object with the head of the singly-linked list head.\n\tint getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 3, 2, 2, 3]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the linked list will be in the range [1, 104].\n\t-104 &lt;= Node.val &lt;= 104\n\tAt most 104 calls will be made to getRandom.\n\n\n&nbsp;\nFollow up:\n\n\n\tWhat if the linked list is extremely large and its length is unknown to you?\n\tCould you solve this efficiently without using extra space?\n\n",
        "solution_py": "class Solution:\n\n    def __init__(self, head: Optional[ListNode]):\n        self.lst = []\n        while head:\n            self.lst.append(head.val)\n            head = head.next\n\n    def getRandom(self) -> int:\n        return random.choice(self.lst)",
        "solution_js": "var Solution = function(head) {\n        this.res = [];\n        let curr = head;\n\n        while(curr !== null) {\n            this.res.push(curr)\n            curr = curr.next;\n        }\n        this.length = this.res.length;\n};\n\nSolution.prototype.getRandom = function() {\n    //Math.random() will generate a random number b/w 0 & 1.\n    //then multiply it with the array size, as i have all the value in the list, i know the size of the list\n    //take only the integer part which is a random index.\n    //return the element at that random index.\n    return this.res[Math.floor(Math.random() * this.length)].val\n};",
        "solution_java": "class Solution {\n    int N = 0;\n    ListNode head = null;\n    public Solution(ListNode head) {\n        this.head = head;\n    }\n    \n    public int getRandom() {\n        ListNode p = this.head;\n        int i = 1, ans = 0;\n        while (p != null) {\n            if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i\n            p = p.next;\n            i ++;\n        }\n        return ans;\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int>v;\n    Solution(ListNode* head) {\n        while(head!=NULL) {\n            v.push_back(head->val);\n            head=head->next;\n        }\n\n    }\n\n    int getRandom() {\n        return v[rand()%v.size()];\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution* obj = new Solution(head);\n * int param_1 = obj->getRandom();\n */"
    },
    {
        "title": "Maximum Score Words Formed by Letters",
        "algo_input": "Given a list of words, list of&nbsp; single&nbsp;letters (might be repeating)&nbsp;and score&nbsp;of every character.\n\nReturn the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two&nbsp;or more times).\n\nIt is not necessary to use all characters in letters and each letter can only be used once. Score of letters&nbsp;'a', 'b', 'c', ... ,'z' is given by&nbsp;score[0], score[1], ... , score[25] respectively.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput: 23\nExplanation:\nScore  a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.\n\nExample 2:\n\nInput: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput: 27\nExplanation:\nScore  a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.\n\nExample 3:\n\nInput: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput: 0\nExplanation:\nLetter \"e\" can only be used once.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 14\n\t1 &lt;= words[i].length &lt;= 15\n\t1 &lt;= letters.length &lt;= 100\n\tletters[i].length == 1\n\tscore.length ==&nbsp;26\n\t0 &lt;= score[i] &lt;= 10\n\twords[i], letters[i]&nbsp;contains only lower case English letters.\n\n",
        "solution_py": "from itertools import combinations \n\nclass Solution:\n    def createNewWord(self, wordList) : \n        ans = ''\n        for word in wordList :\n            ans += word \n        \n        charList = [i for i in ans]\n        return charList \n    \n    def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n        score_dict = {}\n        ord_a = 97 \n        for i in range(len(score)) : \n            score_dict[chr(ord_a + i)] = score[i]\n            \n        max_count, sum_list, to_remove = 0, [], []\n        for word in words : \n            char_list = [i for i in word]\n            max_num = 0\n            for char in set(char_list) : \n                if char_list.count(char) > letters.count(char) : \n                    max_num = 0\n                    to_remove.append(word)\n                    break \n                else : \n                    max_num += score_dict[char]*char_list.count(char)\n\n            if max_num > 0 :\n                sum_list.append(max_num)\n        \n            if max_num > max_count : \n                max_count = max_num \n        \n        new_word = [i for i in words if i not in to_remove]\n        # print(new_word)\n        for i in range(2, len(sum_list)+1) :\n            comb = combinations(new_word, i)\n            for c in comb : \n                combinedWord = self.createNewWord(c)\n                totalNum = 0\n                for char in set(combinedWord) : \n                    if combinedWord.count(char) > letters.count(char) : \n                        totalNum = 0\n                        break \n                    else : \n                        totalNum += score_dict[char]*combinedWord.count(char)\n                if totalNum > max_count : \n                    max_count = totalNum \n                    \n        return max_count ",
        "solution_js": "var maxScoreWords = function(words, letters, score) {\n    // unique chars\n    let set = new Set();\n    for (let w of words)\n        for (let c of w)\n            set.add(c)\n\n    // score of unique chars\n    let map = new Map();\n    for (let c of set)\n        map.set(c, score[c.charCodeAt() - 'a'.charCodeAt()])\n\n    // letter count\n    let map_letters = new Map();\n    for (let c of letters)\n        map_letters.set(c, map_letters.has(c) ? map_letters.get(c) + 1 : 1);\n\n    // score of words\n    let SW = [];\n    for (let w of words) {\n        let s = 0;\n        for (let c of w)\n            s += map.get(c)\n        SW.push(s)\n    }\n\n    const sortStr = (s) => s.split(\"\").sort().join(\"\")\n    const combineStrings_fromArrayAndIndexes = (A, I) => I.reduce((s, i) => (s + A[i]), '')\n    const getFreqMapFromStr = (s) => s.split(\"\").reduce((m, c) => (m.set(c, m.has(c) ? m.get(c) + 1 : 1), m), new Map())\n    const isMapSubOfAnotherMap = (m1, m2) => {\n        for (let [c, count] of m1)\n            if (!m2.has(c) || count > m2.get(c))\n                return false\n        return true\n    }\n\n    let max1 = -Infinity;\n    const takeOrNot = (i, take, indexes, A, n) => {\n        if (i === n) {\n            if (isMapSubOfAnotherMap(\n                    getFreqMapFromStr(\n                        combineStrings_fromArrayAndIndexes(words, indexes)\n                    ),\n                    map_letters\n                )) {\n                let mm = indexes.reduce((sum, i) => sum + SW[i], 0)\n                max1 = Math.max(max1, mm);\n            }\n            return\n        }\n        takeOrNot(i + 1, take, indexes, A, n)\n        takeOrNot(i + 1, take, [...indexes, i], A, n);\n    }\n    takeOrNot(0, true, [], SW, SW.length);\n    return max1;\n};",
        "solution_java": "class Solution {\n    int[] memo;\n    public int maxScoreWords(String[] words, char[] letters, int[] score) {\n        memo = new int[words.length];\n        Arrays.fill(memo,-1);\n        HashMap<Character,Integer> hm = new HashMap<>();\n        for(char c : letters){\n            int t = hm.getOrDefault(c,0);\n            t++;\n            hm.put(c,t);\n        }\n        //return dp(words,hm,score,0,0);\n        int res = dp(words,hm,score,0,0);\n        //for(int i : memo) System.out.println(i);\n        return res;\n    }\n\n    public int dp(String[] words, Map<Character,Integer> hm, int[] score, int index, int cs){//cs-current Score\n        if(index==words.length) return cs;\n        if(memo[index]!=-1) return memo[index];\n        HashMap<Character,Integer> temp = new HashMap<>(hm);\n        int tcs=cs; //tcs = temporory current score\n\n        for(char c : words[index].toCharArray()){\n            int t = temp.getOrDefault(c,0);\n            t--;\n            if(t<0){\n                return dp(words,hm,score,index+1,cs);\n                // memo[index] = dp(words,hm,score,index+1,cs);\n                // return memo[index];\n            }\n            tcs+=score[c-'a'];\n            temp.put(c,t);\n        }\n        return Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n        // memo[index] = Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n        // return memo[index];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int calc(vector<string>& words,map<char,int>&m,vector<int>& score,int i){ \n        int maxi=0;\n        if(i==words.size())\n            return 0;\n        map<char,int>m1=m;//Creating a duplicate in case the given word does not satisfy our answer\n        int c=0;//Store the score\n        for(int j=0;j<words[i].length();j++){\n            if(m1.find(words[i][j])==m1.end()||m1[words[i][j]]==0){//If frequency of the letter reduces to zero or that letter is not present in our hashMap            \n                c=-1;\n                break;\n            }\n            c+=score[words[i][j]-'a'];\n            m1[words[i][j]]--;\n        }        \n        if(c!=-1)           \n          maxi=c+(calc(words,m1,score,i+1));//We are considering the current word and adding it to our answer\n        return max(maxi,calc(words,m,score,i+1));//FInding tha maximum between when we consider the current word and when we DONT consider current word\n        \n}\n    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {\n        map<char,int>m;       \n        for(auto i:letters)\n            m[i]++;\n        return calc(words,m,score,0);   \n    }\n};"
    },
    {
        "title": "Can Make Palindrome from Substring",
        "algo_input": "You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.\n\nIf the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.\n\nReturn a boolean array answer where answer[i] is the result of the ith query queries[i].\n\nNote that each letter is counted individually for replacement, so if, for example s[lefti...righti] = \"aaa\", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.\n\n&nbsp;\nExample :\n\nInput: s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput: [true,false,false,true,true]\nExplanation:\nqueries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.\n\n\nExample 2:\n\nInput: s = \"lyb\", queries = [[0,1,0],[2,2,1]]\nOutput: [false,true]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, queries.length &lt;= 105\n\t0 &lt;= lefti &lt;= righti &lt; s.length\n\t0 &lt;= ki &lt;= s.length\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n        hash_map = {s[0]: 1}\n        x = hash_map\n        prefix = [hash_map]\n        for i in range(1, len(s)):\n            x = x.copy()\n            x[s[i]] = x.get(s[i], 0) + 1\n            prefix.append(x)\n            \n        result = []\n        for query in queries:\n            cnt = 0\n            for key, value in prefix[query[1]].items():\n                if query[0] > 0:\n                    x = value - prefix[query[0]-1].get(key, 0)\n                else:\n                    x = value\n                if x % 2:\n                    cnt+=1\n            if cnt - 2 * query[2] > 1:\n                result.append(False)\n            else:\n                result.append(True)\n        return result",
        "solution_js": "const getBitCount = (n) => {\n    let cnt = 0;\n    while(n > 0) {\n        cnt += n & 1;\n        n >>= 1;\n    }\n    return cnt;\n}\n\nvar canMakePaliQueries = function(s, queries) {\n    const masks = [0], base = 'a'.charCodeAt(0);\n    let mask = 0;\n    for(let c of s) {\n        mask ^= (1 << (c.charCodeAt(0) - base));\n        masks.push(mask);\n    }\n    return queries.map(([l, r, k]) => {\n        const cnt = getBitCount(masks[l] ^ masks[r+1]);\n        return cnt - 1 <= 2 * k\n    });\n};",
        "solution_java": "class Solution \n{\n    public List<Boolean> canMakePaliQueries(String s, int[][] queries) \n    {\n        List<Boolean> list = new ArrayList<>();\n        \n        int n = s.length();\n        int[][] map = new int[n+1][26];\n        \n        for(int i=0;i<s.length();i++)\n        {\n            for(int j=0;j<26;j++)\n                map[i+1][j] = map[i][j];\n            \n            map[i+1][s.charAt(i) - 'a']++;\n        }\n        \n        for(int[] q : queries)\n        {\n            int l = q[0];\n            int r = q[1];\n            int k = q[2];\n            int count = 0;\n            \n            for(int i=0;i<26;i++)\n                count += (map[r+1][i] - map[l][i]) % 2;\n            \n            list.add(count/2 <= k);\n        }\n        \n        return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n  vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {\n    vector<vector<int>>table(s.size(), vector<int>(26,0));\n    vector<bool>ans;\n\n    table[0][s[0]-'a']++;\n    for(int i = 1; i != s.size(); i++){\n      for(int j = 0; j != 26; j++) table[i][j] = table[i-1][j];\n      table[i][s[i]-'a']++;\n    }\n\n    for(auto &q: queries){\n      int odd = 2 + (q[2]<<1);\n      for(int i = 0; i != 26; i++){\n        int val = table[q[1]][i] - (q[0] ? table[q[0]-1][i] : 0);\n        if( (val & 1) && --odd == 0){ans.push_back(false); goto mark;}\n      }\n\n      ans.push_back(true);\n      mark:;\n    }\n\n    return ans;\n  }\n};"
    },
    {
        "title": "Longest Chunked Palindrome Decomposition",
        "algo_input": "You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:\n\n\n\tsubtexti is a non-empty string.\n\tThe concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).\n\tsubtexti == subtextk - i + 1 for all valid values of i (i.e., 1 &lt;= i &lt;= k).\n\n\nReturn the largest possible value of k.\n\n&nbsp;\nExample 1:\n\nInput: text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput: 7\nExplanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n\n\nExample 2:\n\nInput: text = \"merchant\"\nOutput: 1\nExplanation: We can split the string on \"(merchant)\".\n\n\nExample 3:\n\nInput: text = \"antaprezatepzapreanta\"\nOutput: 11\nExplanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 1000\n\ttext consists only of lowercase English characters.\n\n",
        "solution_py": "class Solution:\n    def longestDecomposition(self, text: str) -> int:\n        left, right = 0, len(text) - 1\n        sol, last_left = 0, 0\n        a, b = deque(), deque()\n        while right > left:\n            a.append(text[left])\n            b.appendleft(text[right])\n            if a == b:\n                sol += 2\n                last_left = left\n                a, b = deque(), deque()\n            right -= 1\n            left += 1\n        if left == right or left > last_left + 1:\n            sol += 1\n        return max(sol, 1)",
        "solution_js": "var longestDecomposition = function(text) {\n    var i = 1\n    var output = 0\n    while(i < text.length)\n    {\n        if(text.substring(0,i) == text.substring(text.length-i))\n        {\n            output += 2 //add 2 to simulate adding to both sides of output array\n            text = text.substring(i,text.length-i) //cut text to simulate popping off of both sides\n            i=1\n        } else {\n            i++\n        }\n    }\n    \n    return text ? output + 1 : output //if there's any text leftover that didn't have a match, it's the middle and would add 1 to output array\n}",
        "solution_java": "class Solution {\n\n public int longestDecomposition(String text) {\n    int n = text.length();   \n    for (int i = 0; i < n/2; i++) \n        if (text.substring(0, i + 1).equals(text.substring(n-1-i, n))) \n            return 2+longestDecomposition(text.substring(i+1, n-1-i));\n    return (n==0)?0:1;\n}\n}",
        "solution_c": "class Solution {\npublic:\n    int longestDecomposition(string text) {\n        if(text.size() == 0)\n            return 0;\n        int i = 0;\n        deque<char> sFront;\n        deque<char> sBack;\n        while(i < text.size() / 2){\n            sFront.push_back(text[i]);\n            sBack.push_front(text[text.size() - 1 - i]);\n            if(sFront == sBack)\n                return 2 + longestDecomposition(text.substr(i + 1, text.size() - 2*(i+1)));\n            i++;\n        }\n        return 1;\n    }\n};"
    },
    {
        "title": "Sum Root to Leaf Numbers",
        "algo_input": "You are given the root of a binary tree containing digits from 0 to 9 only.\n\nEach root-to-leaf path in the tree represents a number.\n\n\n\tFor example, the root-to-leaf path 1 -&gt; 2 -&gt; 3 represents the number 123.\n\n\nReturn the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.\n\nA leaf node is a node with no children.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3]\nOutput: 25\nExplanation:\nThe root-to-leaf path 1-&gt;2 represents the number 12.\nThe root-to-leaf path 1-&gt;3 represents the number 13.\nTherefore, sum = 12 + 13 = 25.\n\n\nExample 2:\n\nInput: root = [4,9,0,5,1]\nOutput: 1026\nExplanation:\nThe root-to-leaf path 4-&gt;9-&gt;5 represents the number 495.\nThe root-to-leaf path 4-&gt;9-&gt;1 represents the number 491.\nThe root-to-leaf path 4-&gt;0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026.\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;= 9\n\tThe depth of the tree will not exceed 10.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def sumNumbers(self, root: Optional[TreeNode]) -> int:\n        \n        int_list = []\n        \n        def traverse(node, input_string):\n            \n            nonlocal int_list\n            \n            if not node:\n                return int_list\n            \n            input_string = input_string + str(node.val)\n\n            if not (node.left or node.right):\n                int_list.append(int(input_string))\n            \n            traverse(node.left, input_string)\n            traverse(node.right, input_string)\n                \n        traverse(root, \"\")\n        return sum(int_list)\n                ",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nvar sumNumbers = function(root) {\n    return dfs(root)\n};\n\nconst dfs = (root, path = '') => {\n    if (!root.left && !root.right) return +(path + root.val)\n    \n    const left = root.left ? dfs(root.left, path + root.val) : 0\n    const right = root.right ? dfs(root.right, path + root.val) : 0\n    \n    return left + right\n}",
        "solution_java": "class Solution {\n    int res;\n    public int sumNumbers(TreeNode root) {\n        res = 0;\n        getSum(root, 0);\n        \n        return res;\n    }\n    \n    public void getSum(TreeNode root, int sum){\n        \n        if(root.left == null && root.right == null) {\n            res += (sum*10+root.val);\n        }\n        \n        if(root.left != null)\n            getSum(root.left, sum*10+root.val);\n        \n        \n        if(root.right != null)\n            getSum(root.right, sum*10+root.val);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int ans=0;\n    void dfs(TreeNode* root, string s){\n        if(!root->left && !root->right){\n            s+=to_string(root->val);\n            ans+=stoi(s);\n            return;\n        }\n        string o = s;\n        s+=to_string(root->val);\n        if(root->left) dfs(root->left,s);\n        if(root->right) dfs(root->right,s);\n        s=o;\n\n    }\n    int sumNumbers(TreeNode* root) {\n        if(!root) return ans;\n        string s = \"\";\n        dfs(root,s);\n        return ans;\n    }\n};"
    },
    {
        "title": "Contains Duplicate III",
        "algo_input": "Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) &lt;= t and abs(i - j) &lt;= k.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,3,1], k = 3, t = 0\nOutput: true\nExample 2:\nInput: nums = [1,0,1,1], k = 1, t = 2\nOutput: true\nExample 3:\nInput: nums = [1,5,9,1,5,9], k = 2, t = 3\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\t0 &lt;= k &lt;= 104\n\t0 &lt;= t &lt;= 231 - 1\n\n",
        "solution_py": "from sortedcontainers import SortedList\nclass Solution:\n    def containsNearbyAlmostDuplicate(self, nums, k, t):\n        sl = SortedList()\n        for i in range(len(nums)):\n            if i > k: sl.remove(nums[i-k-1])\n            idxl = sl.bisect_left(nums[i]-t)\n            idxr = sl.bisect_right(nums[i]+t)\n            if idxl != idxr: return True\n            sl.add(nums[i])\n        return False",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} t\n * @return {boolean}\n */\nvar containsNearbyAlmostDuplicate = function(nums, k, t) {\n   for(let i=0;i<nums.length;i++){\n        for(let j=i+1;j<nums.length;j++){\n            if(Math.abs(nums[i]-nums[j])<=t && (Math.abs(i-j)<=k)){\n                return true;\n            }\n        }\n   }\n    return false;\n};",
        "solution_java": "/**\n * Sliding Window solution using Buckets\n *\n * Time Complexity: O(N)\n *\n * Space Complexity: O(min(N, K+1))\n *\n * N = Length of input array. K = Input difference between indexes.\n */\nclass Solution {\n    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {\n        if (nums == null || nums.length < 2 || k < 1 || t < 0) {\n            return false;\n        }\n\n        HashMap<Long, Long> buckets = new HashMap<>();\n        // The bucket size is t+1 as the ranges are from 0..t, t+1..2t+1, ..\n        long bucketSize = (long) t + 1;\n\n        for (int i = 0; i < nums.length; i++) {\n            // Making sure only K buckets exists in map.\n            if (i > k) {\n                long lastBucket = ((long) nums[i - k - 1] - Integer.MIN_VALUE) / bucketSize;\n                buckets.remove(lastBucket);\n            }\n\n            long remappedNum = (long) nums[i] - Integer.MIN_VALUE;\n            long bucket = remappedNum / bucketSize;\n\n            // If 2 numbers belong to same bucket\n            if (buckets.containsKey(bucket)) {\n                return true;\n            }\n\n            // If numbers are in adjacent buckets and the difference between them is at most\n            // t.\n            if (buckets.containsKey(bucket - 1) && remappedNum - buckets.get(bucket - 1) <= t) {\n                return true;\n            }\n            if (buckets.containsKey(bucket + 1) && buckets.get(bucket + 1) - remappedNum <= t) {\n                return true;\n            }\n\n            buckets.put(bucket, remappedNum);\n        }\n\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {\n        int i=0;\n        map<int,int> mp;\n        int n=nums.size();\n        for(int j=0;j<n;j++){\n            auto val=mp.lower_bound(nums[j]);\n            if(val!=mp.end() and (val->first-nums[j])<=valueDiff){\n                return true;\n            }\n            if(val!=mp.begin()){\n                val--;\n                if(abs(val->first-nums[j])<=valueDiff){\n                    return true;\n                }\n            }\n            mp[nums[j]]++;\n            if((j-i)==indexDiff){\n                mp[nums[i]]--;\n                if(mp[nums[i]]==0){\n                    mp.erase(nums[i]);\n                }\n                i++;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Count Equal and Divisible Pairs in an Array",
        "algo_input": "Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 &lt;= i &lt; j &lt; n, such that nums[i] == nums[j] and (i * j) is divisible by k.\n&nbsp;\nExample 1:\n\nInput: nums = [3,1,2,2,2,1,3], k = 2\nOutput: 4\nExplanation:\nThere are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4], k = 1\nOutput: 0\nExplanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i], k &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def countPairs(self, nums: List[int], k: int) -> int:\n        n=len(nums)\n        c=0\n        for i in range(0,n):\n            for j in range(i+1,n):\n                if nums[i]==nums[j] and ((i*j)%k==0):\n                    c+=1\n        return c",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar countPairs = function(nums, k) {\n    var count = 0;\n    for(let i=0; i<nums.length; i++){\n        for(let j=i+1; j<nums.length; j++){\n            if(nums[i] == nums[j] && (i * j) % k == 0){\n                count++;\n            }\n        }\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int countPairs(int[] nums, int k) {\n      HashMap<Integer,List<Integer>> hMap = new HashMap<>();\n        int count = 0;\n        for(int i = 0 ; i < nums.length ; i++){\n            if(!hMap.containsKey(nums[i])){\n                List<Integer> l = new ArrayList<>();\n                l.add(i);\n                hMap.put(nums[i],l);\n            }else{\n                List<Integer> v = hMap.get(nums[i]);\n                for(Integer j : v){\n                    if((i*j)%k == 0) count++;\n                }\n                v.add(i);\n                hMap.put(nums[i],v);\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPairs(vector<int>& nums, int k) {\n        int count=0;\n        for(int i=0;i<nums.size()-1;i++)\n        {\n            for(int j=i+1;j<nums.size();j++)\n                if(nums[i]==nums[j] && i*j%k==0)\n                {\n                    count++;\n                }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Triangle",
        "algo_input": "Given a triangle array, return the minimum path sum from top to bottom.\n\nFor each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.\n\n&nbsp;\nExample 1:\n\nInput: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput: 11\nExplanation: The triangle looks like:\n   2\n  3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n\n\nExample 2:\n\nInput: triangle = [[-10]]\nOutput: -10\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= triangle.length &lt;= 200\n\ttriangle[0].length == 1\n\ttriangle[i].length == triangle[i - 1].length + 1\n\t-104 &lt;= triangle[i][j] &lt;= 104\n\n\n&nbsp;\nFollow up: Could you&nbsp;do this using only O(n) extra space, where n is the total number of rows in the triangle?",
        "solution_py": "class Solution:\n    def minimumTotal(self, t: List[List[int]]) -> int:\n        dp = []\n        dp.append(t[0])\n        \n        r = len(t)\n        answer = float('inf')\n        for i in range(1, r):\n            c = len(t[i])\n            dp.append([])\n            for j in range(0, c):\n                if j == 0:\n                    val = dp[i - 1][j] + t[i][j]\n                elif j == c - 1:\n                    val = dp[i - 1][j - 1] + t[i][j]\n                else:\n                    val = min(dp[i - 1][j], dp[i - 1][j - 1]) + t[i][j]\n                if i == r - 1:\n                    answer = min(answer, val)\n                dp[i].append(val)\n        return answer if r > 1 else t[0][0]",
        "solution_js": "var minimumTotal = function(triangle) {\n    const memo = {};\n    \n    function minPath(row, col) {\n        let key = `${row}:${col}`;\n        \n        if (key in memo) {\n            return memo[key];\n        }\n        \n        let path = triangle[row][col];\n        \n        if (row < triangle.length - 1) {\n            path += Math.min(minPath(row + 1, col), minPath(row + 1, col + 1));\n        }\n        \n        memo[key] = path;\n        \n        return path;\n    }\n    \n    return minPath(0, 0);\n};",
        "solution_java": "class Solution {\n    public int minimumTotal(List<List<Integer>> triangle) {\n\n        int n = triangle.get( triangle.size() - 1).size();\n        int dp[] = new int[n + 1];\n\n        for(int i = triangle.size() - 1; i>=0; i--)\n        {\n            for(int j = 0; j<triangle.get(i).size(); j++)\n                dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j+1]);\n        }\n\n        return dp[0];\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    \n    int travel(vector<vector<int>>& tr , int lvl , int ind) {\n        \n        if(ind >= tr[lvl].size()) // To check if we are going out of bound \n            return INT_MAX;\n        \n        if(lvl == tr.size() - 1) { // Return if we are on last line\n            return tr[lvl][ind];\n        }\n        \n        int s = travel(tr , lvl + 1, ind ); // Go South\n        int se = travel(tr , lvl + 1 , ind + 1); // Go South East \n        \n\t\t// Return the minimum of south and south east + cost of the index we are currently at.\n\t\t\n        return min(s , se) + tr[lvl][ind]; \n        \n    }\n    \n    \n    int minimumTotal(vector<vector<int>>& triangle) {\n        return travel(triangle , 0 , 0);\n    }\n};"
    },
    {
        "title": "Binary Search Tree to Greater Sum Tree",
        "algo_input": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\n\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\nExample 2:\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t0 &lt;= Node.val &lt;= 100\n\tAll the values in the tree are unique.\n\n\n&nbsp;\nNote: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/\n",
        "solution_py": "class Solution:\n    def bstToGst(self, root):\n        self.total = 0\n        def dfs(n):\n            if n:\n                dfs(n.right)\n                self.total +=  n.val\n                n.val       =  self.total\n                dfs(n.left)\n        dfs(root)\n        return root",
        "solution_js": "var bstToGst = function(root) {\n    let sum = 0;\n    const traverse = (r = root) => {\n        if(!r) return null;\n        traverse(r.right);\n        let temp = r.val;\n        r.val += sum;\n        sum += temp;\n        traverse(r.left);\n    }\n    traverse();\n    return root;\n};",
        "solution_java": "class Solution {\n    int sum=0;\n    public TreeNode bstToGst(TreeNode root) {\n        if(root!=null){\n            bstToGst(root.right);\n            sum += root.val;\n            root.val = sum;\n            bstToGst(root.left);\n        }\n        return root;\n    }\n\n    \n   \n}",
        "solution_c": "class Solution {\npublic:\n\n    int s = 0;\n\n    void solve(TreeNode* root){\n        if(!root) return;\n        solve(root->right);\n\n        root->val = s + root->val;\n        s = root->val;\n\n        solve(root->left);\n        return;\n    }\n\n    TreeNode* bstToGst(TreeNode* root) {\n        if(!root) return NULL;\n        solve(root);\n        return root;\n    }\n};"
    },
    {
        "title": "Complete Binary Tree Inserter",
        "algo_input": "A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.\n\nDesign an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.\n\nImplement the CBTInserter class:\n\n\n\tCBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.\n\tint insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode.\n\tTreeNode get_root() Returns the root node of the tree.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n[[[1, 2]], [3], [4], []]\nOutput\n[null, 1, 2, [1, 2, 3, 4]]\n\nExplanation\nCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3);  // return 1\ncBTInserter.insert(4);  // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 1000].\n\t0 &lt;= Node.val &lt;= 5000\n\troot is a complete binary tree.\n\t0 &lt;= val &lt;= 5000\n\tAt most 104 calls will be made to insert and get_root.\n\n",
        "solution_py": "class CBTInserter:\n\n    def __init__(self, root: Optional[TreeNode]):\n        self.root = root\n        self.queue = Queue()\n        self.queue.put(self.root)\n        self.parent_of_last_inserted = None\n        \n    def insert(self, val: int) -> int:\n        if self.parent_of_last_inserted is not None and self.parent_of_last_inserted.right is None:\n            self.parent_of_last_inserted.right = TreeNode(val)\n            self.queue.put(self.parent_of_last_inserted.right)\n            return self.parent_of_last_inserted.val\n        \n        while not self.queue.empty():\n            node = self.queue.get()\n            if node.left is None:\n                node.left = TreeNode(val)\n                self.queue.put(node.left)\n                self.parent_of_last_inserted = node\n                return node.val\n            else:\n                self.queue.put(node.left)\n            if node.right is None:\n                node.right = TreeNode(val)\n                self.queue.put(node.right)\n                self.parent_of_last_inserted = node\n                return node.val\n            else:\n                self.queue.put(node.right)\n        \n\n    def get_root(self) -> Optional[TreeNode]:\n        return self.root",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n */\nvar CBTInserter = function(root) {\n    this.root = root;\n};\n\n/** \n * @param {number} val\n * @return {number}\n */\nCBTInserter.prototype.insert = function(val) {\n    let cur = this.root;\n    let queue = [cur];\n    while(queue.length){\n        let updatedQueue = [];\n        while(queue.length){\n            let node = queue.shift();\n            if(!node.left) {\n                node.left = new TreeNode(val);\n                return node.val;\n            }\n            else updatedQueue.push(node.left);\n            if(!node.right) {\n                node.right = new TreeNode(val);\n                return node.val;\n            }\n            else updatedQueue.push(node.right);\n        }\n        queue = updatedQueue ;\n    }\n    \n};\n\n/**\n * @return {TreeNode}\n */\nCBTInserter.prototype.get_root = function() {\n    return this.root;\n};\n\n/** \n * Your CBTInserter object will be instantiated and called as such:\n * var obj = new CBTInserter(root)\n * var param_1 = obj.insert(val)\n * var param_2 = obj.get_root()\n */",
        "solution_java": "class CBTInserter {\n\n    private TreeNode root;\n    private int total;\n\n    private int count(TreeNode root) {\n        if (root == null) return 0;\n        return 1+count(root.left)+count(root.right);\n    }\n\n    public CBTInserter(TreeNode root) {\n        this.root = root;\n        total = count(root);\n    }\n\n    private int insertBinary(int val, int k, int right) {\n        int left = 0;\n        var ptr = root;\n        while (left < right) {\n            if (left == right -1) {\n                if (ptr.left == null) ptr.left = new TreeNode(val);\n                else ptr.right = new TreeNode(val);\n                return ptr.val;\n            }\n            int mid = (right-left) / 2 + left;\n            if (mid >= k ) {\n                ptr = ptr.left;\n                right = mid;\n            } else if (mid < k) {\n                left = mid+1;\n                ptr = ptr.right;\n            }\n        }\n        return 0;\n    }\n\n    public int insert(int val) {\n        int depth = 0;\n        int n = total;\n        while(n > 0) {\n            depth++;\n            n /= 2;\n        }\n        if ((1<<depth)-1 == total) depth++;\n        // k is the new index in the lowest level of tree, right is the max index of the lowest level of tree\n        // e.g. for tree\n        // 1\n        // / \\\n        // 2 new\n//index 0 1\n        // it's insertBinary(val, 1, 1)\n        var res = insertBinary(val, total - (1<<(depth-1))+1 , (1<<(depth-1)) -1);\n        total++;\n        return res;\n    }\n\n    public TreeNode get_root() {\n        return root;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass CBTInserter {\npublic:\n    vector<TreeNode*> arr;\n\n    CBTInserter(TreeNode* root) {\n\n        arr.push_back(root);\n        queue<TreeNode*> q;\n        q.push(root);\n        while(!q.empty()){\n\n            if(q.front() -> left != NULL){\n                arr.push_back(q.front() -> left);\n                q.push(q.front() -> left);\n            }\n            if(q.front() -> right != NULL){\n                arr.push_back(q.front() -> right);\n                q.push(q.front() -> right);\n            }\n            q.pop();\n\n        }\n    }\n\n    int insert(int val) {\n\n        TreeNode* new_node = new TreeNode(val);\n        arr.push_back(new_node);\n        int parent_index = (arr.size()-2)/2;\n        if(2*parent_index +1 == arr.size()-1){arr[parent_index] -> left = new_node;}\n        else{arr[parent_index] -> right = new_node;}\n        return arr[parent_index] -> val;\n    }\n\n    TreeNode* get_root() {\n        return arr[0];\n    }\n};\n\n/**\n * Your CBTInserter object will be instantiated and called as such:\n * CBTInserter* obj = new CBTInserter(root);\n * int param_1 = obj->insert(val);\n * TreeNode* param_2 = obj->get_root();\n */"
    },
    {
        "title": "Number of Lines To Write String",
        "algo_input": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.\n\nYou are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.\n\nReturn an array result of length 2 where:\n\n\n\tresult[0] is the total number of lines.\n\tresult[1] is the width of the last line in pixels.\n\n\n&nbsp;\nExample 1:\n\nInput: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: [3,60]\nExplanation: You can write s as follows:\nabcdefghij  // 100 pixels wide\nklmnopqrst  // 100 pixels wide\nuvwxyz      // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.\n\nExample 2:\n\nInput: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput: [2,4]\nExplanation: You can write s as follows:\nbbbcccdddaa  // 98 pixels wide\na            // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.\n\n&nbsp;\nConstraints:\n\n\n\twidths.length == 26\n\t2 &lt;= widths[i] &lt;= 10\n\t1 &lt;= s.length &lt;= 1000\n\ts contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numberOfLines(self, w: List[int], s: str) -> List[int]:\n        r=[0]*2\n        px=0\n        l=1\n        for i in range(len(s)):\n            px+=w[ord(s[i])-97]\n            if px>100:\n                l+=1\n                px=w[ord(s[i])-97]\n                \n            print(ord(s[i]))\n        r[0]=l\n        r[1]=px\n        return r\n        ",
        "solution_js": "var numberOfLines = function(widths, s) {\n    let pixel=100, line=1;\n    for(let i=0; i<s.length; i++){\n        if(pixel>=widths[s[i].charCodeAt()-97]){\n            pixel-=widths[s[i].charCodeAt()-97];\n        }else{\n            // this word should be written in NEXT line, so it CANNOT count.\n            i--; line++; pixel=100;\n        }\n    }\n    // 100-pixel = space used in this line.\n    return [line, 100-pixel];\n};",
        "solution_java": "class Solution {\n    public int[] numberOfLines(int[] widths, String s) {\n            int sum=0,count=0;\n            for(int j=0;j<s.length();j++)\n            {\n                int pos = s.charAt(j)-'a';\n                sum+=widths[pos];\n                if(sum>100)\n                {\n                    j--;\n                    count++;\n                    sum=0;\n                    continue;\n                }\n            }\n        int[] arr = new int[2];\n        arr[0]=count+1;\n        arr[1]=sum;\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> numberOfLines(vector<int>& widths, string s) {\n        vector<int>ans(2);\n        int lines =0;\n        int calc = 0;\n        int i =0;\n        while(i<s.length()){\n            calc = 0;\n            while(i<s.length() and calc<=100){\n                calc+=widths[s[i]-'a'];\n                i++;\n            }\n            if(calc>100){\n                i-=1;\n                calc-=widths[s[i]-'a'];\n            }\n            lines++;\n            // cout<<lines;\n        }\n        ans[0] = lines;\n        ans[1] = calc;\n        return ans;\n    }\n};"
    },
    {
        "title": "Custom Sort String",
        "algo_input": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.\n\nPermute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.\n\nReturn any permutation of s that satisfies this property.\n\n&nbsp;\nExample 1:\n\nInput: order = \"cba\", s = \"abcd\"\nOutput: \"cbad\"\nExplanation: \n\"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.\n\n\nExample 2:\n\nInput: order = \"cbafg\", s = \"abcd\"\nOutput: \"cbad\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= order.length &lt;= 26\n\t1 &lt;= s.length &lt;= 200\n\torder and s consist of lowercase English letters.\n\tAll the characters of order are unique.\n\n",
        "solution_py": "class Solution:\n    def customSortString(self, order: str, s: str) -> str:\n        charValue = [0] * 26\n        for i in range(len(order)):\n            idx = ord(order[i]) - ord('a')\n            charValue[idx] = 26 - i\n\n        arrS = []\n        n = 0\n        for c in s:\n            arrS.append(c)\n            n += 1\n\n        sorted = False\n        while not sorted:\n            sorted = True\n            for i in range(n - 1):\n                if charValue[ord(arrS[i]) - ord('a')] < charValue[ord(arrS[i + 1]) - ord('a')]:\n                    sorted = False\n                    arrS[i], arrS[i + 1] = arrS[i + 1], arrS[i]\n\n        return ''.join(arrS)",
        "solution_js": "var customSortString = function(order, s) {\n    const hm = new Map();\n    for(let c of s) {\n        if(!hm.has(c)) hm.set(c, 0);\n        hm.set(c, hm.get(c) + 1);\n    }\n    \n    let op = \"\";\n    for(let c of order) {\n        if(hm.has(c)) {\n            op += \"\".padStart(hm.get(c), c);\n            hm.delete(c);\n        }\n    }\n    for(let [c, occ] of hm) {\n        op += \"\".padStart(hm.get(c), c);\n        hm.delete(c);\n    }\n    return op;\n};",
        "solution_java": "class Solution {\n    public String customSortString(String order, String s) {\n      if(s.length() <= 1) return s;\n      \n      StringBuilder finalString = new StringBuilder();\n      HashMap<Character, Integer> hm = new HashMap<>();\n      \n      for(int i = 0; i < s.length(); i++) {\n        char actualChar = s.charAt(i);\n        \n        if(order.indexOf(actualChar) == -1) {\n          finalString.append(actualChar);\n        } else {\n          hm.put(actualChar, hm.getOrDefault(actualChar, 0) + 1);\n        }\n      }\n      \n      for(int i = 0; i < order.length(); i++) {\n        char actualChar = order.charAt(i);\n        \n        if (hm.get(actualChar) != null){\n          for(int j = 0; j < hm.get(actualChar); j++) {\n            finalString.append(actualChar);\n          }\n        }\n      }\n      \n      return finalString.toString(); \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string customSortString(string order, string s) {\n\n        map<char,int>mp;\n\n        for(int i =0 ; i<order.size() ; i++)\n            mp[order[i]]=i+1;\n\n        vector<pair<int,char> > p;\n        int x=200;\n        for(int i =0 ; i < s.size(); i++)\n        {\n            if(mp[s[i]]!=0)\n            p.push_back(make_pair(mp[s[i]],s[i]));\n            else\n            p.push_back(make_pair(x--,s[i]));\n\n        }\n\n        sort(p.begin(),p.end());\n        string ans=\"\";\n        for(int i =0 ;i < p.size(); i++)\n        {\n            ans+=p[i].second;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Atoms",
        "algo_input": "Given a string formula representing a chemical formula, return the count of each atom.\n\nThe atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\n\nOne or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.\n\n\n\tFor example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible.\n\n\nTwo formulas are concatenated together to produce another formula.\n\n\n\tFor example, \"H2O2He3Mg4\" is also a formula.\n\n\nA formula placed in parentheses, and a count (optionally added) is also a formula.\n\n\n\tFor example, \"(H2O2)\" and \"(H2O2)3\" are formulas.\n\n\nReturn the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\n\nThe test cases are generated so that all the values in the output fit in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: formula = \"H2O\"\nOutput: \"H2O\"\nExplanation: The count of elements are {'H': 2, 'O': 1}.\n\n\nExample 2:\n\nInput: formula = \"Mg(OH)2\"\nOutput: \"H2MgO2\"\nExplanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n\n\nExample 3:\n\nInput: formula = \"K4(ON(SO3)2)2\"\nOutput: \"K4N2O14S4\"\nExplanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= formula.length &lt;= 1000\n\tformula consists of English letters, digits, '(', and ')'.\n\tformula is always valid.\n\n",
        "solution_py": "from collections import Counter, deque\n\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        \"\"\"\n        parser:\n            formula: elem {count} formula\n            elem: term | ( formula )\n            term: [A-Z](a-z)+\n            count: [0-9]+\n        \"\"\"\n        \n        \n        def parse_formula(dq, allCount=Counter()):\n            lhs = parse_elem(dq)\n            count = 1\n            while dq and dq[0].isdigit():\n                count = parse_count(dq)\n            for k in lhs.keys():\n                allCount[k] += lhs[k] * count\n\n            if dq and dq[0] not in ')':\n                return parse_formula(dq, allCount)\n            else:\n                return allCount\n\n        def parse_elem(dq):\n            if dq and dq[0] == '(':\n                dq.popleft()\n                res = parse_formula(dq, Counter())\n                dq.popleft()\n                return res\n            else:\n                elem = ''\n                if dq and dq[0].isupper():\n                    elem += dq.popleft()\n                    while dq and dq[0].islower():\n                        elem += dq.popleft()\n                return {elem: 1}\n\n        def parse_count(dq):\n            c = 0\n            while dq and dq[0].isdigit():\n                c = c * 10 + int(dq.popleft())\n            return c\n\n        formula = deque(formula)\n        count_result = parse_formula(formula)\n        result = ''\n        for k in sorted(count_result.keys()):\n            v = count_result[k]\n            if v == 1:\n                result += k\n            else:\n                result += f\"{k}{count_result[k]}\"\n        return result",
        "solution_js": "var countOfAtoms = function(formula) {\n    function getElementCount(flatFormula) {\n        const reElementCount = /([A-Z][a-z]*)(\\d*)/g;\n        let matches = flatFormula.matchAll(reElementCount);\n        \n        let output = new Map();\n        \n        for (let [match, element, count] of matches) {\n            count = count === '' ? 1 : +count;\n            \n            if (output.has(element)) {\n                output.set(element, output.get(element) + count);\n            } else {\n                output.set(element, count);\n            }\n        }\n        \n        return output;\n    }\n    \n    function flattenElementCount(elCountMap) {\n        let arr = [...elCountMap.entries()].sort();\n        \n        return arr.reduce( (str, item) => {\n            let num = item[1] === 1 ? '' : item[1];\n            return str + item[0] + num;\n        }, '' );\n    }\n    \n    function unnest(fullMatch, innerFormula, multiplier) {\n        let elementCount = getElementCount(innerFormula);\n        multiplier = multiplier === '' ? 1 : +multiplier;\n        \n        for (let [element, count] of elementCount) {\n            elementCount.set(element, elementCount.get(element) * multiplier);\n        }\n        \n        return flattenElementCount(elementCount);\n    }\n    \n    function flattenFormula(formula) {\n        const reNested = /\\((\\w+)\\)(\\d*)/g;\n        \n        while (reNested.test(formula)) {\n            formula = formula.replaceAll(reNested, unnest);\n        }\n        \n        return formula;\n    }\n    \n    let flatFormula = flattenFormula(formula);    \n    \n    return flattenElementCount(getElementCount(flatFormula));\n};",
        "solution_java": "class Solution {\n    public String countOfAtoms(String formula) {\n        Deque<Integer> multiplier = new ArrayDeque<>();\n        Map<String, Integer> map = new HashMap<>();\n        int lastValue = 1;\n        \n        multiplier.push(1);\n        \n\t\t// Iterate from right to left\n        for (int i = formula.length() - 1; i >= 0; i--) {\n            if (Character.isDigit(formula.charAt(i))) { // Case of a digit - Get full number and save\n                StringBuilder sb = new StringBuilder();\n\t\t\t\t\n                while (Character.isDigit(formula.charAt(i-1))) {\n                    sb.append(formula.charAt(i));\n                    i--;\n                }\n                sb.append(formula.charAt(i));\n                lastValue = Integer.parseInt(sb.reverse().toString());\n            } else if (formula.charAt(i) == ')') { // Start parenthesis - push next multiplier to stack\n                multiplier.push(lastValue * multiplier.peek());\n                lastValue = 1;\n            } else if (formula.charAt(i) == '(') { // End parenthesis - pop last multiplier\n                multiplier.pop();\n            } else { // Case of an element name - construct name, update count based on multiplier\n                StringBuilder sb = new StringBuilder();\n                \n                while (Character.isLowerCase(formula.charAt(i))) {\n                    sb.append(formula.charAt(i));\n                    i--;\n                }\n                sb.append(formula.charAt(i));\n                \n                String element = sb.reverse().toString();\n                map.put(element, map.getOrDefault(element, 0) + lastValue * multiplier.peek());\n                lastValue = 1;\n            }\n        }\n        \n\t\t// Sort map keys\n        List<String> elements = new ArrayList<>(map.keySet());\n        StringBuilder sb = new StringBuilder();\n        Collections.sort(elements);\n        \n\t\t// Construct output\n        for (String element : elements) {\n            sb.append(element);\n            if (map.get(element) > 1) {\n                sb.append(map.get(element));       \n            }\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    // helper functions\n    bool isUpper(char ch) {\n        return ch >= 65 && ch <= 90;\n    }\n\n    bool isLower(char ch) {\n        return ch >= 97 && ch <= 122;\n    }\n\n    bool isLetter(char ch) {\n        return isUpper(ch) || isLower(ch);\n    }\n\n    bool isNumber(char ch) {\n        return ch >= 48 && ch <= 57;\n    }\n\n    void addKey(map<string, long int>& count, string key, long int value) {\n        if(count.find(key) != count.end()) {\n            count[key] = count[key] + value;\n        }\n        else {\n            count[key] = value;\n        }\n    }\n\n    // very specific utility function\n    string buildName(string formula, int& i) {\n        string name = \"\";\n        name.push_back(formula[i]);\n        if(isUpper(formula[i])) {\n            return name;\n        }\n        if(i == formula.length()-1) {\n            return name;\n        }\n        while(isLower(formula[i-1])) {\n            name.push_back(formula[i-1]);\n            i--;\n        }\n        name.push_back(formula[i-1]);\n        i--;\n        reverse(name.begin(), name.end());\n        return name;\n     }\n\n    // very specific utility function\n    long int buildCount(string formula, int& i, vector<long int>& stack) {\n        long int num = formula[i] - '0';\n        long int place = 1;\n        if(i == 0) {\n            return num;\n        }\n        while(isNumber(formula[i-1])) {\n            place = place * 10;\n            num = (formula[i-1]-'0') * place + num;\n            i--;\n        }\n        return num;\n    }\n\n    string countOfAtoms(string formula) {\n        string ans;\n        map<string, long int> count;\n        vector<long int> stack;\n        long int factor = 1;\n        string name = \"\";\n        long int num = -1; // -1 indicates a number reset, ie, count = 1\n\n        // iterator i is passed by reference to keep track of\n        // the substrings that are builded, ie, atom\n        // names or numbers\n        int i = formula.length()-1;\n        while (i >= 0) {\n            // here we need the number after the bracket close. This is\n            // either 1 or num depending on whether we built a number before\n            if(formula[i] == ')') {\n                if(i+1 <= formula.length()-1 && isNumber(formula[i+1])) {\n                    stack.push_back(num);\n                    factor = factor * num;\n                    num = -1;\n                }\n                else {\n                    stack.push_back(1);\n                }\n            }\n            // here is why we need a stack. Remove latest factor that was added.\n            else if(formula[i] == '(') {\n                factor = factor / stack.back();\n                stack.pop_back();\n            }\n            // once we detect a letter, we know it can only be a word. num gives us the atom subscript\n            // and factor gives us the molecular count.\n            else if(isLetter(formula[i])) {\n                name = buildName(formula, i);\n                if(num == -1) {\n                    addKey(count, name, 1 * factor);\n                }\n                else {\n                    addKey(count, name, num * factor);\n                }\n                num = -1; // reset number\n            }\n            else if(isNumber(formula[i])) {\n                num = buildCount(formula, i, stack);\n            }\n            i--;\n        }\n\n        // arrange name and count in a string\n        map<string, long int>::iterator it;\n        for (it = count.begin(); it != count.end(); it++)\n        {\n            ans = ans + it->first;\n            if(it->second != 1) {\n                ans = ans + to_string(it->second);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Merge Intervals",
        "algo_input": "Given an array&nbsp;of intervals&nbsp;where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n\n\nExample 2:\n\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nExplanation: Intervals [1,4] and [4,5] are considered overlapping.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= intervals.length &lt;= 104\n\tintervals[i].length == 2\n\t0 &lt;= starti &lt;= endi &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def merge(self, A: List[List[int]]) -> List[List[int]]:\n\t#sort array wrt its 0'th index\n        A.sort(key=lambda x:x[0])\n        i=0\n        while i<(len(A)-1):\n            if A[i][1]>=A[i+1][0]:\n                A[i][1]=max(A[i+1][1],A[i][1])\n                A.pop(i+1)\n            else:\n                i+=1\n        return(A)\n                ",
        "solution_js": "/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\n\nvar merge = function(intervals) {\n    // sorting the intervals array first is a general good first step\n    intervals.sort((a,b) => a[0] - b[0]);\n    const result = [];\n    // i am using the result array as a way to compare previous and next intervals\n    result.push(intervals[0])\n    for (let i=1; i<intervals.length; i++) {\n        const prevInterval = result[result.length-1]\n        const interval = intervals[i]\n        \n        if (prevInterval[1] >= interval[0]) {\n            // overlap detected\n            const [ l, r ] = result.pop();\n            // if overlap, merge intervals by taking min/max of both boundaries\n            const newL = Math.min(l, interval[0])\n            const newR = Math.max(r, interval[1])\n            result.push([newL, newR])\n        } else {\n            result.push(intervals[i])\n        }\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public int[][] merge(int[][] intervals) {\n        // sort\n        // unknown size of ans = use ArrayList\n        // insert from back\n            // case 1 : Merging\n                // start of new interval is less that end of old interval\n                // new end = Math.max(new intervals end, old intervals end)\n            // case 2 : Non-merging\n                // seperate interval\n        // convert ArrayList to array and return\n\n        Arrays.sort(intervals, (a,b) -> a[0]-b[0]);\n        ArrayList<int[]> list = new ArrayList<>();\n        for(int i = 0; i < intervals.length; i++) {\n            if(i == 0) {\n                list.add(intervals[i]);\n            } else {\n                int[] prev = list.get(list.size()-1);\n                int[] curr = intervals[i];\n                if(curr[0] <= prev[1]) {\n                    prev[1] = Math.max(curr[1], prev[1]);\n                }else {\n                    list.add(curr);\n                }\n            }\n        }\n        return list.toArray(new int[list.size()][2]);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> merge(vector<vector<int>>& intervals) {\n        sort(intervals.begin(), intervals.end());\n        vector<vector<int>> res;\n        int i=0;\n        while(i<=intervals.size()-1){\n            int start=intervals[i][0];\n            int end=intervals[i][1];\n            while(i<intervals.size()-1 && end>=intervals[i+1][0]){\n                i++;\n                if(end<intervals[i][1]) end=intervals[i][1];\n            }\n            i++;\n            res.push_back({start, end});\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Orderly Queue",
        "algo_input": "You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string..\n\nReturn the lexicographically smallest string you could have after applying the mentioned step any number of moves.\n\n&nbsp;\nExample 1:\n\nInput: s = \"cba\", k = 1\nOutput: \"acb\"\nExplanation: \nIn the first move, we move the 1st character 'c' to the end, obtaining the string \"bac\".\nIn the second move, we move the 1st character 'b' to the end, obtaining the final result \"acb\".\n\n\nExample 2:\n\nInput: s = \"baaca\", k = 3\nOutput: \"aaabc\"\nExplanation: \nIn the first move, we move the 1st character 'b' to the end, obtaining the string \"aacab\".\nIn the second move, we move the 3rd character 'c' to the end, obtaining the final result \"aaabc\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= s.length &lt;= 1000\n\ts consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def orderlyQueue(self, s: str, k: int) -> str:\n        if k>1:\n            s=list(c for c in s)\n            s.sort()\n            return ''.join(s)\n        s1=s\n        for i in range(len(s)):\n            s=s[1:]+s[0]\n            s1=min(s1,s)\n        return s1",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar orderlyQueue = function(s, k) {\n  // rotate the string one by one, and check which is lexographically smaller\n  if (k === 1) {\n    let temp = `${s}`;\n    let smallest = `${s}`;\n    let count = 0;\n    while (count < s.length) {\n      temp = temp.substring(1, s.length) + temp.charAt(0);\n      if (temp < smallest) {\n        smallest = temp;\n      }\n      count++;\n    }\n    return smallest;\n  }\n  \n  // if k is greater than 1, any permutation is possilbe\n  // so we simply return the sorted string (convert to array -> sort -> back to string)\n  if (k > 1) {\n    return [...s].sort().join('');\n  }\n  \n  return s;\n};",
        "solution_java": "// Time O(n)\n// Space O(n)\nclass Solution {\n    public String orderlyQueue(String s, int k) {\n        int n = s.length();\n        String ans = \"\";\n        if (k == 1){\n            s+=s; // add itself again\n            for (int i = 0; i < n; i++) if (ans.isEmpty() || s.substring(i, i+n).compareTo(ans) < 0){\n                ans = s.substring(i, i+n);\n            }\n        }else{\n            char[] arr = s.toCharArray();\n            Arrays.sort(arr);\n            ans = String.valueOf(arr);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\nstring orderlyQueue(string s, int k) {\n \nif(k>1){\n       sort(s.begin(),s.end());\n       return s;\n    }\n    else{\n        string res=s;\n        \n        for(int i=0;i<s.length();i++){\n            s=s.substr(1)+s.substr(0,1);\n            res=min(res,s);\n        }\n        return res;\n    }\n    \n    return s;\n    \n}\n};"
    },
    {
        "title": "Thousand Separator",
        "algo_input": "Given an integer n, add a dot (\".\") as the thousands separator and return it in string format.\n\n&nbsp;\nExample 1:\n\nInput: n = 987\nOutput: \"987\"\n\n\nExample 2:\n\nInput: n = 1234\nOutput: \"1.234\"\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution(object):\n    def thousandSeparator(self, n):\n        \"\"\"\n        :type n: int\n        :rtype: str\n        \"\"\"\n        n = str(n)\n        if len(n) <= 3:\n            return str(n)\n        result = \"\"      \n        dot = '.'\n        index = 0\n        startPos = len(n) % 3 \n        if startPos == 0:\n            startPos += 3\n        val = -1\n        while index < len(n):\n            result += n[index]\n            if index == startPos - 1:\n                result += dot\n                val = 0\n            if val != -1:\n                val += 1\n                if val > 3 and (val - 1) % 3 == 0 and index != len(n) - 1:\n                    result += dot\n                    val = 1  \n            index += 1\n\n        return result",
        "solution_js": "var thousandSeparator = function(n) {\n    let ans = \"\";\n\n    if(n >= 1000){\n    const arr = String(n).split('');\n        for(let i=0;i<arr.length;i++){\n            let temp = arr.length - i;\n            if(temp === 3 && arr.length > temp || temp === 6 && arr.length > temp || temp === 9 && arr.length > temp || temp === 12 && arr.length > temp){\n                ans += '.';\n            }\n        ans += arr[i];\n        }\n    }else{\n        ans += n;\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public String thousandSeparator(int n) {\n       \n        StringBuffer str = new StringBuffer(Integer.toString(n));\n        int index = str.length() - 3;\n        \n        while(index >= 1){\n            str.insert(index , '.');\n            index = index - 3;\n        }\n        \n        return str.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string thousandSeparator(int n) {\n        string s=\"\";\n        int a=0;\n        if(n==0)return \"0\";\n       while(n>0){\n           s+=char(n%10+48);\n           a++;\n           n/=10;\n           if(a==3&&n!=0)\n           {\n               a=0;\n               s+=\".\";\n           }\n       }\n        reverse(s.begin(),s.end());\n        return s;\n    }\n};"
    },
    {
        "title": "Avoid Flood in The City",
        "algo_input": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.\n\nGiven an integer array rains where:\n\n\n\trains[i] &gt; 0 means there will be rains over the rains[i] lake.\n\trains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.\n\n\nReturn an array ans where:\n\n\n\tans.length == rains.length\n\tans[i] == -1 if rains[i] &gt; 0.\n\tans[i] is the lake you choose to dry in the ith day if rains[i] == 0.\n\n\nIf there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\n\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.\n\n&nbsp;\nExample 1:\n\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.\n\n\nExample 2:\n\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\n\n\nExample 3:\n\nInput: rains = [1,2,0,1,2]\nOutput: []\nExplanation: After the second day, full lakes are  [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rains.length &lt;= 105\n\t0 &lt;= rains[i] &lt;= 109\n\n",
        "solution_py": "from bisect import bisect_left\n\nclass Solution:\n    def avoidFlood(self, rains):\n        full_lakes, dry_dates = {}, []\n        ans = [-1] * len(rains)\n\n        for date, rain_lake in enumerate(rains):\n            if rain_lake == 0:  # no rain, we can dry one lake\n                dry_dates.append(date)  # keep dry date, we'll decide later\n                continue\n\n            if rain_lake in full_lakes:  # the lake is already full\n                # BS find out earliest day we can use to dry that lake | greedy\n                dry_day = bisect_left(dry_dates, full_lakes[rain_lake])\n\n                if dry_day >= len(dry_dates): return []  # can not find a date to dry this lake\n\n                ans[dry_dates.pop(dry_day)] = rain_lake  # dry this lake at the date we choose\n\n            # remember latest rain on this lake\n            full_lakes[rain_lake] = date\n\n        # we may have dry dates remain, on these days, rain > 0, we can not use -1, just choose day 1 to dry (maybe nothing happend)\n        for dry_day in dry_dates:\n            ans[dry_day] = 1\n\n        return ans",
        "solution_js": "var avoidFlood = function(rains) {\n    const n = rains.length;\n    const filledLakes = new Map();\n    const res = new Array(n).fill(-1);\n    const dryDays = [];\n\n    for (let i = 0; i < n; i++) {\n        const lake = rains[i]; // lake to rain on\n\n        if (lake === 0) {\n        // It is a dry day\n            dryDays.push(i);\n        }\n        else if (!filledLakes.has(lake)) {\n        // The lake is not filled yet, so we let it be filled (we just don't want it to be rained on again and be flooded)\n            filledLakes.set(lake, i);\n        }\n        else {\n        // The lake is already filled. We want to see if a dry day was available after the lake was previously rained on so that we can empty the lake\n            const lake_index = filledLakes.get(lake); //\n            const dry_index = binarySearch(lake_index);\n\n            if (dry_index === dryDays.length) return []; // there was no dry day after the lake was previouly filled\n\n            res[dryDays[dry_index]] = lake; // mark the earliest dry day that was used in our result array\n            filledLakes.set(lake, i); // we need to update the day that the lake is rained on again\n            dryDays.splice(dry_index, 1); // remove the dry day that was used (this is not very efficient, but it just makes our code cleaner)\n        }\n    }\n\n    dryDays.forEach((day) => res[day] = 1);\n\n    return res;\n\n    function binarySearch(target) {\n        let left = 0;\n        let right = dryDays.length - 1;\n\n        while (left <= right) {\n            const mid = left + Math.floor((right - left) / 2);\n\n            if (dryDays[mid] < target) left = mid + 1;\n            else right = mid - 1;\n        }\n\n        return left;\n    }\n};",
        "solution_java": "class Solution {\n    public int[] avoidFlood(int[] rains) {\n        // the previous appeared idx of rains[i]\n        Map<Integer, Integer> map = new HashMap<>();\n        TreeSet<Integer> zeros = new TreeSet<>();\n        int[] res = new int[rains.length];\n        for (int i = 0; i < rains.length; i++) {\n            if (rains[i] == 0) {\n                zeros.add(i);\n            } else {\n                if (map.containsKey(rains[i])) {\n                    // find the location of zero that can be used to empty rains[i]\n                    Integer next = zeros.ceiling(map.get(rains[i]));\n                    if (next == null) return new int[0];\n                    res[next] = rains[i];\n                    zeros.remove(next);\n                }\n                res[i] = -1;\n\t\t\t\tmap.put(rains[i], i);\n            }\n        }\n        for (int i : zeros) res[i] = 1;\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> avoidFlood(vector<int>& rains) {\n        vector<int> ans(rains.size() , -1) ;\n        unordered_map<int,int> indices ; //store the lake and its index \n        set<int> st ; //stores the indices of zeros \n        \n        for(int i = 0 ; i < rains.size() ; ++i ){\n            if(!rains[i]) st.insert(i) ;\n            else{\n                if(indices.find(rains[i]) == end(indices)) indices[rains[i]] = i ;\n                else{\n                    int prevDay = indices[rains[i]] ;\n                    auto it = st.upper_bound(prevDay) ;\n                    if(it == end(st)) return {} ;\n                    ans[*it] = rains[i] ;\n                    indices[rains[i]] = i ;\n                    st.erase(it);\n                }\n            }\n        }\n        \n        for(int i = 0 ; i < ans.size(); ++i ){\n            if(!rains[i] and ans[i] == -1) ans[i] = 1 ;\n        }\n        return ans ;\n    }\n};"
    },
    {
        "title": "Shortest Palindrome",
        "algo_input": "You are given a string s. You can convert s to a palindrome by adding characters in front of it.\n\nReturn the shortest palindrome you can find by performing this transformation.\n\n&nbsp;\nExample 1:\nInput: s = \"aacecaaa\"\nOutput: \"aaacecaaa\"\nExample 2:\nInput: s = \"abcd\"\nOutput: \"dcbabcd\"\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 5 * 104\n\ts consists of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def shortestPalindrome(self, s: str) -> str:\n        \n        end = 0\n        \n        # if the string itself is a palindrome return it\n        if(s == s[::-1]):\n            return s\n        \n        # Otherwise find the end index of the longest palindrome that starts\n        # from the first character of the string\n        \n        for i in range(len(s)+1):\n            if(s[:i]==s[:i][::-1]):\n                end=i-1\n        \n        # return the string with the remaining characters other than\n        # the palindrome reversed and added at the beginning\n        \n        return (s[end+1:][::-1])+s",
        "solution_js": "var shortestPalindrome = function(s) {\n    const rev = s.split('').reverse().join('');\n    const slen = s.length;\n\n    const z = s + '$' + rev;\n    const zlen = z.length;\n\n    const lpt = new Array(zlen).fill(0);\n\n    for(let i = 1; i < zlen; i++) {\n        let j = lpt[i-1];\n\n        while(j > 0 && z.charAt(i) != z.charAt(j))\n            j = lpt[j-1];\n\n        if(z.charAt(i) == z.charAt(j))\n            j++;\n\n        lpt[i] = j;\n    }\n\n    return rev.slice(0, slen - lpt.at(-1)) + s;\n};",
        "solution_java": "class Solution {\n    public String shortestPalindrome(String s) {\n        for(int i=s.length()-1; i >= 0; i--){\n            if(isPalindrome(s, 0, i)){\n                String toAppend = s.substring(i+1);\n                String result = new StringBuilder(toAppend).reverse().append(s).toString();\n                return result;\n            }\n        }\n        String result = new StringBuilder(s).reverse().append(s).toString();\n        return result;        \n    }\n    \n    boolean isPalindrome(String s, int left, int right){\n        while(left < right){\n            if(s.charAt(left) != s.charAt(right))\n                return false;\n            left++;\n            right--;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string shortestPalindrome(string s) {\n        \n        int BASE = 26, MOD = 1e9+7;\n        int start = s.size()-1;\n        \n        // Calculate hash values from front and back\n        long front = 0, back = 0;\n        long power = 1;\n        \n        for(int i=0; i<s.size(); i++){\n            front = (front*BASE + (s[i]-'a'+1))%MOD;\n            back = (back*BASE + (s[start--]-'a'+1))%MOD;\n            power = (power*BASE)%MOD;\n        }\n        \n        // If hash values of both front and back are same, then it is a palindrome\n        if(front == back){\n            return s;\n        }\n        \n        // As it is not palindrome, add last characters in the beginning, and then check.\n        // Store the hash value of the newly added characters from front and back\n        \n\t\t// new_front will be added to front to get new hash value\n        // new_back will be added to back to get new hash value \n        long new_front = 0, new_back = 0;\n        long new_power = 1;\n\t\t\n\t\tint end=s.size()-1;\n        string ans = \"\";\n        \n        while(end >= 0){\n\t\t\t// Taking character from ending \n            int ch = (s[end]-'a'+1);\n            \n            new_front = (new_front*BASE + ch*power) % MOD;\n            new_back = (ch*new_power + new_back) % MOD;\n            new_power = (new_power*BASE) % MOD;\n            \n            int final_front = (new_front + front) % MOD;\n\t\t\tback = (back*BASE) % MOD;\n            int final_back = (new_back + back) % MOD;\n                \n\t\t\t// Storing it in separate string\n            ans += s[end];\n            end--;\n            \n\t\t\t// Both hashes are same\n            if(final_front == final_back){\n                break;\n            }\n        }\n        return ans+s;\n    }\n};"
    },
    {
        "title": "Ways to Make a Fair Array",
        "algo_input": "You are given an integer array&nbsp;nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.\n\nFor example, if nums = [6,1,7,4,1]:\n\n\n\tChoosing to remove index 1 results in nums = [6,7,4,1].\n\tChoosing to remove index 2 results in nums = [6,1,4,1].\n\tChoosing to remove index 4 results in nums = [6,1,7,4].\n\n\nAn array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.\n\nReturn the number of indices that you could choose such that after the removal, nums is fair. \n\n&nbsp;\nExample 1:\n\nInput: nums = [2,1,6,4]\nOutput: 1\nExplanation:\nRemove index 0: [1,6,4] -&gt; Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -&gt; Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -&gt; Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -&gt; Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.\n\n\nExample 2:\n\nInput: nums = [1,1,1]\nOutput: 3\nExplanation:&nbsp;You can remove any index and the remaining array is fair.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation:&nbsp;You cannot make a fair array after removing any index.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n\tdef waysToMakeFair(self, nums: List[int]) -> int:\n\t\tif len(nums) == 1:\n\t\t\treturn 1\n\n\t\tif len(nums) == 2:\n\t\t\treturn 0\n\n\t\tprefixEven = sum(nums[2::2])\n\t\tprefixOdd = sum(nums[1::2])\n\t\tresult = 0\n\n\t\tif prefixEven == prefixOdd and len(set(nums)) == 1:\n\t\t\tresult += 1\n\n\t\tfor i in range(1,len(nums)):\n\t\t\tif i == 1:\n\t\t\t\tprefixOdd, prefixEven = prefixEven, prefixOdd \n\n\t\t\tif i > 1:\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tprefixEven -= nums[i-1]\n\t\t\t\t\tprefixEven += nums[i-2]\n\n\t\t\t\telse:\n\t\t\t\t\tprefixOdd -= nums[i-1]\n\t\t\t\t\tprefixOdd += nums[i-2]\n\n\t\t\tif prefixOdd == prefixEven:\n\t\t\t\tresult += 1\n\n\t\treturn result",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar waysToMakeFair = function(nums) {\n    let oddSum = 0; \n    let evenSum = 0 ;\n    let count = 0;\n    \n    for (let i = 0; i < nums.length; i++) {\n        if (i % 2 === 0) {\n            evenSum += nums[i];\n        } else {\n            oddSum += nums[i];\n        }\n    }\n    \n    \n    for (let i = 0; i < nums.length; i++) {\n        if (i % 2 === 0) {\n            evenSum -= nums[i];\n            if (evenSum === oddSum) {\n                count++; \n            }\n            oddSum += nums[i];\n        } else {\n            oddSum -= nums[i];\n            if (evenSum === oddSum) {\n                count++;\n            }\n            evenSum += nums[i]\n        }\n    }\n    \n    return count;\n};",
        "solution_java": "class Solution {\n    public int waysToMakeFair(int[] nums) {\n        \n        /*\n        Idea - \n        \n        have left (odd & even) & right (odd & even) odd & even sums separately\n        \n        as we move each element subtract & add appropriately\n        */\n        int count = 0;\n        \n        int evenLeft = 0;\n        int oddLeft = 0;\n        \n        int evenRight = 0;\n        int oddRight = 0;\n            \n        // calculate the right odd & even initially since we move from 0->n\n        for(int i=0;i<nums.length;i++)\n        {\n            if(i%2 == 0)\n            {\n                evenRight+=nums[i];\n            } else{\n                oddRight+= nums[i];\n            }\n        }\n        \n        // move from 0 -> n\n        for(int i=0;i<nums.length;i++)\n        {\n            \n            // start from 1 since left at 0 index is 0 anyways & array bounds checked\n            if(i>0)\n            {\n                // add previous element to left count\n                if(i%2 == 0)\n                {\n                     oddLeft +=nums[i-1];\n                } else{\n                     evenLeft+=nums[i-1];\n                }\n            }\n            \n            // subtract current element value from right counts so we get right count excluding the current element\n            if(i%2 == 0)\n            {\n                evenRight-=nums[i];\n            } else{\n                oddRight-=nums[i];\n            }\n            \n            // if at any point we have below condition true increment count\n            // notice here we are adding even & odd of opposite sides here since on excluding the current element the right counterpart sum switches\n            // i.e if it was odd before it becomes even, else if it was even becomes odd\n             if(evenLeft+oddRight == oddLeft+evenRight)\n                {\n                    count++;\n                }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int waysToMakeFair(vector<int>& nums) {\n        //it looks a quite complicated problem but actually it is not\n        //the main observation here is when a element is deleted the odd sum after the element becomes the evensum and vice versa\n        //so we maintain two vectors left and right\n        vector<int> left(2,0);\n        vector<int> right(2,0);\n        \n        //left[0],right[0] stores the sum of even indices elements to the left and right side of the element respectively\n        //left[1] right[1] stores the sum of odd indices elements to the left and right side of the element respectively\n        \n        int ans=0; //stores the result\n        //first store the odd sum and even sum in right\n        for(int i=0;i<nums.size();i++)\n        {\n            if(i%2)\n            {\n                //odd index \n                right[1]+=nums[i];\n            }\n            else{\n                //even index \n                right[0]+=nums[i];\n            }\n        }\n        \n        //now traverse through every element in the array and try to remove the element  and check does it makes a fair array\n        for(int i=0;i<nums.size();i++)\n        {\n            //try to remove the element\n            int currOdd=right[1];\n            int currEven=right[0];\n            if(i%2)\n            {\n                //odd index , remove it from currOdd\n                currOdd-=nums[i];\n                right[1]-=nums[i]; //since it would be no longer to the right\n            }\n            else{\n                //even index , remove it from currEven\n                currEven-=nums[i];\n                right[0]-=nums[i];\n            }\n            //now check whether the total oddSum and the evenSum in the array are equal ?\n            //since we are deleting this element oddSum becomes evenSum and evenSum becomes oddSum\n            //check leftOdd+rightOdd==rightEven+leftEven\n            //left[0] is even sum to left of i \n            //left[1] is the odd sum to left of i\n            if(left[0]+currOdd==left[1]+currEven)\n                ans++;\n            //since we traverse to right add this value to the left array\n            (i%2) ? left[1]+=nums[i] : left[0]+=nums[i];\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Simplify Path",
        "algo_input": "Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.\n\nIn a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.\n\nThe canonical path should have the following format:\n\n\n\tThe path starts with a single slash '/'.\n\tAny two directories are separated by a single slash '/'.\n\tThe path does not end with a trailing '/'.\n\tThe path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')\n\n\nReturn the simplified canonical path.\n\n&nbsp;\nExample 1:\n\nInput: path = \"/home/\"\nOutput: \"/home\"\nExplanation: Note that there is no trailing slash after the last directory name.\n\n\nExample 2:\n\nInput: path = \"/../\"\nOutput: \"/\"\nExplanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.\n\n\nExample 3:\n\nInput: path = \"/home//foo/\"\nOutput: \"/home/foo\"\nExplanation: In the canonical path, multiple consecutive slashes are replaced by a single one.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= path.length &lt;= 3000\n\tpath consists of English letters, digits, period '.', slash '/' or '_'.\n\tpath is a valid absolute Unix path.\n\n",
        "solution_py": "class Solution:\n   def simplifyPath(self, path: str) -> str:\n   \tstack = []\n   \t\n   \ti = 0\n       while i < len(path):\n           if path[i] == '/':\n               i += 1\n               continue\n\n           else:\n               cur = ''\n               while i < len(path) and path[i] != '/':\n                   cur += path[i]\n                   i += 1\n\n               if cur == '..':\n                   if stack:\n                       stack.pop()\n               elif cur == '.' or cur == '':\n                   i += 1\n                   continue\n               else:\n                    stack.append(cur)\n\n       return '/' + '/'.join(stack)",
        "solution_js": "var simplifyPath = function(path) {\n    let stack=[];\n    path=path.split(\"/\")\n    for(let i=0;i<path.length;i++){\n        if(path[i]===\"\" || path[i]===\".\")continue;\n        if(path[i]===\"..\"){\n            stack.pop();\n        }else{\n            stack.push(path[i]);\n        }\n    }\n    //edge case\n    if(stack.length===0)return \"/\"\n    //edge case\n\n    let string=\"\";\n    for(let j=0;j<stack.length;j++){\n        string+=\"/\"+stack[j];\n    }\n    return string;\n};",
        "solution_java": "class Solution {\n    public String simplifyPath(String path) {\n        String[] paths = path.split(\"/\");\n        Stack<String> st=new Stack<>();\n        for(String dir:paths){\n            if(dir.equals(\".\") || dir.length()==0) continue;\n            else{\n                if(!st.isEmpty() && dir.equals(\"..\"))\n                    st.pop();\n                else if(st.isEmpty() && dir.equals(\"..\"))\n                    continue;\n                else st.push(dir);\n            }\n        }\n        StringBuilder sb=new StringBuilder();\n        if(st.isEmpty()) return \"/\";\n        for(String s:st){\n            sb.append(\"/\"); sb.append(s);\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "                    // Please upvote if it helps\nclass Solution {\npublic:\n    string simplifyPath(string path) {\n\n        stack<string> st;\n        string res;\n\n        for(int i = 0; i<path.size(); ++i)\n        {\n            if(path[i] == '/')\n                continue;\n            string temp;\n            // iterate till we doesn't traverse the whole string and doesn't encounter the last /\n            while(i < path.size() && path[i] != '/')\n            {\n                // add path to temp string\n                temp += path[i];\n                ++i;\n            }\n            if(temp == \".\")\n                continue;\n            // pop the top element from stack if exists\n            else if(temp == \"..\")\n            {\n                if(!st.empty())\n                    st.pop();\n            }\n            else\n            // push the directory file name to stack\n                st.push(temp);\n        }\n\n        // adding all the stack elements to res\n        while(!st.empty())\n        {\n            res = \"/\" + st.top() + res;\n            st.pop();\n        }\n\n        // if no directory or file is present\n        if(res.size() == 0)\n            return \"/\";\n\n        return res;\n    }\n};"
    },
    {
        "title": "Maximum Score of a Good Subarray",
        "algo_input": "You are given an array of integers nums (0-indexed) and an integer k.\n\nThe score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i &lt;= k &lt;= j.\n\nReturn the maximum possible score of a good subarray.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nExplanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n\n\nExample 2:\n\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\nExplanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 2 * 104\n\t0 &lt;= k &lt; nums.length\n\n",
        "solution_py": "class Solution:\n    def nextSmallerElement(self, nums):\n        nextSmaller = [None] * len(nums)\n        stack = [[-sys.maxsize, -1]]\n        for i in range(len(nums)-1, -1, -1):\n            while nums[i] <= stack[-1][0]:\n                stack.pop()\n            nextSmaller[i] = stack[-1][1]\n            stack.append([nums[i], i])\n        return nextSmaller\n            \n    \n    def previousSmallerElement(self, nums):\n        previousSmaller = [None] * len(nums)\n        stack = [[-sys.maxsize, -1]]\n        for i in range(len(nums)):\n            while nums[i] <= stack[-1][0]:\n                stack.pop()\n            previousSmaller[i] = stack[-1][1]\n            stack.append([nums[i], i])\n        return previousSmaller\n    \n    def maximumScore(self, nums: List[int], k: int) -> int:\n        nextSmaller = self.nextSmallerElement(nums)\n        previousSmaller = self.previousSmallerElement(nums)\n\n        score = 0\n        for idx, num in enumerate(nums):\n\t\t\t# previousSmaller[idx] (let's say i) and nextSmaller[idx] (let's say j) ensures that the element present at idx is the minimum in range (i -> j)\n            i = previousSmaller[idx]\n            i += 1\n            j = nextSmaller[idx]\n            if j == -1:\n                j = len(nums)\n            j -= 1\n            if i <= k <= j:\n                score = max(score, num * (j-i+1))\n        \n        return score\n            ",
        "solution_js": "/*\n\n\tJAVASCRIPT\n\n */\nvar maximumScore = function(nums, k) {\n    // iterate to the left to update the minimum value at each index\n    let min = nums[k];\n    for (let i = k - 1; i >= 0; i--) {\n        min = Math.min(min, nums[i]);\n        nums[i] = min;\n    }\n\n    // iterate to the right to update the minimum value at each index\n    min = nums[k];\n    for (let i = k + 1; i < nums.length; i++) {\n        min = Math.min(min, nums[i]);\n        nums[i] = min;\n    }\n    \n    // start with 2 pointers at opposite ends of nums\n    let left = 0;\n    let right = nums.length - 1;\n    let bestScore = 0;\n\n    while (left <= right) {\n        bestScore = Math.max(bestScore, Math.min(nums[left], nums[right]) * (right - left + 1));\n        \n        // first to check if either pointer is at k\n        // if it is at k then we must move the other pointer inwards\n        if (left === k) {\n            right--;\n        } else if (right === k) {\n            left++\n            \n        // if neither index is at k move the pointer\n        // that is smaller inwards\n        } else if (nums[left] < nums[right]) {\n            left++;\n        } else {\n            right--;\n        }\n    }\n    return bestScore;\n};",
        "solution_java": "class Solution {\n    public int maximumScore(int[] nums, int k) {\n        int n = nums.length;\n        int i = k - 1, j = k + 1;\n        int min = nums[k];\n        int ans = min;\n\n        while(i >= 0 || j < n) {\n            int v1 = 0, v2 = 0;\n            int min1 = min, min2 = min;\n\n            if(i >= 0) {\n                min1 = Math.min(min, nums[i]);\n                v1 = min1 * (j - i);\n            }\n\n            if(j < n) {\n                min2 = Math.min(min, nums[j]);\n                v2 = min2 * (j - i);\n            }\n\n            if(v1 > v2) {\n                --i;\n                ans = Math.max(v1, ans);\n                min = Math.min(min1, min);\n            }\n            else {\n                ++j;\n                ans = Math.max(ans, v2);\n                min = Math.min(min, min2);\n            }\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumScore(vector<int>& nums, int k) {\n        nums.push_back(0);\n        stack<int> st ;\n        int n = nums.size(), res = 0;\n        for(int i=0; i<n ; i++){\n            while(!st.empty() && nums[st.top()] >= nums[i]){\n                int height = nums[st.top()];\n                st.pop();\n                int left = st.empty() ? -1: st.top();\n                if(k < i && k > left) res = max(height* (i-left-1), res);\n            }\n            st.push(i);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Least Number of Unique Integers after K Removals",
        "algo_input": "Given an array of integers&nbsp;arr&nbsp;and an integer k.&nbsp;Find the least number of unique integers&nbsp;after removing exactly k elements.\n\n\n\n\n&nbsp;\nExample 1:\n\nInput: arr = [5,5,4], k = 1\nOutput: 1\nExplanation: Remove the single 4, only 5 is left.\n\nExample 2:\n\nInput: arr = [4,3,1,1,3,3,2], k = 3\nOutput: 2\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length&nbsp;&lt;= 10^5\n\t1 &lt;= arr[i] &lt;= 10^9\n\t0 &lt;= k&nbsp;&lt;= arr.length\n",
        "solution_py": "from heapq import heappop, heapify\n\n\n\nclass Solution:\n\n    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\n        counter = collections.Counter(arr)\n\n        min_heap = [(count, num) for num, count in counter.items()]\n\n\n\n        heapify(min_heap)\n\n\n\n        while k > 0:\n\n            count, num = min_heap[0]\n\n\n\n            if count > k:\n\n                break\n\n\n\n            heappop(min_heap)\n\n            k -= count\n\n\n\n        return len(min_heap)",
        "solution_js": "var findLeastNumOfUniqueInts = function(arr, k) {\n    var hsh = {};\n    var instance = {};  // store set with index # of occurence\n    var count = 0;\n    for (var i = 0; i < arr.length; i++)\n    {\n        if (hsh[arr[i]] == null)\n        {\n            count ++;\n            hsh[arr[i]] = 1;\n            if (instance[1] == null)\n            {\n                var intro = new Set();\n                intro.add(arr[i]);\n                instance[1] = intro;\n            }\n            else\n            {\n                instance[1].add(arr[i]);\n            }\n        }\n        else\n        {\n            hsh[arr[i]] ++;\n            var numTimes = hsh[arr[i]];\n            instance[numTimes - 1].delete(arr[i]);\n            \n            if (instance[numTimes] == null)\n            {\n                instance[numTimes] = new Set();\n                instance[numTimes].add(arr[i]);\n            }\n            else\n            {\n                instance[numTimes].add(arr[i]);\n            }\n        }\n    }\n    \n    var removenum = 0;\n    \n    for (key in instance)\n    {\n        var instanceKey = instance[key].size;\n        if (k == 0)\n        {\n            break;\n        }\n        else if (k >= key*instanceKey)\n        {\n            k -= key*instanceKey;\n            count -= instanceKey;\n        }\n        else\n        {\n            count -= Math.floor(k/key);\n            break;\n        }\n        \n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int findLeastNumOfUniqueInts(int[] arr, int k) {\n        Map<Integer,Integer> freqMap = new HashMap<>();\n        for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1);\n        PriorityQueue<Integer> pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2)));\n        pq.addAll(freqMap.keySet());\n        while(k>0 && !pq.isEmpty()){\n            int element = pq.poll();\n            int toBeDeleted = Math.min(k,freqMap.get(element));\n            k-=toBeDeleted;\n            if(toBeDeleted<freqMap.get(element)) \n                pq.add(element);\n        }\n        return pq.size();\n    }\n}",
        "solution_c": "class Solution {\n\npublic:\n\n    int findLeastNumOfUniqueInts(vector<int>& arr, int k) {\n\n        int ans;\n\n        unordered_map<int,int> mp;\n\n        for(int i=0; i<arr.size(); i++){\n\n            mp[arr[i]]++;\n\n        }\n\n\n\n        priority_queue< int, vector<int>, greater<int>> pq;\n\n        for(auto it : mp){\n\n            pq.push(it.second);\n\n        }\n\n\n\n        while(k>0){\n\n           k-= pq.top();   \n\n           if(k>=0){\n\n              pq.pop(); \n\n           }\n\n        }\n\n        return pq.size();\n\n    }\n\n};"
    },
    {
        "title": "Minimum Time to Type Word Using Special Typewriter",
        "algo_input": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.\n\nEach second, you may perform one of the following operations:\n\n\n\tMove the pointer one character counterclockwise or clockwise.\n\tType the character the pointer is currently on.\n\n\nGiven a string word, return the minimum number of seconds to type out the characters in word.\n\n&nbsp;\nExample 1:\n\nInput: word = \"abc\"\nOutput: 5\nExplanation: \nThe characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.\n\n\nExample 2:\n\nInput: word = \"bza\"\nOutput: 7\nExplanation:\nThe characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.\n\n\nExample 3:\n\nInput: word = \"zjpc\"\nOutput: 34\nExplanation:\nThe characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 100\n\tword consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def minTimeToType(self, word: str) -> int:\n        prev = \"a\"\n        res = 0\n        for c in word:\n            gap = abs(ord(c)-ord(prev))\n            res += min(gap, 26 - gap)\n            prev = c\n        return res + len(word)",
        "solution_js": "var minTimeToType = function(word) {\n  let ops = 0;\n  let cur = 'a';\n  \n  for(const char of word) {\n    const diff = Math.abs(cur.charCodeAt(0) - char.charCodeAt(0));\n    if(diff > 13) {\n      ops += 26 - diff + 1;\n    } else {\n      ops += diff + 1;\n    }\n    \n    cur = char;\n  }\n  \n  return ops;\n};",
        "solution_java": "class Solution {\n    public int minTimeToType(String word) {\n        char prevChar = 'a';\n        int totalTime = word.length();\n        for(int i = 0; i < word.length(); i++){\n            char currChar = word.charAt(i);\n            int diff = Math.abs(currChar - prevChar);\n            totalTime += Math.min(diff, 26 - diff);\n            prevChar = currChar;\n        }\n        \n        return totalTime;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minTimeToType(string word) {\n        int res = word.size(), point = 'a';\n        for (auto ch : word) {\n            res += min(abs(ch - point), 26 - abs(point - ch));\n            point = ch;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Equal Row and Column Pairs",
        "algo_input": "Given a 0-indexed n x n integer matrix grid, return the number of pairs (Ri, Cj) such that row Ri and column Cj are equal.\n\nA row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput: 1\nExplanation: There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]\n\n\nExample 2:\n\nInput: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput: 3\nExplanation: There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 200\n\t1 &lt;= grid[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def equalPairs(self, grid: List[List[int]]) -> int:\n        m = defaultdict(int)\n        cnt = 0\n\n        for row in grid:\n            m[str(row)] += 1\n        \n        for i in range(len(grid[0])):\n            col = []\n            for j in range(len(grid)):\n                col.append(grid[j][i])\n            cnt += m[str(col)]\n        return cnt",
        "solution_js": "var equalPairs = function(grid) {\n    let n = grid.length\n    let count = 0;\n\n    let map = new Map()\n\n    //making rowArray\n    for(let row = 0; row < n; row++){\n        let temp = []\n        for(let col = 0; col < n; col++){\n            temp.push(grid[row][col])\n        }\n\n        temp = temp.join()\n\n        if(map.has(temp)){\n            let tempCount = map.get(temp)\n            map.set(temp, tempCount+1)\n        }\n        else{\n            map.set(temp, 1)\n        }\n    }\n\n    for(let col = 0; col < n; col++){\n        let temp = []\n        for(let row = 0; row < n; row++){\n            temp.push(grid[row][col])\n        }\n\n        temp = temp.join()\n\n        if(map.has(temp)){\n            count += map.get(temp)\n        }\n    }\n\n    return count;\n};",
        "solution_java": "class Solution {\n    public int equalPairs(int[][] grid) {\n        HashMap<String, Integer> map = new HashMap<>();\n        int row = grid.length;\n        int col = grid.length;\n        for(int i = 0; i < row; i++){\n            String res = \"\";\n            for(int j = 0; j < col; j++){\n                res += \"-\" + grid[i][j];\n            }\n            map.put(res, map.getOrDefault(res, 0) + 1);\n        }\n        int cnt = 0;\n        for(int j = 0; j < col; j++){\n            String res = \"\";\n            for(int i = 0; i < row; i++){\n                res += \"-\" + grid[i][j];\n            }\n            cnt += map.getOrDefault(res, 0);\n        }\n        return cnt;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int equalPairs(vector<vector<int>>& grid) \n    {\n        // Number to store the count of equal pairs.\n        int ans = 0;\n        map<vector<int>, int> mp;\n        // Storing each row int he map\n        for (int i = 0; i < grid.size(); i++)\n            mp[grid[i]]++;\n        \n        for (int i = 0; i < grid[0].size(); i++)\n        {\n            vector<int> v;\n            // extracting column in a vector.\n            for (int j = 0; j < grid.size(); j++)\n                v.push_back(grid[j][i]);\n            // Add the number of times that column appeared as a row.\n            ans += mp[v];\n        }\n        // Return the number of count\n        return ans;\n    }\n};"
    },
    {
        "title": "Magical String",
        "algo_input": "A magical string s consists of only '1' and '2' and obeys the following rules:\n\n\n\tThe string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.\n\n\nThe first few elements of s is s = \"1221121221221121122……\". If we group the consecutive 1's and 2's in s, it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1's or 2's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\". You can see that the occurrence sequence is s itself.\n\nGiven an integer n, return the number of 1's in the first n number in the magical string s.\n\n&nbsp;\nExample 1:\n\nInput: n = 6\nOutput: 3\nExplanation: The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def magicalString(self, n: int) -> int:\n        queue, ans, i = deque([2]), 1, 1\n\n        while i <= n - 2:\n            m = queue.popleft()\n            ans += (m == 1)\n            queue.extend([1 + (i % 2 == 0)] * m)\n            i += 1\n\n        return ans",
        "solution_js": "var magicalString = function(n) {\n    const stack = ['1', '2', '2'];\n    let magic = 2;\n\n    while (stack.length < n) {\n        const count = stack[magic++];\n        const last = stack[stack.length - 1];\n        const addStr = last === '1' ? '2' : '1';\n\n        for (let n = 1; n <= count; n++) stack.push(addStr);\n    }\n    return stack.slice(0, n).filter(str => str === '1').length;\n};",
        "solution_java": "class Solution {\n    public int magicalString(int n) {\n        if(n <= 3)\n            return 1;\n        Magical m = new Magical();\n        int ans = 1;\n        for(int i = 3; i < n; ++i)\n            if(m.next() == 1)\n                ++ans;\n        return ans;\n    }\n}\n\nclass Magical{\n\n    private Deque<Integer> nums;\n    private int n;\n\n    public Magical(){\n        nums = new ArrayDeque<>();\n        nums.offerLast(1);\n        nums.offerLast(1);\n        n = 1;\n    }\n\n    public int next(){\n        if(n-- < 0){\n            int c = nums.pollFirst();\n            n = c - 2;\n            int curr = 3 - nums.peekLast();\n            for(; c > 0; --c)\n                nums.offerLast(curr);\n            return curr;\n        }\n        return nums.peekLast();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int magicalString(int n) {\n        string s=\"122\";\n        int sz=3;\n        int start=2,lastDig=2;\n        while(sz<n){\n            int cnt=s[start++]-'0';\n            int currDig=(lastDig==2)?1:2;\n            for(int i=0;i<cnt;i++){\n                s.push_back('0'+currDig);\n                sz++;\n            }\n            lastDig=currDig;\n        }\n        int ans=0;\n        for(int i=0;i<n;i++){\n            if(s[i]=='1'){\n                ans++;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Design a Text Editor",
        "algo_input": "Design a text editor with a cursor that can do the following:\n\n\n\tAdd text to where the cursor is.\n\tDelete text from where the cursor is (simulating the backspace key).\n\tMove the cursor either left or right.\n\n\nWhen deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 &lt;= cursor.position &lt;= currentText.length always holds.\n\nImplement the TextEditor class:\n\n\n\tTextEditor() Initializes the object with empty text.\n\tvoid addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.\n\tint deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.\n\tstring cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.\n\tstring cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n[[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]\nOutput\n[null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]\n\nExplanation\nTextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\ntextEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\ntextEditor.deleteText(4); // return 4\n                          // The current text is \"leet|\". \n                          // 4 characters were deleted.\ntextEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \ntextEditor.cursorRight(3); // return \"etpractice\"\n                           // The current text is \"leetpractice|\". \n                           // The cursor cannot be moved beyond the actual text and thus did not move.\n                           // \"etpractice\" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return \"leet\"\n                          // The current text is \"leet|practice\".\n                          // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n                           // The current text is \"|practice\".\n                           // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return \"\"\n                          // The current text is \"|practice\".\n                          // The cursor cannot be moved beyond the actual text and thus did not move. \n                          // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return \"practi\"\n                           // The current text is \"practi|ce\".\n                           // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length, k &lt;= 40\n\ttext consists of lowercase English letters.\n\tAt most 2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.\n\n\n&nbsp;\nFollow-up: Could you find a solution with time complexity of O(k) per call?\n",
        "solution_py": "class TextEditor:\n\n    def __init__(self):\n        self.s = ''\n        self.cursor = 0\n\n    def addText(self, text: str) -> None:\n        self.s = self.s[:self.cursor] + text + self.s[self.cursor:]\n        self.cursor += len(text)\n\n    def deleteText(self, k: int) -> int:\n        new_cursor = max(0, self.cursor - k)\n        noOfChars = k if self.cursor - k >= 0 else self.cursor\n        self.s = self.s[:new_cursor] + self.s[self.cursor:]\n        self.cursor = new_cursor\n        return noOfChars\n\n    def cursorLeft(self, k: int) -> str:\n        self.cursor = max(0, self.cursor - k)\n        start = max(0, self.cursor-10)\n        return self.s[start:self.cursor]\n\n    def cursorRight(self, k: int) -> str:\n        self.cursor = min(len(self.s), self.cursor + k)\n        start = max(0, self.cursor - 10)\n        return self.s[start:self.cursor]",
        "solution_js": "var TextEditor = function() {\n    this.forward = [];\n    this.backward = [];\n};\n\n/** \n * @param {string} text\n * @return {void}\n */\nTextEditor.prototype.addText = function(text) {\n    for (let letter of text) {\n        this.forward.push(letter);\n    }\n};\n\n/** \n * @param {number} k\n * @return {number}\n */\nTextEditor.prototype.deleteText = function(k) {\n    let deleted = 0;\n    while (this.forward.length && deleted < k) {\n        this.forward.pop();\n        deleted++;\n    }\n    return deleted;\n};\n\n/** \n * @param {number} k\n * @return {string}\n */\nTextEditor.prototype.cursorLeft = function(k) {\n    let moved = 0;\n    while (this.forward.length && moved < k) {\n        this.backward.push(this.forward.pop());\n        moved++;\n    }\n    return toTheLeft(this.forward);\n};\n\n/** \n * @param {number} k\n * @return {string}\n */\nTextEditor.prototype.cursorRight = function(k) {\n    let moved = 0;\n    while (moved < k && this.backward.length) {\n        this.forward.push(this.backward.pop());\n        moved++;\n    }\n    return toTheLeft(this.forward);\n};\n\n\nfunction toTheLeft (arr) {\n    let letters = [];\n    for (let i = Math.max(0, arr.length - 10); i < arr.length; i++) {\n        letters.push(arr[i]);\n    }\n    let res = letters.join(\"\");\n    return res; \n}",
        "solution_java": "class TextEditor {\n    StringBuilder res;\n    int pos=0;\n\n    public TextEditor() {\n        res = new StringBuilder();\n    }\n\n    public void addText(String text) {\n        res.insert(pos,text);\n        pos += text.length();\n    }\n\n    public int deleteText(int k) {\n        int tmp = pos;\n        pos -= k;\n        if(pos<0) pos=0;\n        res.delete(pos,tmp);\n        return tmp-pos;\n    }\n\n    public String cursorLeft(int k) {\n        pos-=k;\n        if(pos<0) pos = 0;\n        if(pos<10) return res.substring(0,pos);\n        return res.substring(pos-10,pos);\n    }\n\n    public String cursorRight(int k) {\n        pos+=k;\n        if(pos>res.length()) pos = res.length();\n        if(pos<10) return res.substring(0,pos);\n        return res.substring(pos-10,pos);\n    }\n}",
        "solution_c": "class TextEditor {\n    stack<char> left;\n    stack<char> right;\npublic:\n    TextEditor() {\n\n    }\n\n    void addText(string text) {\n        for(auto &c : text){\n            left.push(c);\n        }\n    }\n\n    int deleteText(int k) {\n        int cnt=0;\n        while(!left.empty() and k>0){\n            left.pop();\n            cnt++;\n            k--;\n        }\n        return cnt;\n    }\n\n    string cursorLeft(int k) {\n        while(!left.empty() and k>0){\n            char c = left.top();left.pop();\n            right.push(c);\n            k--;\n        }\n        // returning the last min(10, len) characters to the left of the cursor\n        return cursorShiftString();\n    }\n\n    string cursorRight(int k) {\n        while(!right.empty() and k>0){\n            char c = right.top();right.pop();\n            left.push(c);\n            k--;\n        }\n        // returning the last min(10, len) characters to the left of the cursor\n        return cursorShiftString();\n    }\n\n    // function to return the last min(10, len) characters to the left of the cursor\n    string cursorShiftString(){\n        string rtn = \"\";\n        int cnt=10;\n        while(!left.empty() and cnt>0){\n            char c = left.top();left.pop();\n            rtn += c;\n            cnt--;\n        }\n        reverse(rtn.begin(),rtn.end());\n        for(int i=0;i<rtn.size();i++){\n            left.push(rtn[i]);\n        }\n        return rtn;\n    }\n};"
    },
    {
        "title": "Maximum Number of Pairs in Array",
        "algo_input": "You are given a 0-indexed integer array nums. In one operation, you may do the following:\n\n\n\tChoose two integers in nums that are equal.\n\tRemove both integers from nums, forming a pair.\n\n\nThe operation is done on nums as many times as possible.\n\nReturn a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,2,1,3,2,2]\nOutput: [3,1]\nExplanation:\nForm a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.\n\n\nExample 2:\n\nInput: nums = [1,1]\nOutput: [1,0]\nExplanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.\n\n\nExample 3:\n\nInput: nums = [0]\nOutput: [0,1]\nExplanation: No pairs can be formed, and there is 1 number leftover in nums.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def numberOfPairs(self, nums: List[int]) -> List[int]:\n        ans = [0] * 2\n        c = Counter(nums)\n        \n        for v in c.values():\n            ans[0] += (v // 2)\n            ans[1] += (v % 2)\n        \n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar numberOfPairs = function(nums) {\n  let pairs = 0;\n  const s = new Set();\n  for (const num of nums) {\n    if (s.has(num)) {\n      pairs += 1;\n      s.delete(num);\n    } else {\n      s.add(num);\n    }\n  }\n  return [pairs, nums.length - pairs * 2];\n};",
        "solution_java": "class Solution {\n    public int[] numberOfPairs(int[] nums) {\n\n        if(nums.length == 1)\n        return new int[]{0,1};\n\n        HashSet<Integer> set = new HashSet<>();\n\n        int pairs=0;\n        for(int i : nums){\n            if(!set.contains(i)){\n               set.add(i); // No pair present\n            }else{\n              set.remove(i); // Pair found\n              pairs++;\n            }\n        }\n\n        return new int[]{pairs,set.size()};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\t//store the frequency of each of the number in the map and\n\t//then return the answer as sum all the values dividing 2 and \n\t//sum all by taking reminder of 2\n    vector<int> numberOfPairs(vector<int>& nums) {\n        unordered_map<int, int> mp;\n        for(auto i: nums) mp[i]++;\n        int c1 = 0, c2 = 0;\n        for(auto m: mp){\n            c1 += m.second/2;\n            c2 += m.second%2;\n        }\n        return {c1, c2};\n    }\n};"
    },
    {
        "title": "Best Time to Buy and Sell Stock with Transaction Fee",
        "algo_input": "You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.\n\nFind the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n\n&nbsp;\nExample 1:\n\nInput: prices = [1,3,2,8,4,9], fee = 2\nOutput: 8\nExplanation: The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n\n\nExample 2:\n\nInput: prices = [1,3,7,5,10,3], fee = 3\nOutput: 6\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 5 * 104\n\t1 &lt;= prices[i] &lt; 5 * 104\n\t0 &lt;= fee &lt; 5 * 104\n\n",
        "solution_py": "class Solution:\n    def maxProfit(self, prices: List[int], fee: int) -> int:\n        n = len(prices)\n        lookup = {}\n        def f(ind, buy, lookup):\n            \n            if ind == n: return 0\n            \n            if (ind, buy) in lookup: return lookup[(ind, buy)]\n            profit = 0\n            if buy:\n                profit = max(-prices[ind] + f(ind+1,0,lookup), f(ind+1, 1,lookup))\n            else:\n                profit = max(prices[ind] + f(ind+1,1,lookup) - fee, f(ind+1, 0,lookup))\n                \n            lookup[(ind,buy)] = profit\n            return lookup[(ind,buy)]\n        \n        return f(0, 1,lookup)",
        "solution_js": "/**\n * @param {number[]} prices\n * @param {number} fee\n * @return {number}\n */\nvar maxProfit = function(prices, fee) {\n    let purchase = -1*prices[0];//If we purchase on 0th day\n    let sell=0;//If we sell on 0th day\n    let prevPurchase;\n    for(let i=1;i<prices.length;i++){\n        prevPurchase = purchase;\n        purchase = Math.max(purchase,sell-prices[i]);//If we purchase on ith day\n        sell = Math.max(sell,prevPurchase+prices[i]-fee);//If we sell on ith day\n    }\n    return sell;//If must return the best price whenever we sold stock because then only we can be at max profit.\n};",
        "solution_java": "class Solution {\n    public int maxProfit(int[] prices, int fee) {\n        int[][] dp = new int[prices.length][2];\n        for (int[] a : dp) {\n            a[0] = -1;\n            a[1] = -1;\n        }\n        return profit(prices, fee, 0, 1, dp);\n    }\n    public int profit(int[] prices, int fee, int i, int buy, int[][] dp) {\n        if (i == prices.length) {\n            return 0;\n        }\n        if (dp[i][buy] != -1) {\n            return dp[i][buy];\n        }\n        int maxProfit = 0;\n        if (buy == 1) {\n            int yesBuy = profit(prices, fee, i + 1, 0, dp) - prices[i];\n            int noBuy = profit(prices, fee, i + 1, 1, dp);\n            maxProfit = Math.max(yesBuy, noBuy);\n        } else {\n            int yesSell = prices[i] - fee + profit(prices, fee, i + 1, 1, dp);\n            int noSell = profit(prices, fee, i + 1, 0, dp);\n            maxProfit = Math.max(yesSell, noSell);\n        }\n        return dp[i][buy] = maxProfit;\n    }\n}",
        "solution_c": " class Solution {\npublic:\n    int ans=0;\n    int f(vector<int>&prices,int i,int buy,vector<vector<int>>&dp,int fee){\n        if(i==prices.size())return 0;\n        if(dp[i][buy]!=-1)return dp[i][buy];\n        int take=0;\n        if(buy){\n            take=max(-prices[i]+f(prices,i+1,0,dp,fee),f(prices,i+1,1,dp,fee));\n        }\n        else{\n            take=max(prices[i]+f(prices,i+1,1,dp,fee)-fee,f(prices,i+1,0,dp,fee));\n        }return dp[i][buy]=take;\n    }\n    int maxProfit(vector<int>& prices, int fee) {\n         vector<vector<int>>dp(prices.size(),vector<int>(2,-1));\n        return f(prices,0,1,dp,fee);\n    }\n};"
    },
    {
        "title": "Goat Latin",
        "algo_input": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.\n\nWe would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:\n\n\n\tIf a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append \"ma\" to the end of the word.\n\n\t\n\t\tFor example, the word \"apple\" becomes \"applema\".\n\t\n\t\n\tIf a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\".\n\t\n\t\tFor example, the word \"goat\" becomes \"oatgma\".\n\t\n\t\n\tAdd one letter 'a' to the end of each word per its word index in the sentence, starting with 1.\n\t\n\t\tFor example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.\n\t\n\t\n\n\nReturn the final sentence representing the conversion from sentence to Goat Latin.\n\n&nbsp;\nExample 1:\nInput: sentence = \"I speak Goat Latin\"\nOutput: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\nExample 2:\nInput: sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentence.length &lt;= 150\n\tsentence consists of English letters and spaces.\n\tsentence has no leading or trailing spaces.\n\tAll the words in sentence are separated by a single space.\n\n",
        "solution_py": "class Solution:\n    def toGoatLatin(self, sentence: str) -> str:\n        wordList, result, index = sentence.split(' '), \"\", 1\n        for word in wordList:\n            if index > 1:\n                result += \" \"\n            firstLetter = word[0]\n            if firstLetter in 'aeiouAEIOU':\n                result += word + \"ma\"\n            else:\n                result += word[1:] + firstLetter + \"ma\"\n            for i in range(index):\n                result += 'a'\n            index += 1\n        return result",
        "solution_js": "/**\n * @param {string} S\n * @return {string}\n */\nvar toGoatLatin = function(S) {\n    let re = /[aeiou]/gi\n    let word = S.split(' ')\n    let add = 0\n    let arr = []\n    \n    for(let i= 0; i < word.length; i++) {\n        if(!word[i].substring(0,1).match(re)) {\n            arr = word[i].split('')\n            let letter = arr.shift()\n            arr.push(letter)\n            word[i] = arr.join('')\n        }\n        \n        // have to append 'ma' regardless if it starts with a vowel\n        word[i] += 'ma'\n        \n        // append 'a' number of times as the index + 1\n        add = i+1\n        while(add >0) {\n            word[i] += 'a'\n            add--\n        }\n    }\n    \n    return word.join(' ')\n};",
        "solution_java": "class Solution {\n    public String toGoatLatin(String sentence) {\n        StringBuffer sb = new StringBuffer();\n        StringBuffer temp = new StringBuffer(\"a\"); // temporary stringbuffer\n\n        for(String str : sentence.split(\" \")) {\n            if(beginsWithConsonant(str)) {\n                sb.append(str.substring(1)); // removing the first letter\n                sb.append(str.charAt(0)); // appending it to the end\n            } else {\n                sb.append(str);\n            }\n\n            sb.append(\"ma\"); // appending \"ma\" to the end of the word (common operation)\n            sb.append(temp); // adding one letter 'a' to the end of each word\n\n            // the first word gets \"a\" added to the end,\n            // the second word gets \"aa\" added to the end,\n            // and so on.\n            temp.append(\"a\"); // increasing the a's for every word\n            sb.append(\" \"); // to put space between words\n        }\n\n        return sb.toString().trim(); // using trim() to remove the one extra space from the end of string.\n    }\n\n    public boolean beginsWithConsonant(String str) {\n        return \"aeiou\".indexOf(str.toLowerCase().charAt(0)) == -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string toGoatLatin(string sentence) {\n        sentence += ' ';\n        vector<string> Words;\n        string TEMP, SOL, A = \"a\";\n        for (int i = 0; i < sentence.size(); ++i)\n        {\n            if (sentence[i] == ' ')\n            {\n                Words.push_back(TEMP);\n                TEMP = \"\";\n            }\n            else\n                TEMP += sentence[i];\n        }\n        for (string V : Words)\n        {\n            char TMP = tolower(V[0]);\n            if (TMP == 'a' || TMP == 'e' || TMP == 'i' || TMP == 'o' || TMP == 'u')\n                V += \"ma\";\n            else\n            {\n                TMP = V[0];\n                V.erase(0, 1);\n                V += TMP;\n                V += \"ma\";\n            }\n            V += A;\n            A += 'a';\n            SOL += V + ' ';\n        }\n        SOL.erase(SOL.size() - 1, 1);\n        return SOL;\n    }\n};"
    },
    {
        "title": "Minimum Absolute Difference in BST",
        "algo_input": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 104].\n\t0 &lt;= Node.val &lt;= 105\n\n\n&nbsp;\nNote: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/\n",
        "solution_py": "class Solution:\n    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n        cur, stack, minDiff, prev = root, [], 10**5, -10**5\n        \n        while stack or cur:\n            while cur:\n                stack.append(cur)\n                cur = cur.left\n            node = stack.pop()\n            minDiff = min(minDiff, node.val - prev)\n            prev = node.val\n            cur = node.right\n        \n        return minDiff",
        "solution_js": "var getMinimumDifference = function(root) {\n    let order = inOrder(root, []);\n    let diff = Math.abs(order[1] - order[0]);\n    for(let i=0;i<order.length;i++) {\n        for(let j=i+1;j<order.length;j++) {\n            if(Math.abs(order[i] - order[j]) < diff) diff = Math.abs(order[i] - order[j])\n        }\n    }\n    return diff;\n};\n\nconst inOrder = (root, order) => {\n    if(!root) return null;\n    inOrder(root.left, order);\n    order.push(root.val);\n    inOrder(root.right, order);\n    return order;\n}",
        "solution_java": "class Solution {\n    public int getMinimumDifference(TreeNode root) {\n      Queue<Integer> queue=new PriorityQueue<>();\n      Queue<TreeNode> nodesQueue=new LinkedList<>();\n      int min=Integer.MAX_VALUE;\n      if(root==null)\n        return 0;\n      nodesQueue.add(root);\n      while(!nodesQueue.isEmpty())\n      {\n        TreeNode node=nodesQueue.poll();\n        queue.add(node.val);\n        if(node.left!=null)\n        { \n          nodesQueue.add(node.left);\n        }\n        if(node.right!=null)\n        { \n          nodesQueue.add(node.right);\n        }\n      }\n      int prev=queue.poll();\n      while(!queue.isEmpty())\n      {\n        int current=queue.poll();\n        int absValue=Math.abs(current-prev);\n        prev=current;\n        min=Math.min(min,absValue);\n        \n      } \n      return min;\n    }\n}",
        "solution_c": "class Solution {\n    TreeNode* pre = nullptr;\n    int minimum = std::numeric_limits<int>:: max();\npublic:\n    void inorder(TreeNode* node) {\n        if (!node) return;\n        inorder(node->left);\n        if(pre) {\n            minimum = min(node->val - pre->val, minimum);\n        }\n        pre = node;\n        inorder(node->right);\n    }\n    int getMinimumDifference(TreeNode* root) {\n        inorder(root);\n        return minimum;\n    }\n\n};"
    },
    {
        "title": "Serialize and Deserialize BST",
        "algo_input": "Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.\n\nThe encoded string should be as compact as possible.\n\n&nbsp;\nExample 1:\nInput: root = [2,1,3]\nOutput: [2,1,3]\nExample 2:\nInput: root = []\nOutput: []\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t0 &lt;= Node.val &lt;= 104\n\tThe input tree is guaranteed to be a binary search tree.\n\n",
        "solution_py": "class Codec:\n    def serialize(self, root: Optional[TreeNode]) -> str:\n        \"\"\"Encodes a tree to a single string.\n        \"\"\"\n        if not root:\n            return \"\"\n        res = []\n        def dfs(node):\n            res.append(str(node.val))\n            if node.left:\n                dfs(node.left)\n            if node.right:\n                dfs(node.right)\n        dfs(root)\n        return ','.join(res)\n    def deserialize(self, data: str) -> Optional[TreeNode]:\n        \"\"\"Decodes your encoded data to tree.\n        \"\"\"\n        if len(data) == 0:\n            return []\n        splitdata = data.split(\",\") \n        preorder = []\n        for item in splitdata:\n            preorder.append(int(item))          \n        inorder = sorted(preorder)\n        hash_map = {}  \n        for i in range(len(inorder)):\n            hash_map[inorder[i]] = i\n        def helper(preorder, pstart, pend, inorder, istart, iend):\n            if pstart > pend:\n                return None\n            elif pstart == pend:\n                return TreeNode(preorder[pstart])\n\n            root = TreeNode(preorder[pstart])\n            \n            rootindex = hash_map[preorder[pstart]]\n            \n            numleft = rootindex - istart\n            \n            root.left = helper(preorder, pstart+1, pstart + numleft, inorder, istart,rootindex-1 )\n            root.right = helper(preorder, pstart + numleft +1, pend, inorder, rootindex +1, iend)\n            \n            return root\n            \n        return (helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1))",
        "solution_js": ";/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n *     this.val = val;\n *     this.left = this.right = null;\n * }\n */\n\n/**\n * Encodes a tree to a single string.\n *\n * @param {TreeNode} root\n * @return {string}\n */\nvar serialize = function(root) {\n    // Using Preorder traversal to create a string of BST\n    // Preorder works in following way\n    // root -> left -> right\n    let preorder = [];\n    \n    function dfs(node) {\n        if (node === null) return;\n        // Get root value\n        preorder.push(node.val);\n\n        // Get All the Left values\n        dfs(node.left);\n\n        // Get all the right values\n        dfs(node.right);\n    }\n\n    // call it with root\n    dfs(root)\n\n    // Turn into string and return it\n    return preorder.join(',')\n};\n\n/**\n * Decodes your encoded data to tree.\n *\n * @param {string} data\n * @return {TreeNode}\n */\nvar deserialize = function(data) {\n    if (data === \"\") return null;\n\n    // Get numbers array from a string\n    const preorder = data.split(',').map(Number);\n\n    // using -Infinity and +Infinity as placeholder check\n    function recur(lower = -Infinity, upper = Infinity) {\n        // This condition useful for when we are filling left side of tree it'll avoid all the values greater then then its upper value by putting null init.\n        if (preorder[0] < lower || preorder[0] > upper) return null;\n\n        // If preorder become empty\n        if (preorder.length === 0) return null;\n\n        // Create a root node [shift method will change the original array]\n        const root = new TreeNode(preorder.shift());\n\n        // Here for left side of tree, we are using current root node's value as 'upper bound' (so higher values ignored).\n        root.left = recur(lower, root.val);\n\n        // Same as above for right side we are using root node's values as 'lower bound' (so lower values ignored);\n        root.right = recur(root.val, upper);\n\n        return root;\n    }\n\n    // Final root will be out BST\n    return recur();\n};\n\n/**\n * Your functions will be called as such:\n * deserialize(serialize(root));\n */",
        "solution_java": "public class Codec {\n\n    // Encodes a tree to a single string.\n    public String serialize(TreeNode root) {\n        StringBuilder string = new StringBuilder();\n        traverse(root, string);\n        return string.toString();\n    }\n\n    private void traverse(TreeNode root, StringBuilder string){\n        if(root == null) return;\n        string.append(root.val).append(\",\");\n        traverse(root.left, string);\n        traverse(root.right, string);\n    }\n\n    // Decodes your encoded data to tree.\n    public TreeNode deserialize(String data) {\n        if(data.isEmpty()) return null;\n\n        String[] dataArr = data.split(\",\");\n\n        TreeNode root = new TreeNode(Integer.parseInt(dataArr[0]));\n\n        for(int i = 1; i < dataArr.length; i++)\n            insert(Integer.parseInt(dataArr[i]), root);\n\n        return root;\n    }\n\n    private void insert(int digit, TreeNode root){\n\n        if(digit > root.val){\n            if(root.right != null)\n                insert(digit, root.right);\n            else\n                root.right = new TreeNode(digit);\n        } else {\n            if(root.left != null)\n                insert(digit, root.left);\n            else\n                root.left = new TreeNode(digit);\n        }\n\n    }\n}",
        "solution_c": "class Codec\n{\n    public:\n\n    string pre(TreeNode * root)\n    {\n        if(root==NULL)\n            return \"\";\n\n        int temp = root->val;\n        string tempz = to_string(temp);\n\n        string l = pre(root->left);\n        string r = pre(root->right);\n\n        return (tempz + \",\" + l + \",\" + r);\n    }\n\n    vector<int> parse_string(string data)\n    {\n        vector<int> ans;\n        string temp = \"\";\n        int n=data.size();\n\n        for(int i=0;i<n; ++i)\n        {\n            if(data[i]==',')\n            {\n                if(temp.size()==0)\n                    continue;\n                else\n                {\n                    int val = stoi(temp);\n                    ans.push_back(val);\n                    temp=\"\";\n                }\n            }\n            else\n                temp += data[i];\n        }\n        return ans;\n    }\n\n    TreeNode * make_tree(vector<int>& preorder, int min_val, int max_val, int& preorder_idx, int n)\n    {\n        if(preorder_idx == n)\n            return NULL;\n        int val = preorder[preorder_idx];\n        if(min_val <= val and val <= max_val)\n        {\n            TreeNode * curr = new TreeNode(val);\n            preorder_idx++;\n            curr->left = make_tree(preorder, min_val, val-1, preorder_idx, n);\n            curr->right = make_tree(preorder, val+1, max_val, preorder_idx, n);\n            return curr;\n        }\n        else\n            return NULL;\n    }\n\n    string serialize(TreeNode* root)\n    {\n        string traversal = pre(root);\n        //cout<<traversal<<endl;\n        return traversal;\n    }\n\n    TreeNode* deserialize(string data)\n    {\n        if(data.size()==0)\n            return NULL;\n        vector<int> traversal = parse_string(data);\n\n        // for(auto x:traversal)\n        // cout<<x<<\" \";\n\n        int preorder_idx = 0;\n        TreeNode * root = make_tree(traversal, INT_MIN, INT_MAX, preorder_idx, traversal.size());\n\n        return root;\n    }\n};"
    },
    {
        "title": "Find Servers That Handled Most Number of Requests",
        "algo_input": "You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:\n\n\n\tThe ith (0-indexed) request arrives.\n\tIf all servers are busy, the request is dropped (not handled at all).\n\tIf the (i % k)th server is available, assign the request to that server.\n\tOtherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.\n\n\nYou are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\n\nReturn a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n\n&nbsp;\nExample 1:\n\nInput: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \nOutput: [1] \nExplanation: \nAll of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n\n\nExample 2:\n\nInput: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput: [0]\nExplanation: \nThe first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n\n\nExample 3:\n\nInput: k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput: [0,1,2]\nExplanation: Each server handles a single request, so they are all considered the busiest.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 105\n\t1 &lt;= arrival.length, load.length &lt;= 105\n\tarrival.length == load.length\n\t1 &lt;= arrival[i], load[i] &lt;= 109\n\tarrival is strictly increasing.\n\n",
        "solution_py": "class Solution:\n    def busiestServers(self, k: int, A: List[int], B: List[int]) -> List[int]:\n        available = list(range(k)) # already a min-heap\n        busy = [] \n        res = [0] * k\n        for i, a in enumerate(A):\n            while busy and busy[0][0] <= a: # these are done, put them back as available\n                _, x = heapq.heappop(busy)\n                heapq.heappush(available, i + (x-i)%k) # invariant: min(available) is at least i, at most i+k-1\n            if available: \n                j = heapq.heappop(available) % k\n                heapq.heappush(busy, (a+B[i],j))\n                res[j] += 1\n        a = max(res)\n        return [i for i in range(k) if res[i] == a]",
        "solution_js": "var busiestServers = function(k, arrival, load) {\n    let loadMap = {};\n    let pq = new MinPriorityQueue({ compare: (a,b) => a[1] - b[1] });\n    let availableServers = new Set(new Array(k).fill(0).map((_, index) => index));\n\n    for (let i = 0; i < arrival.length; i++) {\n        // calc end time\n        let end = arrival[i] + load[i];\n        \n        // bring server back\n        while (pq.front()?.[1] <= arrival[i]) {\n            const [server] = pq.dequeue();\n            availableServers.add(server);\n        }\n        \n        let server = i % k;\n        // drop if no available server\n        if (availableServers.size === 0) continue;\n        \n        // find the next avaiable sever\n        while (!availableServers.has(server)) {\n            server++;\n            if (server === k + 1) {\n                server = 0;\n            }\n        }\n        \n        // record the load\n        if (!loadMap[server]) {\n            loadMap[server] = 0;\n        }\n        \n        loadMap[server]++;\n        \n        availableServers.delete(server);\n        pq.enqueue([server, end]);\n    }\n    \n    let res = [];\n    let sorted = Object.entries(loadMap).sort((a,b) => b[1] - a[1]);\n    let max = sorted[0][1];\n    let i = 0;\n    while (sorted[i]?.[1] === max) {\n        res.push(+sorted[i++][0]);\n    }\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    public List<Integer> busiestServers(int k, int[] arrival, int[] load) {\n\n        // use a tree to track available servers\n        TreeSet<Integer> availableServerIdxs = new TreeSet<Integer>();\n        for (int num = 0; num < k; num++) {\n            availableServerIdxs.add(num);\n        }\n        // use a PQ to maintain the availability based on curTime + loadTime and the server index = idx%k\n        Queue<int[]> runningServers = new PriorityQueue<>((a, b)->(a[0] - b[0]));\n\n        int[] serverHandledReqCount = new int[k];\n\n        for (int idx = 0; idx < arrival.length; idx++) {\n            int newTaskCompletionTime = arrival[idx];\n\n          // peek if the server's work time is less than or equal to the next task completion time, if it is poll those servers from the running servers queue and add the index of that server to the availableServerIdxs treeSet\n            while (!runningServers.isEmpty() && runningServers.peek()[0] <= newTaskCompletionTime) {\n                int freedServer = runningServers.poll()[1];\n                availableServerIdxs.add(freedServer);\n            }\n\n            if (availableServerIdxs.size() == 0) continue; // all busy\n\n            // to always get the last freed server\n            Integer serverIdx = availableServerIdxs.ceiling(idx % k);\n\n            if (serverIdx == null) {\n                serverIdx = availableServerIdxs.first();\n            }\n\n            serverHandledReqCount[serverIdx]++;\n            availableServerIdxs.remove(serverIdx);\n\n            runningServers.offer(new int[] {newTaskCompletionTime + load[idx], serverIdx});\n        }\n\n        int max = Arrays.stream(serverHandledReqCount).max().getAsInt();\n        return IntStream.range(0, k).filter(i -> serverHandledReqCount[i] == max).boxed().collect(Collectors.toList());\n\n        //return findMaxesInCounter(counter);\n    }\n\n    /*\n    private List<Integer> findMaxesInCounter(int[] counter) {\n        int max = 0;\n        for (int i = 0; i < counter.length; i++) {\n            max = Math.max(max, counter[i]);\n        }\n        List<Integer> result = new ArrayList<>();\n        for (int i = 0; i < counter.length; i++) {\n            if (counter[i] == max) {\n                result.add(i);\n            }\n        }\n        return result;\n    }\n    */\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {\n        int n = (int)arrival.size();\n        \n        set<int> freeServers;\n        for (int i = 0; i < k; i++) freeServers.insert(i);\n        \n        vector<int> serverTaskCount(k, 0);\n        \n        set<pair<int, int>> workingServers;     // [end time, server index]\n        for (int i = 0; i < n; i++) {\n            int startTime = arrival[i];\n            \n            while (!workingServers.empty() && workingServers.begin()->first <= startTime) {\n                auto s = *workingServers.begin();\n                workingServers.erase(workingServers.begin());\n                freeServers.insert(s.second);\n            }\n            \n            if (freeServers.empty()) continue;\n            \n            int serverIndex = -1;\n            auto it = freeServers.lower_bound(i % k);\n            if (it == freeServers.end()) {\n                serverIndex = *freeServers.begin();\n                freeServers.erase(freeServers.begin());\n            } else {\n                serverIndex = *it;\n                freeServers.erase(it);\n            }\n            \n            workingServers.insert({startTime + load[i], serverIndex});\n            \n            serverTaskCount[serverIndex]++;\n            //printf(\"Task %d (%d, %d) assigned to server %d\\n\", i, startTime, load[i], serverIndex);\n        }\n        // for (auto x : serverTaskCount) cout << x << \" \";\n        // cout << endl;\n        \n        vector<int> ret;\n        int maxVal = *max_element(serverTaskCount.begin(), serverTaskCount.end());\n        for (int i = 0; i < k; i++) \n            if (maxVal == serverTaskCount[i]) ret.push_back(i);\n        \n        return ret;\n    }\n};"
    },
    {
        "title": "Array With Elements Not Equal to Average of Neighbors",
        "algo_input": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.\n\nMore formally, the rearranged array should have the property such that for every i in the range 1 &lt;= i &lt; nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].\n\nReturn any rearrangement of nums that meets the requirements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n\n\nExample 2:\n\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def rearrangeArray(self, nums: List[int]) -> List[int]:\n        for i in range(1, len(nums) -1):\n            pre = nums[i-1]\n            current = nums[i]\n            next = nums[i+1]\n            \n            # If block will run when we meet 1 2 3 or 6 4 2\n            if (pre < current < next) or (pre > current > next):\n                # Swap next and current\n                # For example: \n                # 1 2 3 -> 1 3 2\n                # 6 4 2 -> 6 2 4\n                nums[i+1], nums[i] = nums[i], nums[i+1]\n                \n        return nums",
        "solution_js": "var rearrangeArray = function(nums) {\n    let arr=[], res=[]\n    for(let q of nums) arr[q]= 1\n\n    let l=0, r=arr.length-1\n    while(l<=r){\n        while(!arr[l])l++\n        while(!arr[r])r--\n        if(l<=r)res.push(l++)\n        if(l<=r)res.push(r--)\n    }\n    return res\n};",
        "solution_java": "class Solution {\n    public int[] rearrangeArray(int[] nums) {\n       Arrays.sort(nums);\n       // sort in wave format\n        for(int i = 0;i<nums.length-1;i+=2){\n            int temp = nums[i];\n            nums[i] = nums[i+1];\n            nums[i+1] = temp;\n        }\n        return nums;\n    }\n}",
        "solution_c": "//Approach-1 (Using sorting O(nlogn))\n/*\n    If you make sure that\n    nums[i-1] < nums[i] > nums[i+1]\n    You are good to go.\n\n    So, just sort the input and choose wisely to satisfy above condition.\n\n    Example :\n    [6,2,0,9,7]\n    sort it : [0, 2, 6, 7, 9]\n\n    result : [0, _, 2, _, 6] - 1st loop (fill alternaltely)\n    result : [0, 7, 2, 9, 6] - 2nd loop (fill next larger numbers from nums to result in spaces left)\n\n*/\n\nclass Solution {\npublic:\n    vector<int> rearrangeArray(vector<int>& nums) {\n        int n = nums.size();\n        sort(begin(nums), end(nums));\n\n        vector<int> result(n);\n        int j = 0;\n        int i = 0;\n        for(; i < n && j < n; i++, j += 2) //alternately fill so that you leave one space in between for large number\n            result[j] = nums[i];\n\n        j = 1;\n        for(; i < n && j < n; i++, j += 2) //filter the large number in spaces between that we left above\n            result[j] = nums[i];\n\n        return result;\n    }\n};"
    },
    {
        "title": "Maximum Consecutive Floors Without Special Floors",
        "algo_input": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.\n\nYou are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.\n\nReturn the maximum number of consecutive floors without a special floor.\n\n&nbsp;\nExample 1:\n\nInput: bottom = 2, top = 9, special = [4,6]\nOutput: 3\nExplanation: The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.\n\n\nExample 2:\n\nInput: bottom = 6, top = 8, special = [7,6,8]\nOutput: 0\nExplanation: Every floor rented is a special floor, so we return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= special.length &lt;= 105\n\t1 &lt;= bottom &lt;= special[i] &lt;= top &lt;= 109\n\tAll the values of special are unique.\n\n",
        "solution_py": "class Solution:\n    def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n        special.sort()\n        special.insert(0, bottom - 1)\n        special.append(top + 1)\n        \n        ans = 0\n        for i in range(len(special)-1):\n            ans = max(ans, special[i+1] - special[i] - 1)\n        return ans",
        "solution_js": "/**\n * @param {number} bottom\n * @param {number} top\n * @param {number[]} special\n * @return {number}\n */\nvar maxConsecutive = function(bottom, top, special) {\n    special.push(top+1);\n    special.push(bottom-1);\n    special.sort((a, b) => a - b);\n    let specialMax = 0;\n    for (let i = 1; i < special.length; i++){\n        specialMax = Math.max(specialMax, special[i] - special[i-1] - 1)\n    }\n    return specialMax;\n};",
        "solution_java": "class Solution {\n    public int maxConsecutive(int bottom, int top, int[] special) {\n        int max = Integer.MIN_VALUE;\n\n        Arrays.sort(special);\n\n        // from bottom to the first special floor\n        max = Math.max(max, special[0] - bottom);\n\n        // middle floors\n        for(int i = 1; i < special.length; i++) {\n            max = Math.max(max, special[i] - special[i - 1] - 1);\n        }\n\n        // from last special floor to the top\n        max = Math.max(max, top - special[special.length - 1]);\n\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxConsecutive(int bottom, int top, vector<int>& special) {\n\n        int res(0), n(size(special));\n        sort(begin(special), end(special));\n\n        for (int i=1; i<n; i++) {\n            res = max(res, special[i]-special[i-1]-1);\n        }\n\n        return max({res, special[0]-bottom, top-special[n-1]});\n    }\n};"
    },
    {
        "title": "Detect Capital",
        "algo_input": "We define the usage of capitals in a word to be right when one of the following cases holds:\n\n\n\tAll letters in this word are capitals, like \"USA\".\n\tAll letters in this word are not capitals, like \"leetcode\".\n\tOnly the first letter in this word is capital, like \"Google\".\n\n\nGiven a string word, return true if the usage of capitals in it is right.\n\n&nbsp;\nExample 1:\nInput: word = \"USA\"\nOutput: true\nExample 2:\nInput: word = \"FlaG\"\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 100\n\tword consists of lowercase and uppercase English letters.\n\n",
        "solution_py": "class Solution:\n    def detectCapitalUse(self, word: str) -> bool:\n        l=len(word)\n        if l==1:\n            return True\n        if word[0]==word[0].lower() and word[1]==word[1].upper():\n            return False\n            \n        u=False\n        if word[0]==word[0].upper():\n            if word[1]==word[1].upper():\n                u=True\n                \n        for i in word[2:]:\n            if i==i.upper() and u==False:\n                return False\n            elif i==i.lower() and u==True:\n                return False\n        return True",
        "solution_js": "var detectCapitalUse = function(word) {\n      if((word.charAt(0)==word.charAt(0).toUpperCase() && word.slice(1)==word.slice(1).toLowerCase()) || (word == word.toUpperCase() \n   || word == word.toLowerCase()))\n   {\n      return true\n   }\n    else{\n      return false\n  }\n};",
        "solution_java": "class Solution {\n    public boolean detectCapitalUse(String word) {\n        int count = 0;\n        for(int i=0; i < word.length(); i++){\n            if('A' <= word.charAt(i) && word.charAt(i) <= 'Z')\n                count++;\n        }\n        if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt(0) && word.charAt(0) <= 'Z')))\n            return true;\n        else\n            return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool detectCapitalUse(string word) {\n        int n = word.size();\n\n        //if the first letter of the string is lower-case\n        if(islower(word[0])){\n            int c = 0;\n            for(int i=0; i<n; i++){\n                if(islower(word[i])){\n                    c++;\n                }\n            }\n\n            //total lower-case count must be equal to the size of the string\n            if(c == n){\n                return true;\n            }\n            return false;\n        }\n\n        //if the first letter of the string is upper-case.\n        else{\n            int c = 0;\n            for(int i=0; i<n; i++){\n                if(isupper(word[i])){\n                    c++;\n                }\n            }\n\n            //count of total upper-case letters must be equal to 1 or to the size of the string.\n            if(c == 1 or c == n){\n                return true;\n            }\n\n            //in all other cases, return false.\n            return false;\n        }\n    }\n};"
    },
    {
        "title": "Plates Between Candles",
        "algo_input": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.\n\nYou are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.\n\n\n\tFor example, s = \"||**||**|*\", and a query [3, 8] denotes the substring \"*||**|\". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.\n\n\nReturn an integer array answer where answer[i] is the answer to the ith query.\n\n&nbsp;\nExample 1:\n\nInput: s = \"**|**|***|\", queries = [[2,5],[5,9]]\nOutput: [2,3]\nExplanation:\n- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.\n\n\nExample 2:\n\nInput: s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\nOutput: [9,0,0,0,0]\nExplanation:\n- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 105\n\ts consists of '*' and '|' characters.\n\t1 &lt;= queries.length &lt;= 105\n\tqueries[i].length == 2\n\t0 &lt;= lefti &lt;= righti &lt; s.length\n\n",
        "solution_py": "class Solution:\n    def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:\n        psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1)\n        res = []\n        for i, ch in enumerate(s):\n            psum[i + 1] = psum[i] + (ch == '|')\n            prev[i + 1] = i if ch == '|' else prev[i]\n        for i, ch in reversed(list(enumerate(s))):\n            next[i] = i if ch == '|' else next[i + 1]\n        for q in queries:\n            l, r = next[q[0]], prev[q[1] + 1]\n            res.append(r - l - (psum[r] - psum[l]) if l < r else 0)\n        return res",
        "solution_js": "// time O(N + M) Space O(N) N = s.length M = query.length\nvar platesBetweenCandles = function(s, queries) {\n    let platPreFixSum = [...Array(s.length + 1)];\n    let leftViewCandle = [...Array(s.length + 1)];\n    let rightViewCandle = [...Array(s.length + 1)];\n\n    platPreFixSum[0] = 0;\n    leftViewCandle[0] = -1;\n    rightViewCandle[s.length] = -1;\n\n    for(let i = 1; i <= s.length; i++){\n        platPreFixSum[i] = s[i-1] == '*' ? platPreFixSum[i - 1] + 1 : platPreFixSum[i - 1];\n        leftViewCandle[i] = s[i - 1] == '|' ? i - 1 : leftViewCandle[i - 1];\n        rightViewCandle[s.length - i] = s[s.length - i] == '|' ? s.length - i : rightViewCandle[s.length - i + 1];\n    }\n\n    let result = [];\n\n    queries.forEach(([left, right]) => {\n        if(rightViewCandle[left] >= 0 && leftViewCandle[right + 1] >= 0 &&\n           rightViewCandle[left] < leftViewCandle[right + 1]) {\n            result.push(platPreFixSum[leftViewCandle[right + 1]] - platPreFixSum[rightViewCandle[left]]);\n        } else {\n            result.push(0);\n        }\n    });\n\n    return result;\n\n};",
        "solution_java": "class Solution {\n    // O(sLen + queries.length) time, O(sLen) space\n    public int[] platesBetweenCandles(String s, int[][] queries) {\n        int sLen = s.length();\n        // cumulative number of plates from the left\n        int[] numberOfPlates = new int[sLen+1];\n        for (int i=0; i<sLen; i++) {\n            numberOfPlates[i+1] = numberOfPlates[i] + (s.charAt(i) == '*' ? 1 : 0);\n        }\n        // closest candle to the left\n        int[] candleToTheLeft = new int[sLen];\n        int cand = -1;\n        for (int i=0; i<sLen; i++) {\n            if (s.charAt(i) == '|') {\n                cand = i;\n            }\n            candleToTheLeft[i] = cand;\n        }\n        // closest candle to the right\n        int[] candleToTheRight = new int[sLen];\n        cand = -1;\n        for (int i=sLen-1; i>=0; i--) {\n            if (s.charAt(i) == '|') {\n                cand = i;\n            }\n            candleToTheRight[i] = cand;\n        }\n        // for each query - count the number of plates between closest candles\n        int[] res = new int[queries.length];\n        for (int i=0; i<queries.length; i++) {\n            int left = candleToTheRight[queries[i][0]];\n            int right = candleToTheLeft[queries[i][1]];\n            if (left == -1 || right == -1 || left >= right) {\n                res[i] = 0;\n            } else {\n                res[i] = numberOfPlates[right+1] - numberOfPlates[left];\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> platesBetweenCandles(string s, vector<vector<int>>& queries) {\n        vector<int> candlesIndex;\n        \n        for(int i=0;i<s.length();i++){\n            if(s[i] == '|')\n                candlesIndex.push_back(i);\n        }\n        \n        vector<int> ans;\n        for(auto q : queries){\n            int firstCandleIndex = lower_bound(candlesIndex.begin() , candlesIndex.end() , q[0]) - candlesIndex.begin();\n            int lastCandleIndex = upper_bound(candlesIndex.begin() , candlesIndex.end() , q[1]) - candlesIndex.begin() - 1;\n            \n            if(lastCandleIndex <= firstCandleIndex){\n                ans.push_back(0);\n                continue;\n            }\n                \n            \n            int tempAns = candlesIndex[lastCandleIndex] - candlesIndex[firstCandleIndex] - (lastCandleIndex - firstCandleIndex);\n            \n            ans.push_back(tempAns);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Replace Words",
        "algo_input": "In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\".\n\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.\n\nReturn the sentence after the replacement.\n\n&nbsp;\nExample 1:\n\nInput: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n\n\nExample 2:\n\nInput: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput: \"a a b c\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= dictionary.length &lt;= 1000\n\t1 &lt;= dictionary[i].length &lt;= 100\n\tdictionary[i] consists of only lower-case letters.\n\t1 &lt;= sentence.length &lt;= 106\n\tsentence consists of only lower-case letters and spaces.\n\tThe number of words in sentence is in the range [1, 1000]\n\tThe length of each word in sentence is in the range [1, 1000]\n\tEvery two consecutive words in sentence will be separated by exactly one space.\n\tsentence does not have leading or trailing spaces.\n\n",
        "solution_py": "class Solution {\npublic:\n    class trii{\n        public:\n        char data;\n        trii* dict[26];\n        bool isTerminal;\n        \n        trii(){\n            \n        }\n        \n        trii(char d){\n           data=d;\n            for(int i=0;i<26;i++){\n                dict[i]=NULL;\n            }\n            isTerminal=false;\n        }\n    };\n    \n    class tree{\n        public:\n        trii* root;\n        tree(){\n            root=new trii('\\0');\n        }\n        \n        void insert(string str,trii* node){\n            if(str.size()==0){\n                node->isTerminal=true;\n                return;\n            }\n            int index=str[0]-'a';\n            if(node->dict[index]==NULL ){\n                node->dict[index]=new trii(str[0]);\n            }\n            insert(str.substr(1),node->dict[index]);\n        }\n        \n        string find(string str,trii* node,string pre){\n            if( node->isTerminal==true ){\n                return pre; \n            }            \n            int index=str[0]-'a';\n            if(str.size()==0 || node->dict[index]==NULL){\n                return \"\\0\";\n            }\n           return find(str.substr(1),node->dict[index],pre+str[0]);\n        }\n        \n        string replaceWith(string word ,trii* node){\n            string temp=find(word,node,\"\");\n            if(temp!=\"\\0\"){\n                word=temp;\n            }\n            return word;\n        }\n    };\n    \n    string replaceWords(vector<string>& dictionary, string sentence) {\n       tree* t=new tree();\n        for(int i=0;i<dictionary.size();i++){\n            t->insert(dictionary[i],t->root);\n        }\n        string ans=sentence;\n        sentence=\"\";\n        for(int i=0;i<ans.size();i++){\n            string word=\"\";\n            while(i<ans.size()&&ans[i]!=' '){\n                word+=ans[i];\n                i++;\n            }\n            \n            sentence+=t->replaceWith(word,t->root)+\" \";\n        }\n        sentence.pop_back();\n        return sentence;\n    }\n};",
        "solution_js": "class Solution {\npublic:\n    class trii{\n        public:\n        char data;\n        trii* dict[26];\n        bool isTerminal;\n        \n        trii(){\n            \n        }\n        \n        trii(char d){\n           data=d;\n            for(int i=0;i<26;i++){\n                dict[i]=NULL;\n            }\n            isTerminal=false;\n        }\n    };\n    \n    class tree{\n        public:\n        trii* root;\n        tree(){\n            root=new trii('\\0');\n        }\n        \n        void insert(string str,trii* node){\n            if(str.size()==0){\n                node->isTerminal=true;\n                return;\n            }\n            int index=str[0]-'a';\n            if(node->dict[index]==NULL ){\n                node->dict[index]=new trii(str[0]);\n            }\n            insert(str.substr(1),node->dict[index]);\n        }\n        \n        string find(string str,trii* node,string pre){\n            if( node->isTerminal==true ){\n                return pre; \n            }            \n            int index=str[0]-'a';\n            if(str.size()==0 || node->dict[index]==NULL){\n                return \"\\0\";\n            }\n           return find(str.substr(1),node->dict[index],pre+str[0]);\n        }\n        \n        string replaceWith(string word ,trii* node){\n            string temp=find(word,node,\"\");\n            if(temp!=\"\\0\"){\n                word=temp;\n            }\n            return word;\n        }\n    };\n    \n    string replaceWords(vector<string>& dictionary, string sentence) {\n       tree* t=new tree();\n        for(int i=0;i<dictionary.size();i++){\n            t->insert(dictionary[i],t->root);\n        }\n        string ans=sentence;\n        sentence=\"\";\n        for(int i=0;i<ans.size();i++){\n            string word=\"\";\n            while(i<ans.size()&&ans[i]!=' '){\n                word+=ans[i];\n                i++;\n            }\n            \n            sentence+=t->replaceWith(word,t->root)+\" \";\n        }\n        sentence.pop_back();\n        return sentence;\n    }\n};",
        "solution_java": "class Solution {\npublic:\n    class trii{\n        public:\n        char data;\n        trii* dict[26];\n        bool isTerminal;\n        \n        trii(){\n            \n        }\n        \n        trii(char d){\n           data=d;\n            for(int i=0;i<26;i++){\n                dict[i]=NULL;\n            }\n            isTerminal=false;\n        }\n    };\n    \n    class tree{\n        public:\n        trii* root;\n        tree(){\n            root=new trii('\\0');\n        }\n        \n        void insert(string str,trii* node){\n            if(str.size()==0){\n                node->isTerminal=true;\n                return;\n            }\n            int index=str[0]-'a';\n            if(node->dict[index]==NULL ){\n                node->dict[index]=new trii(str[0]);\n            }\n            insert(str.substr(1),node->dict[index]);\n        }\n        \n        string find(string str,trii* node,string pre){\n            if( node->isTerminal==true ){\n                return pre; \n            }            \n            int index=str[0]-'a';\n            if(str.size()==0 || node->dict[index]==NULL){\n                return \"\\0\";\n            }\n           return find(str.substr(1),node->dict[index],pre+str[0]);\n        }\n        \n        string replaceWith(string word ,trii* node){\n            string temp=find(word,node,\"\");\n            if(temp!=\"\\0\"){\n                word=temp;\n            }\n            return word;\n        }\n    };\n    \n    string replaceWords(vector<string>& dictionary, string sentence) {\n       tree* t=new tree();\n        for(int i=0;i<dictionary.size();i++){\n            t->insert(dictionary[i],t->root);\n        }\n        string ans=sentence;\n        sentence=\"\";\n        for(int i=0;i<ans.size();i++){\n            string word=\"\";\n            while(i<ans.size()&&ans[i]!=' '){\n                word+=ans[i];\n                i++;\n            }\n            \n            sentence+=t->replaceWith(word,t->root)+\" \";\n        }\n        sentence.pop_back();\n        return sentence;\n    }\n};",
        "solution_c": "class Solution {\npublic:\n    class trii{\n        public:\n        char data;\n        trii* dict[26];\n        bool isTerminal;\n        \n        trii(){\n            \n        }\n        \n        trii(char d){\n           data=d;\n            for(int i=0;i<26;i++){\n                dict[i]=NULL;\n            }\n            isTerminal=false;\n        }\n    };\n    \n    class tree{\n        public:\n        trii* root;\n        tree(){\n            root=new trii('\\0');\n        }\n        \n        void insert(string str,trii* node){\n            if(str.size()==0){\n                node->isTerminal=true;\n                return;\n            }\n            int index=str[0]-'a';\n            if(node->dict[index]==NULL ){\n                node->dict[index]=new trii(str[0]);\n            }\n            insert(str.substr(1),node->dict[index]);\n        }\n        \n        string find(string str,trii* node,string pre){\n            if( node->isTerminal==true ){\n                return pre; \n            }            \n            int index=str[0]-'a';\n            if(str.size()==0 || node->dict[index]==NULL){\n                return \"\\0\";\n            }\n           return find(str.substr(1),node->dict[index],pre+str[0]);\n        }\n        \n        string replaceWith(string word ,trii* node){\n            string temp=find(word,node,\"\");\n            if(temp!=\"\\0\"){\n                word=temp;\n            }\n            return word;\n        }\n    };\n    \n    string replaceWords(vector<string>& dictionary, string sentence) {\n       tree* t=new tree();\n        for(int i=0;i<dictionary.size();i++){\n            t->insert(dictionary[i],t->root);\n        }\n        string ans=sentence;\n        sentence=\"\";\n        for(int i=0;i<ans.size();i++){\n            string word=\"\";\n            while(i<ans.size()&&ans[i]!=' '){\n                word+=ans[i];\n                i++;\n            }\n            \n            sentence+=t->replaceWith(word,t->root)+\" \";\n        }\n        sentence.pop_back();\n        return sentence;\n    }\n};"
    },
    {
        "title": "Find the Town Judge",
        "algo_input": "In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.\n\nIf the town judge exists, then:\n\n\n\tThe town judge trusts nobody.\n\tEverybody (except for the town judge) trusts the town judge.\n\tThere is exactly one person that satisfies properties 1 and 2.\n\n\nYou are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.\n\nReturn the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, trust = [[1,2]]\nOutput: 2\n\n\nExample 2:\n\nInput: n = 3, trust = [[1,3],[2,3]]\nOutput: 3\n\n\nExample 3:\n\nInput: n = 3, trust = [[1,3],[2,3],[3,1]]\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\t0 &lt;= trust.length &lt;= 104\n\ttrust[i].length == 2\n\tAll the pairs of trust are unique.\n\tai != bi\n\t1 &lt;= ai, bi &lt;= n\n\n",
        "solution_py": "class Solution:\n    def findJudge(self, n: int, trust: List[List[int]]) -> int:\n        possible = set([i for i in range(1,n+1)])\n        in_edges = [0] * (n+1)\n        \n        for first, second in trust:\n            possible.discard(first)\n            in_edges[second] += 1\n            \n        if len(possible) != 1:\n            return -1\n        \n        i = possible.pop()\n        if in_edges[i] == n-1:\n            return i\n        return -1",
        "solution_js": "var findJudge = function(n, trust) {\n    const length = trust.length;\n    let possibleJudge = [], judgeMap = new Map(), value, judge = -1;\n    for(let i = 0; i < length; i++) {\n        if(judgeMap.has(trust[i][0])){\n            value = judgeMap.get(trust[i][0]);\n            value.push(trust[i][1]);\n            judgeMap.set(trust[i][0], value);\n        }\n        else {\n            judgeMap.set(trust[i][0], [trust[i][1]]);\n        }\n    }\n    value = [];\n    for(let i = 1; i <= n; i++) {\n        if(!judgeMap.has(i)) {\n            possibleJudge.push(i);\n        }\n        else {\n            value.push([i,judgeMap.get(i)]);\n        }\n    }\n    if(!value.length || value.length !== n-1) {\n        if(possibleJudge.length === 1) return possibleJudge[0];\n        return judge;\n    }\n    for(let i = 0; i < possibleJudge.length; i++) {\n        judge = possibleJudge[i];\n        for(let j = 0; j < value.length; j++) {\n            if(value[j][1].indexOf(judge) < 0) {\n                judge = -1;\n                break;\n            }\n        }\n        if(judge !== -1) break;\n    }\n    return judge;\n};",
        "solution_java": "class Solution {\n    public int findJudge(int n, int[][] trust) {\n        int count=0;\n        int x[]=new int[n+1];\n        int y[]=new int[n+1];\n         Arrays.fill(x, 0);\n         Arrays.fill(y, 0);\n        for(int i=0;i<trust.length;i++)\n        {\n            x[trust[i][0]]=1;\n        }\n        for(int i=1;i<=n;i++)\n        {\n            if(x[i]!=0)\n            count++;\n            if(x[i]==0)\n            y[i]=1;\n        }\n        if(count==n)\n        return -1;\n       for(int i=1;i<=n;i++)\n       System.out.println(y[i]);\n       int jud=0;\n         for(int i=1;i<=n;i++)\n        {\n            if(y[i]==1)\n            jud=i;\n        }\n        int c=0;\n        for(int i=0;i<trust.length;i++)\n        {\n            if(trust[i][1]==jud)\n            c++;\n        }\n        if(c==n-1)\n        return jud;\n        return -1;\n       \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findJudge(int n, vector<vector<int>>& trust) {\n        vector<pair<int,int>> v(n+1,{0,0});\n        \n        for(auto i : trust){\n            v[i[0]].first++;\n            v[i[1]].second++;\n        }\n        \n        int ans = -1;\n        \n\n        for(int i=1;i<=n;i++){\n            auto p = v[i];\n            if(p.first == 0 && p.second == n-1){\n                ans = i;\n                break;\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Shortest Common Supersequence",
        "algo_input": "Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.\n\nA string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.\n\n&nbsp;\nExample 1:\n\nInput: str1 = \"abac\", str2 = \"cab\"\nOutput: \"cabac\"\nExplanation: \nstr1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.\n\n\nExample 2:\n\nInput: str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput: \"aaaaaaaa\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= str1.length, str2.length &lt;= 1000\n\tstr1 and str2 consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def shortestCommonSupersequence(self, A, B):\n        n, m = len(A), len(B)\n        dp = [B[:i] for i in range(m + 1)]\n        for i in range(n):\n            prev = A[:i]\n            dp[0] = A[:i + 1]\n            for j in range(m):\n                if A[i] == B[j]:\n                    prev, dp[j + 1] = dp[j + 1], prev + A[i]\n                else:\n                    prev, dp[j + 1] = dp[j + 1], min(dp[j] + B[j], dp[j + 1] + A[i], key = len)\n        return dp[-1]",
        "solution_js": "var shortestCommonSupersequence = function(str1, str2) {\n    const lcs = getLCS(str1, str2)\n    \n    let i = 0\n    let j = 0\n\n    let result = ''\n    for (const c of lcs) {\n        while(i < str1.length && str1[i] !== c) {\n            result += str1[i]\n            i++\n        }\n        while(j < str2.length && str2[j] !== c) {\n            result += str2[j]\n            j++\n        }\n        result += c\n        i++\n        j++\n    }\n    while(i < str1.length) {\n        result += str1[i]\n        i++\n    }\n    while(j < str2.length) {\n        result += str2[j]\n        j++\n    }\n    return result\n};\n\nfunction getLCS (a, b) {\n    const t = new Array(a.length + 1).fill(0).map(() => new Array(b.length + 1).fill(0))\n    \n    for (let i = 1; i <= a.length; i++) {\n        for (let j = 1; j <= b.length; j++) {\n            if (a[i - 1] === b[j - 1]) {\n                t[i][j] = 1 + t[i - 1][j - 1]\n            } else {\n                t[i][j] = Math.max(t[i - 1][j], t[i][j - 1])\n            }\n        }\n    }\n    \n    let i = a.length\n    let j = b.length\n    let result = ''\n    while(i > 0 && j > 0) {\n        if (a[i-1] === b[j-1]) {\n            result += a[i-1]\n            i--\n            j--\n        } else {\n            if (t[i-1][j] > t[i][j-1]) {\n                i--\n            } else {\n                j--\n            }\n        }\n    }\n    return result.split('').reverse().join('')\n}",
        "solution_java": "class Solution {\n    public String shortestCommonSupersequence(String str1, String str2) {\n        int m=str1.length();\n        int n=str2.length();\n        int[][] dp=new int[m+1][n+1];\n        for(int i=1;i<m+1;i++){\n            for(int j=1;j<n+1;j++){\n                if(str1.charAt(i-1)==str2.charAt(j-1)){\n                    dp[i][j]=1+dp[i-1][j-1];\n                }else{\n                    dp[i][j]=Math.max(dp[i][j-1],dp[i-1][j]);\n                }\n            }\n        }\n        int i=m,j=n;\n        String res=\"\";\n        while(i>0 && j>0){\n            if(str1.charAt(i-1)==str2.charAt(j-1)){\n                res=str1.charAt(i-1)+res;\n                i--;\n                j--;\n            }else if(dp[i-1][j]>dp[i][j-1]){\n                res=str1.charAt(i-1)+res;\n                i--;\n            }else{\n                res=str2.charAt(j-1)+res;\n                j--;\n            }\n        }\n        while(i>0){\n            res=str1.charAt(i-1)+res;\n            i--;\n        }\n        while(j>0){\n            res=str2.charAt(j-1)+res;\n            j--;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution\n{\n    string LCS(string str1, string str2, int m, int n)\n    {\n        int t[m+1][n+1];\n        string ans = \"\";\n        for(int i = 0;i < m+1; ++i)\n        {\n            for(int j = 0; j< n+1; ++j)\n            {\n                if(i == 0 || j == 0)\n                    t[i][j] = 0;\n            }\n        }\n\n        for(int i = 1; i < m+1; ++i)\n        {\n            for(int j = 1; j < n+1; ++j)\n            {\n                if(str1[i-1] == str2[j-1])\n                    t[i][j] = 1 + t[i-1][j-1];\n                else\n                    t[i][j] = max(t[i-1][j], t[i][j-1]);\n            }\n        }\n        int i = m, j = n;\n        while(i > 0 && j > 0)\n        {\n            if(str1[i-1] == str2[j-1])\n            {\n                ans.push_back(str1[i-1]);\n                --i;\n                --j;\n            }\n\n            else if(t[i][j-1] > t[i-1][j])\n            {\n                ans.push_back(str2[j-1]);\n                --j;\n            }\n\n            else\n            {\n                ans.push_back(str1[i-1]);\n                --i;\n            }\n        }\n        while( i > 0)\n        {\n            ans.push_back(str1[i-1]);\n            --i;\n        }\n        while( j > 0)\n        {\n            ans.push_back(str2[j-1]);\n            --j;\n        }\n        reverse(ans.begin(),ans.end());\n        return ans;\n    }\n\npublic:\n    string shortestCommonSupersequence(string str1, string str2) {\n\n        int m = str1.length();\n        int n = str2.length();\n\n        return LCS(str1, str2, m ,n);\n    }\n};"
    },
    {
        "title": "Minimum Speed to Arrive on Time",
        "algo_input": "You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.\n\nEach train can only depart at an integer hour, so you may need to wait in between each train ride.\n\n\n\tFor example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.\n\n\nReturn the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.\n\nTests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.\n\n&nbsp;\nExample 1:\n\nInput: dist = [1,3,2], hour = 6\nOutput: 1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.\n\n\nExample 2:\n\nInput: dist = [1,3,2], hour = 2.7\nOutput: 3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.\n\n\nExample 3:\n\nInput: dist = [1,3,2], hour = 1.9\nOutput: -1\nExplanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == dist.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= dist[i] &lt;= 105\n\t1 &lt;= hour &lt;= 109\n\tThere will be at most two digits after the decimal point in hour.\n\n",
        "solution_py": "class Solution:\n    def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n        # the speed upper is either the longest train ride: max(dist),\n        # or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).\n        # notice: \"hour will have at most two digits after the decimal point\"\n        upper = max(max(dist), ceil(dist[-1] / 0.01))\n        #\n        # the function to calcute total time consumed\n        total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)\n        # the case of impossible to arrive office on time\n        if total(upper) > hour:\n            return -1\n        #\n        # binary search: find the mimimal among \"all\" feasible answers\n        left, right = 1, upper\n        while left < right:\n            mid = left + (right - left) // 2\n            if total(mid) > hour:\n                left = mid + 1 # should be larger\n            else:\n                right = mid # should explore a smaller one\n        return right",
        "solution_js": "var minSpeedOnTime = function(dist, hour) {\n    let left=1,right=10000000,speed,sum,ans=-1;\n    while(left<=right){\n        //We need to return the minimum positive integer speed (in kilometers per hour) that all the trains must travel. So speed will always be an integer ranging from 1 to 10000000 as per the question description.\n        speed = left + Math.floor((right-left)/2);\n        sum=0;\n        for(let i=0;i<dist.length-1;i++){\n            sum += Math.ceil((dist[i]/speed));\n        }\n        sum += (dist[dist.length-1]/speed);//For the last train we need not to do Math.ceil\n        if(sum<=hour){//sum(time taken is less than the required time, so it can be our answer, but we will keep looking for the another smaller speed until left<=right)\n            ans=speed;\n            right = speed-1;\n        }else{\n            left=speed+1;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int minSpeedOnTime(int[] dist, double hour) {\n        int left = 1;\n        int right = (int) 1e8;\n\n        while (left < right) {\n            int middle = (left + right) / 2;\n            if (arriveOnTime(dist, hour, middle))\n                right = middle;\n            else left = middle + 1;\n        }\n\n        return right == (int) 1e8 ? -1 : right;\n    }\n\n    private boolean arriveOnTime(int[] dist, double hour, int speed) {\n        int time = 0;\n        for (int i = 0; i < dist.length - 1; i++) {\n            time += Math.ceil((double) dist[i] / speed);\n        }\n        return time + (double) dist[dist.length - 1] / speed <= hour;\n    }\n}",
        "solution_c": "class Solution\n{\n    bool canReachInTime(const vector<int>& dist, const double hour, int speed)\n    {\n        double time = 0;\n        for (int i = 0; i < dist.size() - 1; ++i)\n            time += ((dist[i] + speed - 1) / speed);\n\n        time += ((double)dist.back()) / speed;\n        return time <= hour;\n    }\n\npublic:\n    int minSpeedOnTime(vector<int>& dist, double hour)\n    {\n        int N = dist.size();\n        if (hour <= (double)(N - 1))\n            return -1;\n\n        int lo = 1, hi = 1e7, mi;\n        while (lo < hi)\n        {\n            mi = (lo + hi) / 2;\n            if (canReachInTime(dist, hour, mi))\n                hi = mi;\n            else\n                lo = mi + 1;\n        }\n\n        return hi;\n    }\n};"
    },
    {
        "title": "How Many Numbers Are Smaller Than the Current Number",
        "algo_input": "Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's&nbsp;such that&nbsp;j != i and nums[j] &lt; nums[i].\n\nReturn the answer in an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \nFor nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n\n\nExample 2:\n\nInput: nums = [6,5,4,8]\nOutput: [2,1,0,3]\n\n\nExample 3:\n\nInput: nums = [7,7,7,7]\nOutput: [0,0,0,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 500\n\t0 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def smallerNumbersThanCurrent(self, nums):\n        sortify = sorted(nums)\n        return (bisect_left(sortify, i) for i in nums)",
        "solution_js": "var smallerNumbersThanCurrent = function(nums) {\n    let count, ans=[];\n    /*Run a loop on each element excluding nums[i]\n    and compare it with nums[j] if it's large, then count++\n    else break;*/\n    \n    for(let i=0; i<nums.length; i++){\n        let temp=nums[i], count=0;\n        for(let j=0; j<nums.length; j++){\n            if(i===j) continue;\n            if(temp>nums[j]) count++;\n        }\n        ans.push(count);\n    }\n    return ans;\n};\n\n//second way using objects:--->\n\nvar smallerNumbersThanCurrent = function(nums) {\n    let arr=[...nums], ans=[];\n    arr.sort((a,b)=>a-b);\n    let map={};\n    map[arr[0]]=0;\n    for(let i=1; i<arr.length; i++){\n        if(arr[i-1]!==arr[i]) map[arr[i]]=i;\n    }\n    for(let i=0; i<nums.length; i++){\n        ans.push(map[nums[i]]);\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int[] smallerNumbersThanCurrent(int[] nums) {\n        int[] sorted = nums.clone();\n        int[] res = new int[nums.length];//result array\n        Arrays.sort(sorted);\n        for (int i = 0; i < nums.length; ++i) {\n            //binary search it, if there is no duplicates the idx will be how many smaller are there\n            int idx = binarySearch(sorted, nums[i]);\n            //if there are duplicates, then we need to find the first one presented in the array\n            if (idx-1>=0 && sorted[idx-1] == nums[i]) {\n                while (idx >= 0 && sorted[idx] == nums[i]) {\n                    --idx;\n                }\n                ++idx;\n            }\n            //As I said before, array of indices(indexes) will be the answer\n            res[i] = idx;\n        }\n        return res;\n    }\n    //Just simple iterative binary search\n     public static int binarySearch(int[] arr, int target) {\n        int s = 0;\n        int e = arr.length-1;\n        int m = (s+e)/2;\n\n        while (s<=e) {\n            if (arr[m] == target) {\n                return m;\n            } else if (arr[m] > target) {\n                e = m-1;\n            } else {\n                s = m+1;\n            }\n            m = (s+e)/2;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {\n        vector<int> ans;\n        int i,j,size,count;\n        size = nums.size();\n        for(i = 0; i<size; i++){\n            count = 0;\n            for(j = 0;j<size;j++){\n                if(nums[j]<nums[i]) count++;\n            }\n            ans.push_back(count);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Product Difference Between Two Pairs",
        "algo_input": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).\n\n\n\tFor example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.\n\n\nGiven an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.\n\nReturn the maximum such product difference.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,6,2,7,4]\nOutput: 34\nExplanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.\n\n\nExample 2:\n\nInput: nums = [4,2,5,9,7,4,8]\nOutput: 64\nExplanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.\n\n\n&nbsp;\nConstraints:\n\n\n\t4 &lt;= nums.length &lt;= 104\n\t1 &lt;= nums[i] &lt;= 104\n",
        "solution_py": "class Solution:\n    def maxProductDifference(self, nums: List[int]) -> int:\n        max_1 = 0\n        max_2 = 0\n        min_1 = 10001\n        min_2 = 10001\n        for i in nums:\n            if i >= max_1:\n                max_2,max_1 = max_1,i\n            elif i > max_2:\n                max_2 = i\n            if i <= min_1:\n                min_2,min_1 = min_1,i\n            elif i < min_2:\n                min_2 = i\n            \n        return max_1*max_2 - min_1*min_2",
        "solution_js": "var maxProductDifference = function(nums) {\n    nums.sort((a,b) => a-b);\n    return nums.slice(nums.length - 2).reduce((a,b) => a*b, 1) - nums.slice(0, 2).reduce((a,b) => a*b, 1);\n};",
        "solution_java": "class Solution {\n    public int maxProductDifference(int[] nums) {\n        int max1 = Integer.MIN_VALUE;\n        int max2 = max1;\n\n        int min1 = Integer.MAX_VALUE;\n        int min2 = min1;\n        for (int i = 0; i < nums.length; i++) {\n            if (max1 < nums[i]) {\n                max2 = max1;\n                max1 = nums[i];\n            } else if(nums[i] > max2)\n                max2 = nums[i];\n\n            if(min1 > nums[i]){\n                min2 = min1;\n                min1 = nums[i];\n            }else if (nums[i] < min2)\n                min2 = nums[i];\n        }\n        \n        return (max1 * max2) - (min1 * min2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxProductDifference(vector<int>& nums) {\n        //we have to return the result of\n        // (firstMax*secondMax) - (firstMin*secondMin)\n        int max1=INT_MIN;\n        int max2=INT_MIN;\n        int min1=INT_MAX;\n        int min2=INT_MAX;\n        for(int i=0;i<nums.size();i++)\n        {\n\n            if(nums[i]>max1)\n            {\n                //assign the second max to max2\n                max2=max1;\n                max1=nums[i];\n            }\n            else if(nums[i]>max2)\n            {\n                //it can become second max\n                max2= nums[i];\n            }\n\n            //check for the minimum\n            if(nums[i]<min1)\n            {\n                //it can become first minimum\n                min2=min1;\n                min1=nums[i];\n            }\n            else if(nums[i]<min2)\n            {\n                //it can become second minimum\n                min2=nums[i];\n            }\n        }\n        return (max1*max2)- (min1*min2);\n    }\n};"
    },
    {
        "title": "Linked List Cycle II",
        "algo_input": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.\n\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.\n\nDo not modify the linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [3,2,0,-4], pos = 1\nOutput: tail connects to node index 1\nExplanation: There is a cycle in the linked list, where tail connects to the second node.\n\n\nExample 2:\n\nInput: head = [1,2], pos = 0\nOutput: tail connects to node index 0\nExplanation: There is a cycle in the linked list, where tail connects to the first node.\n\n\nExample 3:\n\nInput: head = [1], pos = -1\nOutput: no cycle\nExplanation: There is no cycle in the linked list.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of the nodes in the list is in the range [0, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\tpos is -1 or a valid index in the linked-list.\n\n\n&nbsp;\nFollow up: Can you solve it using O(1) (i.e. constant) memory?\n",
        "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 detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if not head or not head.next:\n            return None\n        slow = fast = entry = head\n        \n        while fast and fast.next:\n            slow = slow.next\n            fast = fast.next.next\n            \n            if slow == fast:\n                while slow != entry:\n                    slow = slow.next\n                    entry = entry.next\n                return entry\n        return None",
        "solution_js": "var detectCycle = function(head) {\n    let slowRunner = head\n    let fastRunner = head\n\n    while(fastRunner) {\n        fastRunner = fastRunner.next?.next\n        slowRunner = slowRunner.next\n\n        if (fastRunner === slowRunner) {\n            fastRunner = slowRunner\n            slowRunner = head\n\n            while (slowRunner !== fastRunner) {\n                slowRunner = slowRunner.next\n                fastRunner = fastRunner.next\n            }\n\n            return slowRunner\n        }\n    }\n\n    return null\n};",
        "solution_java": "public class Solution {\n    public ListNode detectCycle(ListNode head) {\n        if (head == null) return null;\n        ListNode tortoise = head;\n        ListNode hare = new ListNode();\n        hare.next = head.next;\n        while (hare != null && hare.next != null && hare != tortoise) {\n            tortoise = tortoise.next;\n            hare = hare.next.next;\n        }\n        if (hare == null || hare.next == null) return null;\n        tortoise = head;\n        while (tortoise != hare) {\n            tortoise = tortoise.next;\n            hare = hare.next;\n        }\n        return hare;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode *detectCycle(ListNode *head) {\n        map<ListNode*, int> m;\n        int index = 0;\n        while (head)\n        {\n            if (m.find(head) == m.end())\n                m[head] = index;\n            else \n                return (head);\n            head = head->next;\n            index++;       \n        }\n        return (NULL);\n    }\n};"
    },
    {
        "title": "Minimum Moves to Reach Target Score",
        "algo_input": "You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.\n\nIn one move, you can either:\n\n\n\tIncrement the current integer by one (i.e., x = x + 1).\n\tDouble the current integer (i.e., x = 2 * x).\n\n\nYou can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.\n\nGiven the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.\n\n&nbsp;\nExample 1:\n\nInput: target = 5, maxDoubles = 0\nOutput: 4\nExplanation: Keep incrementing by 1 until you reach target.\n\n\nExample 2:\n\nInput: target = 19, maxDoubles = 2\nOutput: 7\nExplanation: Initially, x = 1\nIncrement 3 times so x = 4\nDouble once so x = 8\nIncrement once so x = 9\nDouble again so x = 18\nIncrement once so x = 19\n\n\nExample 3:\n\nInput: target = 10, maxDoubles = 4\nOutput: 4\nExplanation: Initially, x = 1\nIncrement once so x = 2\nDouble once so x = 4\nIncrement once so x = 5\nDouble again so x = 10\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target &lt;= 109\n\t0 &lt;= maxDoubles &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minMoves(self, target: int, maxDoubles: int) -> int:\n        c=0\n        while(maxDoubles>0 and target>1):\n            c += target%2\n            target //= 2\n            c += 1\n            maxDoubles -=1\n        return c + target-1",
        "solution_js": "var minMoves = function(target, maxDoubles) {\n    if (maxDoubles === 0) return target - 1;\n    let count = 0;\n\n    while (target > 1) {\n        if (target % 2 === 0 && maxDoubles > 0) {\n            target /= 2;\n            maxDoubles--;\n        } else {\n            target--;\n        }\n\n        count++;\n    }\n\n    return count;\n};",
        "solution_java": "class Solution {\n    public int minMoves(int target, int maxDoubles) {\n        int ans = 0;\n        for(int i=0;i<maxDoubles;i++){\n            if(target==1)break;\n            \n            if(target%2==0){\n                ans+=1;\n                target=(target)/2;\n            }else{\n                 ans+=2;\n                target=(target-1)/2;\n            }\n        }\n        return ans+target-1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMoves(int target, int maxDoubles) {\n        int cnt = 0;\n        while(target>1 && maxDoubles>0){\n            if(target%2==0){\n                cnt++;\n                maxDoubles--;\n                target = target/2;\n            }\n            else{\n                cnt++;\n                target--;\n            }\n        }\n        return cnt + (target-1);\n    }\n};"
    },
    {
        "title": "Minimum Number of Days to Eat N Oranges",
        "algo_input": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:\n\n\n\tEat one orange.\n\tIf the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.\n\tIf the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.\n\n\nYou can only choose one of the actions per day.\n\nGiven the integer n, return the minimum number of days to eat n oranges.\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 4\nExplanation: You have 10 oranges.\nDay 1: Eat 1 orange,  10 - 1 = 9.  \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange  1 - 1  = 0.\nYou need at least 4 days to eat the 10 oranges.\n\n\nExample 2:\n\nInput: n = 6\nOutput: 3\nExplanation: You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange  1 - 1  = 0.\nYou need at least 3 days to eat the 6 oranges.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 109\n\n",
        "solution_py": "from collections import deque\nfrom math import log2, ceil\nclass Solution:\n    def minDays(self, n: int) -> int:\n        maxd = 2*ceil(log2(n))\n        que = deque([(1,1)])\n        seen = set()\n        while que:\n            v, d = que.popleft()\n            seen.add(v)\n            if v == n:\n                return d\n            for w in [v+1, 2*v, 3*v]:\n                if w not in seen and d <= maxd and w <= n:\n                    que.append((w,d+1))",
        "solution_js": "var minDays = function(n) {\n    const queue = [ [n,0] ];\n    const visited = new Set();\n    \n    while (queue.length > 0) {\n        const [ orangesLeft, days ] = queue.shift();\n        \n        if (visited.has(orangesLeft)) continue;\n        if (orangesLeft === 0) return days;\n        \n        visited.add(orangesLeft);\n        queue.push([orangesLeft - 1, days + 1]);\n        \n        if (orangesLeft % 2 === 0) {\n            queue.push([orangesLeft - orangesLeft / 2, days + 1]);\n        }\n        \n        if (orangesLeft % 3 === 0) {\n            queue.push([orangesLeft - 2 * (orangesLeft / 3), days + 1])\n        }\n    }\n};",
        "solution_java": "class Solution {\n    HashMap<Integer,Integer>map;\n    public int minDays(int n) {\n        map = new HashMap<>();\n        map.put(0,0);\n        map.put(1,1);\n        return dp(n);\n    }\n    public int dp(int n){\n        if(map.get(n)!=null)\n            return map.get(n);\n         int one = 1+(n%2)+dp(n/2);\n         int two = 1+(n%3)+dp(n/3);\n        map.put(n,Math.min(one,two));\n        return map.get(n);\n}\n    }\n        // int one = 1+(n%2)+cache(n/2);\n        // int two = 1+(n%3)+cache(n/3);",
        "solution_c": "class Solution {\npublic:\n    // approach: BFS\n    int minDays(int n) {\n        int cnt=0;\n        queue<int>q;\n        q.push(n);\n        unordered_set<int>s;\n        s.insert(n);\n        while(!q.empty()){\n            int l=q.size();\n            while(l--){\n                int a=q.front();\n                q.pop();\n                if(a==0)\n                    break;\n                if(s.find(a-1)==s.end()){ \n                    q.push(a-1);\n                    s.insert(a-1);\n                }  \n                if(!(a&1) && s.find(a>>1)==s.end()){   // if divisible by 2 and a/2 not present in set\n                    q.push(a>>1);\n                    s.insert(a>>1);\n                }\n                if(a%3==0 && s.find(a/3)==s.end()){  // if divisible by 3 and a/3 not present in set\n                    q.push(a/3);\n                    s.insert(a/3);\n                }\n            }\n            cnt++;\n            if(s.find(0)!=s.end())\n                break;\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Largest Number After Digit Swaps by Parity",
        "algo_input": "You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).\n\nReturn the largest possible value of num after any number of swaps.\n\n&nbsp;\nExample 1:\n\nInput: num = 1234\nOutput: 3412\nExplanation: Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.\n\n\nExample 2:\n\nInput: num = 65875\nOutput: 87655\nExplanation: Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def largestInteger(self, num: int):\n        n = len(str(num))\n        arr = [int(i) for i in str(num)]\n        odd, even = [], []\n        for i in arr:\n            if i % 2 == 0:\n                even.append(i)\n            else:\n                odd.append(i)\n        odd.sort()\n        even.sort()\n        res = 0\n        for i in range(n):\n            if arr[i] % 2 == 0:\n                res = res*10 + even.pop()\n            else:\n                res = res*10 + odd.pop()\n        return res",
        "solution_js": "/**\n * @param {number} num\n * @return {number}\n */\nvar largestInteger = function(num) {\n    var nums = num.toString().split(\"\");//splitting the numbers into an array\n    var odd=[];//helps keep a track of odd numbers\n    var even =[];//helps keep a track of even numbers\n    for(var i=0;i<nums.length;i++){\n        if(nums[i]%2===0) //pushing even numbers to even array\n            even.push(nums[i]);\n        else//pushing odd numbers to odd array\n            odd.push(nums[i]);\n    }\n    odd.sort((a,b)=>a-b);//sorting the arrays in ascending order\n    even.sort((a,b)=>a-b);\n    var ans =[];\n    for(var i=0;i<nums.length;i++){\n        if(nums[i]%2===0){//replacing even with even\n            ans.push(even[even.length-1]);//pushing the greatest even number in the ans\n            even.pop();//popping the used number\n        }\n        else{//replacing odd with odd\n            ans.push(odd[odd.length-1]);//pushing the greatest odd number in the ans\n            odd.pop();//popping the used number\n        }\n    }\n    var ans2 = parseInt(ans.join(\"\"));//converting the ans array into an int number\n    return ans2;\n\n};",
        "solution_java": "class Solution {\n    public int largestInteger(int num) {\n        PriorityQueue<Integer> opq = new PriorityQueue<>();\n        PriorityQueue<Integer> epq = new PriorityQueue<>();\n        int bnum = num;\n        while(num>0){\n            int cur = num%10;\n            if(cur%2==1){\n                opq.add(cur);\n            }else{\n                epq.add(cur);\n            }\n            num /= 10;\n        }\n        StringBuilder sb = new StringBuilder();\n        num = bnum;\n        while(num>0){\n            int cur = num%10;\n            if(cur%2==1)\n                sb.insert(0, opq.poll());\n            else\n                sb.insert(0, epq.poll());\n            num /= 10;\n        }\n        return Integer.parseInt(sb.toString());\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largestInteger(int num) {\n        priority_queue<int> p; // priority queue to store odd digits in descending order\n        priority_queue<int> q; // priority queue to store even digits in descending order\n        string nums=to_string(num); // converting num to a string for easy access of the digits\n        int n=nums.size(); // n stores the number of digits in num\n\n        for(int i=0;i<n;i++){\n            int digit=nums[i]-'0';\n            if((digit)%2) // if digit is odd, push it into priority queue p\n                p.push(digit);\n            else\n                q.push(digit); // if digit is even, push it into priority queue q\n        }\n\n        int answer=0;\n        for(int i=0; i<n; i++){\n            answer=answer*10;\n            if((nums[i]-'0')%2) // if the digit is odd, add the largest odd digit of p into the answer\n                {answer+=p.top();p.pop();}\n            else\n                {answer+=q.top();q.pop();} // if the digit is even, add the largest even digit of q into the answer\n        }\n        return answer;\n    }\n};"
    },
    {
        "title": "Matrix Cells in Distance Order",
        "algo_input": "You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).\n\nReturn the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.\n\nThe distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.\n\n&nbsp;\nExample 1:\n\nInput: rows = 1, cols = 2, rCenter = 0, cCenter = 0\nOutput: [[0,0],[0,1]]\nExplanation: The distances from (0, 0) to other cells are: [0,1]\n\n\nExample 2:\n\nInput: rows = 2, cols = 2, rCenter = 0, cCenter = 1\nOutput: [[0,1],[0,0],[1,1],[1,0]]\nExplanation: The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\n\n\nExample 3:\n\nInput: rows = 2, cols = 3, rCenter = 1, cCenter = 2\nOutput: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\nExplanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rows, cols &lt;= 100\n\t0 &lt;= rCenter &lt; rows\n\t0 &lt;= cCenter &lt; cols\n\n",
        "solution_py": "class Solution:\n    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n        # create a r, c matrix given the rows & cols\n        # each element represents a list [r, c] where r is the row & c the col\n        # find find the distances of all cells from the center (append to res)\n        # sort the result by distance function\n        # Time O(M + N) Space O(M + N)\n        \n        \n        def distance(p1, p2):\n            return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n        \n        matrix = [[i, j] for i in range(rows) for j in range(cols)]\n        center = [rCenter, cCenter]\n        matrix.sort(key=lambda c: distance(c, center))\n        \n        return matrix",
        "solution_js": "var allCellsDistOrder = function(rows, cols, rCenter, cCenter) {\n    let distances = []\n    let result = []\n\n    //create a new \"visited\" cells matrix\n    let visited = new Array(rows).fill([])\n    for(i=0;i<visited.length;i++){\n        visited[i] = new Array(cols).fill(0)\n    }\n\n    const computeDistances = (row, col, rCenter, cCenter) => {\n        if(row >= rows || col >= cols) return\n        if(visited[row][col]) return // don't compute distance again if cell already visited\n        visited[row][col] = 1\n\n        let distance = Math.abs(rCenter - row) + Math.abs(cCenter - col)\n        if(distances[distance]){\n            distances[distance].add([row,col])\n        }else{\n            distances[distance] = new Set()\n            distances[distance].add([row,col])\n        }\n\n        computeDistances(row + 1, col, rCenter, cCenter)\n        computeDistances(row, col + 1, rCenter, cCenter)\n    }\n\n    computeDistances(0, 0, rCenter, cCenter)\n\n    distances.forEach(distance => {\n        result.push(...distance)\n    })\n\n    return result\n};",
        "solution_java": "//--------------------Method 1----------------------\n\nclass Solution {\n    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n        int [][]res=new int[rows*cols][2];\n\n        int idx=0;\n\n        for(int i=0;i<rows;i++){\n            for(int j=0;j<cols;j++){\n                res[idx][0]=i;\n                res[idx][1]=j;\n                idx++;\n            }\n        }\n\n        Arrays.sort(res,(a,b)->{\n            int d1=Math.abs(a[0]-rCenter)+Math.abs(a[1]-cCenter);\n            int d2=Math.abs(b[0]-rCenter)+Math.abs(b[1]-cCenter);\n\n            return d1-d2;\n        });\n\n        return res;\n    }\n}\n\n//--------------------Method 2--------------------\n\n// class Solution {\n// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n// boolean [][]vis=new boolean[rows][cols];\n// int [][]ans=new int[rows*cols][2];\n\n// Queue<Pair> q=new LinkedList<>();\n// q.add(new Pair(rCenter,cCenter));\n// int idx=0;\n// vis[rCenter][cCenter]=true;\n// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};\n\n// while(!q.isEmpty()){\n// Pair curr=q.remove();\n// ans[idx][0]=curr.r;\n// ans[idx][1]=curr.c;\n// idx++;\n\n// for(int []d:dir){\n// int nr=curr.r+d[0];\n// int nc=curr.c+d[1];\n\n// if(nr>=0 && nr<rows && nc>=0 && nc<cols && !vis[nr][nc]){\n// vis[nr][nc]=true;\n// q.add(new Pair(nr,nc));\n// }\n// }\n// }\n\n// return ans;\n// }\n// }\n\n// class Pair{\n// int r;\n// int c;\n\n// public Pair(int r, int c){\n// this.r=r;\n// this.c=c;\n// }\n// }",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n        vector<vector<int>> ans;\n        multimap<int,vector<int>> mp;\n        for(int i = 0;i<rows;i++){\n            for(int j = 0;j<cols;j++){\n                    mp.insert(pair<int,vector<int>>(abs(i-rCenter)+abs(j-cCenter),{i,j})); //map will sort the value based on key(distance)    \n                }\n            }\n        for(auto itr = mp.begin();itr != mp.end();itr++){\n            ans.push_back(itr->second);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Stamping The Sequence",
        "algo_input": "You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.\n\nIn one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.\n\n\n\tFor example, if stamp = \"abc\" and target = \"abcba\", then s is \"?????\" initially. In one turn you can:\n\n\t\n\t\tplace stamp at index 0 of s to obtain \"abc??\",\n\t\tplace stamp at index 1 of s to obtain \"?abc?\", or\n\t\tplace stamp at index 2 of s to obtain \"??abc\".\n\t\n\tNote that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).\n\n\nWe want to convert s to target using at most 10 * target.length turns.\n\nReturn an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.\n\n&nbsp;\nExample 1:\n\nInput: stamp = \"abc\", target = \"ababc\"\nOutput: [0,2]\nExplanation: Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.\n\n\nExample 2:\n\nInput: stamp = \"abca\", target = \"aabcaca\"\nOutput: [3,0,1]\nExplanation: Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= stamp.length &lt;= target.length &lt;= 1000\n\tstamp and target consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def movesToStamp(self, S: str, T: str) -> List[int]:\n        if S == T: return [0]\n        S, T = list(S), list(T)\n        slen, tlen = len(S), len(T) - len(S) + 1\n        ans, tdiff, sdiff = [], True, True\n        while tdiff:\n            tdiff = False\n            for i in range(tlen):\n                sdiff = False\n                for j in range(slen):\n                    if T[i+j] == \"*\": continue\n                    if T[i+j] != S[j]: break\n                    sdiff = True\n                else: \n                    if sdiff:\n                        tdiff = True\n                        for j in range(i, i + slen): T[j] = \"*\"\n                        ans.append(i)\n        for i in range(len(T)):\n            if T[i] != \"*\": return []\n        return reversed(ans)",
        "solution_js": "var movesToStamp = function(stamp, target) {\n    var s = target.replace(/[a-z]/g,\"?\")\n    var repl = s.substr(0,stamp.length)\n    let op = []\n    let s1 = target\n\n    while(s1 !== s){\n        let idx = getIndex()\n        if(idx === -1) return []\n        op.push(idx)\n    }\n    return op.reverse()\n    \n    function getIndex(){\n        for(let i=0; i<target.length; i++){\n            let match = 0\n            let j=0\n            for(; j<stamp.length; j++){\n                if(target.substr(i+j,1) === stamp.substr(j,1)) match++\n                else \n                    if(target.substr(i+j,1) === \"?\") continue\n                else break\n            }\n\n            \n            if(j===stamp.length && match!==0){\n                let k=i\n                for(let j=0; j<stamp.length; j++){\n                    if(k===0){ s1 = \"?\"+target.substr(1)}\n                    else {     s1 = target.substr(0,k)+\"?\"+target.substr(k+1)}\n                    k++\n                    target = s1\n                }\n                return i\n            }\n        }\n    \n    return -1\n    }\n};\n    \n    \n    ```",
        "solution_java": "class Solution {\n    public int[] movesToStamp(String stamp, String target) {\n        \n        /*\n        * Intitution:\n        * Instead of creating target string from intial state,\n        * create the intial state from the target string.\n        * - take a window of stamp length\n        * - reverse that window to the intail state \n        *  current state -> abcdefgh, window = def, \n        *  next state    -> abc???gh \n        *\n        */\n        \n        int sLen = stamp.length();\n        int tLen = target.length();\n        \n        //it save the index of reversed charcacter\n        Queue<Integer> reversedCharIndices= new LinkedList();\n        \n        //it mark Character of target, as reversed\n        boolean[] isReversedCharOfThisIndex = new boolean[tLen];\n        \n        Stack<Integer> stack = new Stack();\n        \n        List<Window> widowList = new ArrayList();\n        \n        for(int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++){\n            \n            Set<Integer> matched = new HashSet();\n            Set<Integer> notMatched = new HashSet();\n            \n            for(int j = 0; j < sLen; j++){\n                \n                //char index of current window of the target\n                int charIndex = windowStartIndex + j;\n                \n                if(stamp.charAt(j) == target.charAt(charIndex)){\n                    matched.add(charIndex);\n                } else {\n                    notMatched.add(charIndex);\n                }\n            }\n            \n            //add the window\n            widowList.add(new Window(matched, notMatched));\n            \n            //when all char of current window is matched with \n            if(notMatched.isEmpty()){\n                stack.push(windowStartIndex);\n                \n                for(int index : matched){\n                    if(!isReversedCharOfThisIndex[index]){\n                        \n                        //add in queue, so that we can process,\n                        //another window which is affected by its character get reversed\n                        reversedCharIndices.add(index);\n                        \n                        //mark it reversed\n                        isReversedCharOfThisIndex[index] = true;\n                    }\n                }\n                \n            }\n        }\n        \n        \n        \n        //get all char index, one by once\n        //see the impact of reverse char of this index, in ano\n        while(!reversedCharIndices.isEmpty()){\n            int reversedCharIndex = reversedCharIndices.remove();\n            \n            int start =  Math.max(0, reversedCharIndex - sLen + 1);\n            int end   =  Math.min(reversedCharIndex, tLen - sLen);\n            \n            for(int windowIndex = start; windowIndex <= end; windowIndex++){\n                \n                if(widowList.get(windowIndex).notMatched.contains(reversedCharIndex)){\n                    \n                   \n                    //as this char is reversed in another window\n                    //remove this char index from current window, \n                    widowList.get(windowIndex).notMatched.remove(reversedCharIndex);\n                    \n                    if(widowList.get(windowIndex).notMatched.isEmpty()){\n                        \n                        //as all of charcater reversed of current window\n                        //now add current window index\n                        stack.push(windowIndex);\n                        \n                        for(int index : widowList.get(windowIndex).matched){\n                            \n                            if(!isReversedCharOfThisIndex[index]){\n\n                                //add in queue, so that we can process,\n                                //another window which is affected by its character get reversed\n                                reversedCharIndices.add(index);\n\n                                //mark it reversed\n                                isReversedCharOfThisIndex[index] = true;\n                            }\n                        }\n                    }\n                }\n                \n            }\n        }\n        \n            \n        for(boolean reversed : isReversedCharOfThisIndex){\n            if(!reversed){\n                return new int[0];\n            }\n        }\n        \n        int i = 0;\n        int[] result = new int[stack.size()];\n        while(!stack.empty()){\n            result[i++] = stack.pop();\n        }\n        \n        \n        return result;\n        \n    }\n}\n\nclass Window {\n    Set<Integer> matched;\n    Set<Integer> notMatched;\n    \n    public Window(Set<Integer> matched, Set<Integer> notMatched){\n        this.matched = matched;\n        this.notMatched = notMatched;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> movesToStamp(string stamp, string target) {\n        auto isUndone = [](auto it, auto endIt) {\n            return all_of(it, endIt, [](char c) { return c == '?'; });\n        };\n        vector<int> res;\n\n        while (!isUndone(begin(target), end(target))) {\n            auto prevResSize = size(res);\n\n            for (size_t i = 0; i < size(target) - size(stamp) + 1; ++i) {\n                auto it = begin(target) + i, endIt = it + size(stamp);\n                if (isUndone(it, endIt))\n                    continue;\n\n                size_t j = 0;\n                for (; j < size(stamp) && (*(it + j) == stamp[j] || *(it + j) == '?'); ++j);\n\n                if (j == size(stamp)) {\n                    fill(it, endIt, '?');\n                    res.push_back(i);\n                }\n            }\n            if (prevResSize == size(res))\n                return {};\n        }\n\n        reverse(begin(res), end(res));\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Ways Where Square of Number Is Equal to Product of Two Numbers",
        "algo_input": "Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:\n\n\n\tType 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; k &lt; nums2.length.\n\tType 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 &lt;= i &lt; nums2.length and 0 &lt;= j &lt; k &lt; nums1.length.\n\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [7,4], nums2 = [5,2,8,9]\nOutput: 1\nExplanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). \n\n\nExample 2:\n\nInput: nums1 = [1,1], nums2 = [1,1,1]\nOutput: 9\nExplanation: All Triplets are valid, because 12 = 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2).  nums1[i]2 = nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\n\n\nExample 3:\n\nInput: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput: 2\nExplanation: There are 2 valid triplets.\nType 1: (3,0,2).  nums1[3]2 = nums2[0] * nums2[2].\nType 2: (3,0,1).  nums2[3]2 = nums1[0] * nums1[1].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 1000\n\t1 &lt;= nums1[i], nums2[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n        sqr1, sqr2 = defaultdict(int), defaultdict(int)\n        m, n = len(nums1), len(nums2)\n        for i in range(m):\n            sqr1[nums1[i]**2] += 1\n        for j in range(n):\n            sqr2[nums2[j]**2] += 1\n\n        res = 0\n        for i in range(m-1):\n            for j in range(i+1, m):\n                if nums1[i]*nums1[j] in sqr2:\n                    res += sqr2[nums1[i]*nums1[j]]\n\n        for i in range(n-1):\n            for j in range(i+1, n):\n                if nums2[i]*nums2[j] in sqr1:\n                    res += sqr1[nums2[i]*nums2[j]]\n        return res",
        "solution_js": "var numTriplets = function(nums1, nums2) {\n    const nm1 = new Map(), nm2 = new Map();\n    const n = nums1.length, m = nums2.length;\n    for(let i = 0; i < n; i++) {\n        for(let j = i + 1; j < n; j++) {\n            const product = nums1[i] * nums1[j];\n            if(!nm1.has(product)) nm1.set(product, 0);\n            const arr = nm1.get(product);\n            nm1.set(product, arr + 1);\n        }\n    }\n    for(let i = 0; i < m; i++) {\n        for(let j = i + 1; j < m; j++) {\n            const product = nums2[i] * nums2[j];\n            if(!nm2.has(product)) nm2.set(product, 0);\n            const arr = nm2.get(product);\n            nm2.set(product, arr + 1);\n        }\n    }\n    let ans = 0;\n\n    for(let num of nums1) {\n        const sq = num * num;\n        if(nm2.has(sq)) {\n            ans += nm2.get(sq);\n        }\n    }\n    for(let num of nums2) {\n        const sq = num * num;\n        if(nm1.has(sq)) {\n            ans += nm1.get(sq);\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int numTriplets(int[] nums1, int[] nums2) {\n        Arrays.sort(nums1);\n        Arrays.sort(nums2);\n        return count(nums1 , nums2) + count(nums2 , nums1);\n    }\n\n    public int count(int a[] , int b[]){\n        int n = a.length;\n        int m = b.length;\n        int count = 0;\n        for(int i=0;i<n;i++){\n            long x = (long)a[i]*a[i];\n            int j = 0;\n            int k = m-1;\n            while(j<k){\n                long prod = (long)b[j]*b[k];\n                if(prod<x)\n                    j++;\n                else if(prod>x)\n                    k--;\n                else if(b[j] != b[k]){\n                    int jNew = j;\n                    int kNew = k;\n\n                    while(b[j] == b[jNew])\n                        jNew++;\n                    while(b[k] == b[kNew])\n                        kNew--;\n                    count += (jNew-j)*(k-kNew);\n                    j = jNew;\n                    k = kNew;\n                }\n                else{\n                    int q = k-j+1;\n                    count += (q)*(q-1)/2;\n                    break;\n                }\n            }\n        }\n        return count;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int numTriplets(vector<int>& nums1, vector<int>& nums2) {\n\n        unordered_map<long, int> m1, m2;\n        for(int i : nums1) m1[(long long)i*i]++;\n        for(int i : nums2) m2[(long long)i*i]++;\n\n        int ans = 0;\n\n        for(int i=0; i<nums2.size()-1; i++){\n            for(int j=i+1; j<nums2.size(); j++){\n                if(m1[(long long)nums2[i] * nums2[j]]){\n                    ans += m1[(long long)nums2[i] * nums2[j]];\n                }\n            }\n        }\n        for(int i=0; i<nums1.size()-1; i++){\n            for(int j=i+1; j<nums1.size(); j++){\n                if(m2[(long long)nums1[i] * nums1[j]]){\n                    ans += m2[(long long)nums1[i] * nums1[j]];\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "The kth Factor of n",
        "algo_input": "You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.\n\nConsider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.\n\n&nbsp;\nExample 1:\n\nInput: n = 12, k = 3\nOutput: 3\nExplanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.\n\n\nExample 2:\n\nInput: n = 7, k = 2\nOutput: 7\nExplanation: Factors list is [1, 7], the 2nd factor is 7.\n\n\nExample 3:\n\nInput: n = 4, k = 4\nOutput: -1\nExplanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= n &lt;= 1000\n\n\n&nbsp;\nFollow up:\n\nCould you solve this problem in less than O(n) complexity?\n",
        "solution_py": "class Solution:\n    def kthFactor(self, n: int, k: int) -> int:\n        start=[1]\n        end=[n]\n        for i in range(2,math.ceil(math.sqrt(n))+1):\n            if n%i==0:\n                start.append(i)\n                if i!=n//i:\n                    end.append(n//i)\n        start=sorted(set(start).union(set(end)))\n        if k<=len(start):\n            return start[k-1]\n        else:\n            return -1",
        "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar kthFactor = function(n, k) {\n    const res = [1]\n    for(let i=2; i<n; i++){\n        if(n%i === 0){\n            res.push(i)\n        }\n    }\n    res.push(n)\n    return res[k-1] || -1\n};",
        "solution_java": "class Solution {\n    public int kthFactor(int n, int k) {\n    ArrayList<Integer> list = new ArrayList<>();\n\n        for (int i = 1; i <= n; i++) {\n\n            if (n % i == 0){\n                list.add(i);\n            }\n        }\n        if (list.size() < k){\n            return -1;\n        }\n        \n        return list.get(k-1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int kthFactor(int n, int k) {\n        vector<int> sol;\n        sol.push_back(1);\n        for(int i = 2; i <= n / 2; i++) {\n            if(n % i == 0) sol.push_back(i);\n        }\n        if(n != 1) sol.push_back(n);\n        if(k > sol.size()) return -1;\n        return sol[k - 1];\n    }\n};"
    },
    {
        "title": "Reaching Points",
        "algo_input": "Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.\n\nThe allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).\n\n&nbsp;\nExample 1:\n\nInput: sx = 1, sy = 1, tx = 3, ty = 5\nOutput: true\nExplanation:\nOne series of moves that transforms the starting point to the target is:\n(1, 1) -&gt; (1, 2)\n(1, 2) -&gt; (3, 2)\n(3, 2) -&gt; (3, 5)\n\n\nExample 2:\n\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: false\n\n\nExample 3:\n\nInput: sx = 1, sy = 1, tx = 1, ty = 1\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sx, sy, tx, ty &lt;= 109\n\n",
        "solution_py": "from collections import defaultdict\n\nclass Solution:\n    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n        def nextNum(ta,tb,s):\n            if ta % tb == s % tb:\n                return min(ta, s)\n            return ta % tb\n        visited = defaultdict(bool)\n        while tx >= sx and ty >= sy and (sx != tx or sy != ty):\n            if tx > ty:\n                tx, ty = nextNum(tx, ty, sx), ty\n            else:\n                tx, ty = tx, nextNum(ty, tx, sy)\n            if visited[(tx,ty)]:\n                break\n            visited[(tx,ty)] = True\n        return (sx == tx) and (sy == ty)",
        "solution_js": "/**\n * @param {number} sx\n * @param {number} sy\n * @param {number} tx\n * @param {number} ty\n * @return {boolean}\n */\nvar reachingPoints = function(sx, sy, tx, ty) {\n    while (tx >= sx && ty >= sy) {\n        if (tx == ty) break;\n        \n        if (tx > ty) {\n            if (ty > sy) tx %= ty;\n            else return (tx - sx) % ty == 0;\n        } else {\n            if (tx > sx) ty %= tx;\n            else return (ty - sy) % tx == 0;\n        }\n    }\n    \n    return (tx == sx && ty == sy);\n};",
        "solution_java": "class Solution {\n    public boolean reachingPoints(int sx, int sy, int tx, int ty) {\n        if (sx==tx && sy==ty){\n            return true;\n        }\n        if (tx < sx || ty < sy){\n            return false;\n        }\n        return tx<ty?\n                  reachingPoints(sx, sy, tx, Math.min(ty%tx+sy/tx*tx,ty-tx))\n                : reachingPoints(sx, sy, Math.min(tx%ty+sx/ty*ty,tx-ty), ty);\n    }\n}",
        "solution_c": "/*\nExplanation:\n\nLet's say at some point we have coordinates as (a,b)\nif(a>b) then at the previous step coordinate must be (a-b,b)\nas it can't be (a,b-a) because all the coordinates are positive and for a>b... b-a<0\nthis continues till the point when a becomes <=b\nwe can run a loop till there but its time taking\nwe can observe that the above phenomeon occurs till it becomes (a%b,b)\nexample :\nfor (50,7) it would have been like this:\n(50,7)...(43,7)...(36,7)...........(8,7)..(1,7)\n1 = 50%7\nBy repeating this procedure, after the loop, we have to test if sx == tx or sy == ty. There is still a condition to test.\nLet see we got sy = ty = 5 and have the following result\nsx,sy = (16,5)\ntx,ty = (21,5)\nnow if we run our program then it will stop at (1,5) which is not equal to sx,sy and will return false\nhowever during our iteration we will encounter (16,5) infact after the first iteration only but according to our current code it won't detect it\nso at the end we apply another condition:\ncheck if (tx - sx) % ty == 0. In our case, (21 - 16) mod 5 = 0 so we can return true.\n*/\n\n\nclass Solution \n{\npublic:\n    // METHOD - 1\n    bool reachingPoints_recursive(int sx, int sy, int tx, int ty) \n    {\n        if (sx > tx ||  sy > ty)\n        {\n            return false;\n        }\n        \n        if (sx == tx && sy == ty)\n        {\n            return true;\n        }\n        \n        \n        bool canReach = reachingPoints_recursive(sx, sx+sy, tx, ty);\n        if (!canReach)\n        {\n            canReach = reachingPoints_recursive(sx+sy, sy, tx, ty);\n        }\n        \n        return canReach;\n    }\n    \n    \n    // METHOD - 2\n    bool reachingPoints_internal(int sx, int sy, int tx, int ty)\n    {\n        if (sx > tx || sy > ty)\n        {\n            return false;\n        }\n        else if (sx == tx && sy == ty)\n        {\n            return true;\n        }\n        \n        while (tx > sx && ty > sy)\n        {\n            if (tx > ty)\n            {\n                // implies previous path to this tx, ty should have to be tx-ty, ty \n                // and this could continue till either tx < ty i.e difference would be tx % ty\n                // so instead of doing that repeatedly just go the final point where \n                // tx would have started before started adding ty to it repeatedly \n                tx = tx % ty;\n            }\n            else\n            {\n                // implies previous path to this tx, ty should have to be (tx, ty-tx)\n                // and this could continue till either tx > ty i.e difference would be tx % ty\n                // so instead of doing that repeatedly just go the final point where \n                // ty would have started before started adding tx to it repeatedly\n                ty = ty % tx;\n            }\n        }\n        \n        if ((tx == sx) && ((ty - sy) % sx == 0) )\n        {\n            return true;\n        }\n        else if ((ty == sy) && ((tx - sx) % sy == 0))\n        {\n            return true;\n        }\n        \n        return false;\n    }\n    \n    \n    bool reachingPoints(int sx, int sy, int tx, int ty)\n    {\n        // Method-1 : recurssion - will not work for larger numbers as stack will use up all the memory\n\t\t// return reachingPoints_recursive(sx, sy, tx, ty);\n        \n\t\t// Method-2 : Effecient non recursive solution\n        return reachingPoints_internal(sx, sy, tx, ty);\n    }\n};"
    },
    {
        "title": "Swapping Nodes in a Linked List",
        "algo_input": "You are given the head of a linked list, and an integer k.\n\nReturn the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\n\n\nExample 2:\n\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 &lt;= k &lt;= n &lt;= 105\n\t0 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n        tot = 0 # initialise total\n        Head = head\n        while Head: # count total nodes\n            Head = Head.next # move forward\n            tot += 1 # incerse count by one for each node\n        one, two = None, None # two pointers of one and two\n        count = 1 # we're initialising to one because we have one based index for swapping\n        Head = head # regain original head to traverse\n        while Head:\n            if one and two: break # if we have both one and two then break loop to save time\n            if count == k: # if from forward we reach at node k then it's our first node\n                one = Head\n            if count == (tot-k+1): # if from backward we reach to node k then save it\n                two = Head\n            Head = Head.next # move further\n            count += 1 # increse count\n        one.val, two.val = two.val, one.val # now swap values\n        return head # return head",
        "solution_js": "var swapNodes = function(head, k) {\n    let A = head, B = head, K, temp\n    for (let i = 1; i < k; i++) A = A.next\n    K = A, A = A.next\n    while (A) A = A.next, B = B.next\n    temp = K.val, K.val = B.val, B.val = temp\n    return head\n};",
        "solution_java": "class Solution {\n    public ListNode swapNodes(ListNode head, int k) {\n        ListNode fast = head;\n        ListNode slow = head;\n        ListNode first = head, second = head;\n\n        // Put fast (k-1) nodes after slow\n        for(int i = 0; i < k - 1; ++i)\n            fast = fast.next;\n\n        // Save the node for swapping\n        first = fast;\n\n        // Move until the end of the list\n        while(fast.next != null) {\n            slow = slow.next;\n            fast = fast.next;\n        }\n\n        // Save the second node for swapping\n        // Note that the pointer second isn't necessary: we could use slow for swapping as well\n        // However, having second improves readability\n        second = slow;\n\n        // Swap values\n        int temp = first.val;\n        first.val = second.val;\n        second.val = temp;\n\n        return head;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* swapNodes(ListNode* head, int k) {\n        \n        // declare a dummy node\n        \n        ListNode* dummy = new ListNode(0);\n        \n        // point dummy -> next to head\n        \n        dummy -> next = head;\n        \n        // declare a tail pointer and point to dummy\n        \n        ListNode* tail = dummy;\n        \n        // move the curr pointer (k - 1) times\n        \n        // this will maintain a gap of (k - 1) between curr and tail pointer\n        \n        ListNode* curr = head;\n        \n        while(k > 1)\n        {\n            curr = curr -> next;\n            \n            k--;\n        }\n        \n        // store the address in start pointer\n        \n        ListNode* start = curr;\n        \n        // maintaing a gap of (k - 1) between curr and tail, move both pointer\n        \n        while(curr)\n        {\n            tail = tail -> next;\n            \n            curr = curr -> next;\n        }\n        \n        // store the address of kth node from end\n        \n        ListNode* end = tail;\n        \n        // swap the values\n        \n        swap(start -> val, end -> val);\n        \n        // dummy -> next will be head\n        \n        return dummy -> next;\n    }\n};"
    },
    {
        "title": "Min Max Game",
        "algo_input": "You are given a 0-indexed integer array nums whose length is a power of 2.\n\nApply the following algorithm on nums:\n\n\n\tLet n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.\n\tFor every even index i where 0 &lt;= i &lt; n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).\n\tFor every odd index i where 0 &lt;= i &lt; n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).\n\tReplace the array nums with newNums.\n\tRepeat the entire process starting from step 1.\n\n\nReturn the last number that remains in nums after applying the algorithm.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,5,2,4,8,2,2]\nOutput: 1\nExplanation: The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.\n\n\nExample 2:\n\nInput: nums = [3]\nOutput: 3\nExplanation: 3 is already the last remaining number, so we return 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1024\n\t1 &lt;= nums[i] &lt;= 109\n\tnums.length is a power of 2.\n\n",
        "solution_py": "class Solution:\n    def minMaxGame(self, a: List[int]) -> int:\n        \n        def solve(n):\n            if n==1:\n                return\n            for i in range(n//2):\n                if i%2:\n                    a[i] = max (a[2*i], a[2*i+1])\n                else:\n                    a[i] = min (a[2*i], a[2*i+1])\n            solve(n//2)\n            return\n        solve(len(a))\n        return a[0]",
        "solution_js": "var minMaxGame = function(nums) {\n    while (nums.length > 1) {\n        let half = nums.length / 2;\n        for (let i = 0; i < half; i++)\n            nums[i] = i % 2 === 0 ? Math.min(nums[2 * i], nums[2 * i + 1]) : Math.max(nums[2 * i], nums[2 * i + 1]);\n\n        nums.length = half;\n    }\n\n    return nums[0];\n};",
        "solution_java": "class Solution {\n    public int minMaxGame(int[] nums) {\n        var isMin = true;\n        var n=1;\n        \n        while(n<nums.length) {\n            \n            for(int i=0; i<nums.length; i+= n*2) {\n                nums[i] = isMin ?\n                    Math.min(nums[i], nums[i+n]) : \n                    Math.max(nums[i], nums[i+n]);\n                isMin = !isMin;\n            }\n            \n            n *= 2;\n        }\n        \n        return nums[0];\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMaxGame(vector<int>& nums) {\n        int n = nums.size(); \n        if(n==1) return nums[0];  // Base case\n        vector<int> newNum(n/2); \n        for(int i=0; i<n/2; i++) { \n            if(i%2==0) newNum[i] = min(nums[2 * i], nums[2 * i + 1]); \n            else newNum[i] = max(nums[2 * i], nums[2 * i + 1]); \n        } \n        int res = minMaxGame(newNum); // Recursive call\n        return res;\n    }\n};"
    },
    {
        "title": "Find K-th Smallest Pair Distance",
        "algo_input": "The distance of a pair of integers a and b is defined as the absolute difference between a and b.\n\nGiven an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 &lt;= i &lt; j &lt; nums.length.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,1], k = 1\nOutput: 0\nExplanation: Here are all the pairs:\n(1,3) -&gt; 2\n(1,1) -&gt; 0\n(3,1) -&gt; 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0.\n\n\nExample 2:\n\nInput: nums = [1,1,1], k = 2\nOutput: 0\n\n\nExample 3:\n\nInput: nums = [1,6,1], k = 3\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t2 &lt;= n &lt;= 104\n\t0 &lt;= nums[i] &lt;= 106\n\t1 &lt;= k &lt;= n * (n - 1) / 2\n\n",
        "solution_py": "from heapq import heappush, heappop, heapify\nclass Solution:\n    def smallestDistancePair(self, nums: List[int], k: int) -> int:\n        # pairs = list(combinations(nums, 2))\n        \n        maxHeap = []\n        heapify(maxHeap)\n        \n        for idx, val1 in enumerate(nums):\n            for val2 in nums[idx + 1:]:\n                pair = [val1, val2]\n                heappush(maxHeap, [-1*abs(pair[0] - pair[1]), pair])\n                if len(maxHeap) > k:\n                    heappop(maxHeap)\n        \n        return -1*maxHeap[0][0]",
        "solution_js": "var smallestDistancePair = function(nums, k) {    \n    nums.sort((a,b) => a - b);   \n    let left = 0, right = nums[nums.length-1] - nums[0], mid = null, total = 0;    \n    \n    while (left < right) {\n        mid = left + Math.floor((right - left) / 2);\n    \n        total = 0;\n        for (var i = 0, j = 1; i < nums.length - 1 && total <= k; i++) {\n            for ( ; j < nums.length && nums[j] - nums[i] <= mid; j++) {}\n\t\t\ttotal += j - i - 1; \n        }\n        \n        if (total >= k) {right = mid;}  \n\t\telse {left = mid+1;}\n    }    \n\t\n    return left;\n};",
        "solution_java": "class Solution {\n    public int smallestDistancePair(int[] nums, int k) {\n        Arrays.sort(nums);\n        int low = 0, high = nums[nums.length-1] - nums[0];\n        \n        while(low<=high){\n            int mid = low + (high-low)/2;\n            if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1;\n            else low = mid + 1;\n        }\n        return low;\n    }\n    private int noOfDistancesLessThan(int dist,int[] nums){\n        int count = 0,i = 0, j = 0;\n        while(i<nums.length){\n            while(j<nums.length && nums[j]-nums[i]<=dist){  // sliding window\n                j++;\n            }\n            count += j-i-1;\n            i++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int count(vector<int> &temp,int mid){\n        int i=0,j=0,n=temp.size();\n        int len=0;\n\n        while(i<n){\n            while(j<n && (temp[j]-temp[i])<=mid) j++;\n            len+=j-i-1;\n            i++;\n        }\n        return len;\n    }\n    int smallestDistancePair(vector<int>& nums, int k) {\n        int s=0,e=1e6;\n        int ans=0;\n        vector<int> temp=nums;\n        sort(temp.begin(),temp.end());\n        while(s<=e){\n            int mid=s+(e-s)/2;\n\n            if(count(temp,mid)>=k){\n                ans=mid;\n                e=mid-1;\n            }else {\n                s=mid+1;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Design Bitset",
        "algo_input": "A Bitset is a data structure that compactly stores bits.\n\nImplement the Bitset class:\n\n\n\tBitset(int size) Initializes the Bitset with size bits, all of which are 0.\n\tvoid fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs.\n\tvoid unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs.\n\tvoid flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.\n\tboolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.\n\tboolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.\n\tint count() Returns the total number of bits in the Bitset which have value 1.\n\tString toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Bitset\", \"fix\", \"fix\", \"flip\", \"all\", \"unfix\", \"flip\", \"one\", \"unfix\", \"count\", \"toString\"]\n[[5], [3], [1], [], [], [0], [], [], [0], [], []]\nOutput\n[null, null, null, null, false, null, null, true, null, 2, \"01010\"]\n\nExplanation\nBitset bs = new Bitset(5); // bitset = \"00000\".\nbs.fix(3);     // the value at idx = 3 is updated to 1, so bitset = \"00010\".\nbs.fix(1);     // the value at idx = 1 is updated to 1, so bitset = \"01010\". \nbs.flip();     // the value of each bit is flipped, so bitset = \"10101\". \nbs.all();      // return False, as not all values of the bitset are 1.\nbs.unfix(0);   // the value at idx = 0 is updated to 0, so bitset = \"00101\".\nbs.flip();     // the value of each bit is flipped, so bitset = \"11010\". \nbs.one();      // return True, as there is at least 1 index with value 1.\nbs.unfix(0);   // the value at idx = 0 is updated to 0, so bitset = \"01010\".\nbs.count();    // return 2, as there are 2 bits with value 1.\nbs.toString(); // return \"01010\", which is the composition of bitset.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= size &lt;= 105\n\t0 &lt;= idx &lt;= size - 1\n\tAt most 105 calls will be made in total to fix, unfix, flip, all, one, count, and toString.\n\tAt least one call will be made to all, one, count, or toString.\n\tAt most 5 calls will be made to toString.\n\n",
        "solution_py": "class Bitset(object):\n\n    def __init__(self, size):\n        self.a = 0\n        self.size = size\n        self.cnt = 0\n\n    def fix(self, idx):\n        if self.a & (1 << idx) == 0:\n            self.a |= 1 << idx\n            self.cnt += 1\n\n    def unfix(self, idx):\n        if self.a & (1 << idx):\n            self.a ^= 1 << idx\n            self.cnt -= 1\n\n    def flip(self):\n        self.a ^= (1 << self.size) - 1\n        self.cnt = self.size - self.cnt\n\n    def all(self):\n        return self.cnt == self.size\n\n    def one(self):\n        return self.a > 0\n\n    def count(self):\n        return self.cnt\n\n    def toString(self):\n        a = bin(self.a)[2:]\n        return a[::-1] + '0' * (self.size - len(a))",
        "solution_js": "var Bitset = function(size) {\n    //this.bits = new Array(size).fill(0);\n    //this.bitsOp = new Array(size).fill(1);\n    this.set0 = new Set();\n    this.set1 = new Set();\n    for (let i = 0; i<size; i++) this.set0.add(i);\n};\n\n/** \n * @param {number} idx\n * @return {void}\n */\nBitset.prototype.fix = function(idx) {\n  //this.bits[idx] = 1;\n  //this.bitsOp[idx] = 0;\n  if (this.set0.has(idx)) {\n    this.set1.add(idx);\n    this.set0.delete(idx);\n  }\n};\n\n/** \n * @param {number} idx\n * @return {void}\n */\nBitset.prototype.unfix = function(idx) {\n  //this.bits[idx] = 0;\n  //this.bitsOp[idx] = 1;\n  if (this.set1.has(idx)) {\n    this.set0.add(idx);\n    this.set1.delete(idx);\n  }\n};\n\n/**\n * @return {void}\n */\nBitset.prototype.flip = function() {\n  //this.bits = this.bits.map(x=>(x)?0:1); \n  //this.bits.forEach(x=>x=(x)?0:1); \n  [this.set0, this.set1] = [this.set1, this.set0];\n};\n\n/**\n * @return {boolean}\n */\nBitset.prototype.all = function() {\n  //return (this.bits.filter(x=>x).length == this.bits.length) \n  //return !this.bits.includes(0);\n  //for (let i = 0; i<this.bits.length; i++)\n    //if (this.bits[i] === 0) return false;\n   //return true; \n  return this.set0.size===0\n};\n\n/**\n * @return {boolean}\n */\nBitset.prototype.one = function() {\n    //return this.bits.filter(x=>x).length>0 \n    //return this.bits.includes(1);\n    //for (let i = 0; i<this.bits.length; i++)\n      //if (this.bits[i] === 1) return true;\n     //return false; \n  return this.set1.size>0;\n};\n\n/**\n * @return {number}\n */\nBitset.prototype.count = function() {\n    //return this.bits.filter(x=>x).length \n  //return this.bits.reduce((sum, cur)=>sum+cur);\n  return this.set1.size;\n};\n\n/**\n * @return {string}\n */\nBitset.prototype.toString = function() {\n    //return this.bits.join('');\n  let set = new Array(this.set0.size+this.set1.size);\n  for (let i=0; i<set.length; i++) {\n    set[i] = this.set0.has(i)?0:1;\n  }\n  return set.join('');\n};",
        "solution_java": "class Bitset {\n    int size;\n    Set<Integer> one = new HashSet<>();\n    Set<Integer> zero = new HashSet<>();\n    public Bitset(int size) {\n        this.size = size;\n        for(int i=0;i<size;i++) zero.add(i);\n    }\n    \n    public void fix(int idx) {\n        one.add(idx);\n        zero.remove(idx);\n    }\n    \n    public void unfix(int idx) {\n        one.remove(idx);\n        zero.add(idx);\n    }\n    \n\t//swapping object's referrence is O(1)\n    public void flip() {\n        Set<Integer> s = one;\n        one = zero;\n        zero = s;\n    }\n    \n    public boolean all() {\n        return one.size() == size;\n    }\n    \n    public boolean one() {\n        return one.size()>=1;\n    }\n    \n    public int count() {\n        return one.size();\n    }\n    \n    public String toString() {\n        StringBuilder sb=  new StringBuilder();\n        for(int i=0;i<size;i++) {\n            if(one.contains(i)) sb.append(\"1\"); \n            else if(zero.contains(i)) sb.append(\"0\");\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Bitset {\npublic:\n    vector<int>arr;\n    int cnt,cntflip;\n    Bitset(int size) {\n        arr.resize(size,0);\n        cnt=0,cntflip=0;\n    }\n    void fix(int idx) {\n\t// means current bit is 0 ,so set it to 1\n        if((arr[idx]+cntflip)%2==0){\n            arr[idx]++;\n            cnt++;\n        }\n    }\n    void unfix(int idx) {\n\t// means current bit is 1,so set it to 0\n      if((arr[idx]+cntflip)%2!=0){\n            arr[idx]--;\n            cnt--;\n        }  \n    }\n    void flip() {\n\t// cnt will flip ,if we flip all the bits\n         cnt=arr.size()-cnt;\n        cntflip++;\n    }\n    bool all() {\n        if(cnt==arr.size())\n            return true;\n        return false;\n    }\n    bool one() {\n        if(cnt>=1)\n            return true;\n        return false;\n    }\n    int count() {\n        return cnt;\n    }\n    string toString() {\n        string ans;\n        for(auto &ele :arr){\n            if((cntflip+ele)%2==0)\n                ans.push_back('0');\n            else\n                ans.push_back('1');  \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Ideal Subsequence",
        "algo_input": "You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:\n\n\n\tt is a subsequence of the string s.\n\tThe absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.\n\n\nReturn the length of the longest ideal string.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\nNote that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.\n\n&nbsp;\nExample 1:\n\nInput: s = \"acfgbd\", k = 2\nOutput: 4\nExplanation: The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.\n\nExample 2:\n\nInput: s = \"abcd\", k = 3\nOutput: 4\nExplanation: The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\t0 &lt;= k &lt;= 25\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestIdealString(self, s: str, k: int) -> int:\n        DP = [0 for _ in range(26)]\n        ans = 1\n        \n        for ch in s:\n            i = ord(ch) - ord('a')\n            DP[i] = DP[i] + 1\n            \n            for j in range(max(0, i - k), min(25, i + k) + 1):\n                if j != i:\n                    DP[i] = max(DP[i], DP[j] + 1)\n            \n            ans = max(ans, DP[i])\n        \n        return ans",
        "solution_js": "var longestIdealString = function(s, k) {\n    let n = s.length\n    let dp = Array(26).fill(0);\n    let ans = 0;\n    for(let i=0; i<n; i++){\n        const cur = s.charCodeAt(i)-97;\n        dp[cur] += 1;\n        for(let j=Math.max(0, cur-k); j<=Math.min(cur+k, 25); j++){\n            if(j !== cur){\n                dp[cur] = Math.max(dp[cur], dp[j]+1);\n            }\n        }\n        ans = Math.max(dp[cur], ans)\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int longestIdealString(String s, int k) {\n        int DP[] = new int[26], ans = 1;\n\n        for (int ch = 0, n = s.length(); ch < n; ch++) {\n            int i = s.charAt(ch) - 'a';\n            DP[i] = DP[i] + 1;\n\n            for (int j = Math.max(0, i - k); j <= Math.min(25, i + k); j++)\n                if (j != i)\n                    DP[i] = Math.max(DP[i], DP[j] + 1);\n\n            ans = Math.max(ans, DP[i]);\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestIdealString(string s, int k) {\n        int DP[26] = {0}, ans = 1;\n\n        for (char &ch: s) {\n            int i = ch - 'a';\n            DP[i] = DP[i] + 1;\n\n            for (int j = max(0, i - k); j <= min(25, i + k); j++)\n                if (j != i)\n                    DP[i] = max(DP[i], DP[j] + 1);\n\n            ans = max(ans, DP[i]);\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Linked List Cycle",
        "algo_input": "Given head, the head of a linked list, determine if the linked list has a cycle in it.\n\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the&nbsp;next&nbsp;pointer. Internally, pos&nbsp;is used to denote the index of the node that&nbsp;tail's&nbsp;next&nbsp;pointer is connected to.&nbsp;Note that&nbsp;pos&nbsp;is not passed as a parameter.\n\nReturn&nbsp;true if there is a cycle in the linked list. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: head = [3,2,0,-4], pos = 1\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n\n\nExample 2:\n\nInput: head = [1,2], pos = 0\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 0th node.\n\n\nExample 3:\n\nInput: head = [1], pos = -1\nOutput: false\nExplanation: There is no cycle in the linked list.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of the nodes in the list is in the range [0, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\tpos is -1 or a valid index in the linked-list.\n\n\n&nbsp;\nFollow up: Can you solve it using O(1) (i.e. constant) memory?\n",
        "solution_py": "class Solution:\n    def hasCycle(self, head: Optional[ListNode]) -> bool:\n        for i in range(0, 10001):\n            if head == None: return False\n            head = head.next\n        \n        return True",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n *     this.val = val;\n *     this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nfunction hasCycle(head){\n    \n  let fast = head;\n  while (fast && fast.next) {\n    head = head.next;\n    fast = fast.next.next;\n    if (head === fast) return true;\n  }\n   //head and first pointers value in \n  //each iteration with head=[3,2,0,-4], pos = 1\n  //1st iteration: 3 3\n  //2nd iteration: 2 0\n  //3rd iteration: 0 2\n  //final iteration: -4 -4\n  return false;\n};",
        "solution_java": "public class Solution {\n    public boolean hasCycle(ListNode head) {\n        ListNode fast = head;\n        ListNode slow = head;\n        boolean result = false;\n        while(fast!=null && fast.next!=null){\n            fast = fast.next.next;\n            slow = slow.next;\n                if(fast == slow){\n                    result =  true;\n                    break;\n                }\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool hasCycle(ListNode *head) {\n\t\n\t\t// if head is NULL then return false;\n        if(head == NULL)\n            return false;\n        \n\t\t// making two pointers fast and slow and assignning them to head\n        ListNode *fast = head;\n        ListNode *slow = head;\n        \n\t\t// till fast and fast-> next not reaches NULL\n\t\t// we will increment fast by 2 step and slow by 1 step\n        while(fast != NULL && fast ->next != NULL)\n        {\n            fast = fast->next->next;\n            slow = slow->next;\n            \n\t\t\t\n\t\t\t// At the point if fast and slow are at same address\n\t\t\t// this means linked list has a cycle in it.\n            if(fast == slow)\n                return true;\n        }\n        \n\t\t// if traversal reaches to NULL this means no cycle.\n        return false;\n    }\n};"
    },
    {
        "title": "Find Elements in a Contaminated Binary Tree",
        "algo_input": "Given a binary tree with the following rules:\n\n\n\troot.val == 0\n\tIf treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1\n\tIf treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2\n\n\nNow the binary tree is contaminated, which means all treeNode.val have been changed to -1.\n\nImplement the FindElements class:\n\n\n\tFindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.\n\tbool find(int target) Returns true if the target value exists in the recovered binary tree.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]\nOutput\n[null,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True \n\nExample 2:\n\nInput\n[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]\nOutput\n[null,true,true,false]\nExplanation\nFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False\n\nExample 3:\n\nInput\n[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\nOutput\n[null,true,false,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True\n\n\n&nbsp;\nConstraints:\n\n\n\tTreeNode.val == -1\n\tThe height of the binary tree is less than or equal to 20\n\tThe total number of nodes is between [1, 104]\n\tTotal calls of find() is between [1, 104]\n\t0 &lt;= target &lt;= 106\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass FindElements:\n\n    def __init__(self, root: Optional[TreeNode]):\n        def recoverTree(root):\n            if not root:\n                return None\n            self.vals.add(root.val)\n            if root.left:\n                root.left.val = 2 * root.val + 1\n                recoverTree(root.left)\n            if root.right:\n                root.right.val = 2 * root.val + 2\n                recoverTree(root.right)\n        self.vals = set()\n        root.val = 0\n        recoverTree(root)\n\n    def find(self, target: int) -> bool:\n        return target in self.vals\n\n# Your FindElements object will be instantiated and called as such:\n# obj = FindElements(root)\n# param_1 = obj.find(target)",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n */\nvar FindElements = function(root) {\n    this.st = new Set()\n\n    recover = (root, val) =>{\n    this.st.add(val);\n    if(root.left != null) recover(root.left, val * 2 + 1)\n    if(root.right != null) recover(root.right, val * 2 + 2)\n    }\n\n    recover(root, 0)\n};\n\n/**\n * @param {number} target\n * @return {boolean}\n */\nFindElements.prototype.find = function(target) {\n    return this.st.has(target)\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * var obj = new FindElements(root)\n * var param_1 = obj.find(target)\n */",
        "solution_java": "class FindElements {\n    TreeNode tree,nodept;\n    public FindElements(TreeNode root) {\n        tree=root;\n        tree.val=0;\n        go(tree);\n    }\n\n    void go(TreeNode node){\n        if(node.left!=null){\n            node.left.val=node.val*2+1;\n            go(node.left);\n        }\n        if(node.right!=null){\n            node.right.val=node.val*2+2;\n            go(node.right);\n        }\n    }\n\n    public boolean find(int target) {\n        return doit(target);\n    }\n\n    boolean doit(int target){\n        if(target==0){\n            nodept=tree;\n            return true;\n        }\n        boolean f=doit((target-1)/2);\n        if(!f)return false;\n        if(nodept.left!=null && nodept.left.val==target)\n            nodept=nodept.left;\n        else if(nodept.right!=null && nodept.right.val==target)\n            nodept=nodept.right;\n        else f=false;\n        return f;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass FindElements {\npublic:\n    void initialize(TreeNode* root,unordered_set<int> &s){\n        queue<TreeNode*> q;\n        q.push(root);\n        while(!q.empty()){\n            auto t = q.front();\n            q.pop();\n            s.insert(t->val);\n            if(t->left != NULL){\n                t->left->val = 2*(t->val)+1;\n                q.push(t->left);\n            }\n            if(t->right != NULL){\n                t->right->val= 2*(t->val)+2;\n                q.push(t->right);\n            }\n        }\n    }\n    unordered_set<int> s;\n    FindElements(TreeNode* root) {\n        root->val = 0;\n        \n\n        initialize(root,s);\n        \n    }\n    \n    bool find(int target) {\n        if(s.find(target) != s.end())\n            return true;\n        return false;\n    }\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements* obj = new FindElements(root);\n * bool param_1 = obj->find(target);\n */```"
    },
    {
        "title": "LFU Cache",
        "algo_input": "Design and implement a data structure for a Least Frequently Used (LFU) cache.\n\nImplement the LFUCache class:\n\n\n\tLFUCache(int capacity) Initializes the object with the capacity of the data structure.\n\tint get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.\n\tvoid put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.\n\n\nTo determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.\n\nWhen a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.\n\nThe functions&nbsp;get&nbsp;and&nbsp;put&nbsp;must each run in O(1) average time complexity.\n\n&nbsp;\nExample 1:\n\nInput\n[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n\nExplanation\n// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1);   // cache=[1,_], cnt(1)=1\nlfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1);      // return 1\n                 // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n&nbsp;                // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n                 // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4);      // return 4\n                 // cache=[4,3], cnt(4)=2, cnt(3)=3\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= capacity&nbsp;&lt;= 104\n\t0 &lt;= key &lt;= 105\n\t0 &lt;= value &lt;= 109\n\tAt most 2 * 105&nbsp;calls will be made to get and put.\n\n\n&nbsp;\n&nbsp;",
        "solution_py": "class Node:\n    \n    def __init__(self, key, val, cnt=1, nxxt=None, prev=None):\n        self.key = key\n        self.val = val\n        self.cnt = cnt\n        self.nxxt = nxxt\n        self.prev = prev\n        \n        \nclass NodeList(Node):\n    \n    def __init__(self):\n        self.head = Node(0,0)\n        self.tail = Node(0,0)\n        self.head.nxxt = self.tail\n        self.tail.prev = self.head\n        self.size = 0\n        \n        \n    def addFront(self, node):\n        temp = self.head.nxxt\n        self.head.nxxt = node\n        node.prev = self.head\n        node.nxxt = temp\n        temp.prev = node\n        \n        self.size += 1\n        \n        \n    def removeNode(self, node):\n        delprev = node.prev\n        delnxxt = node.nxxt\n        delprev.nxxt = delnxxt\n        delnxxt.prev = delprev\n        \n        self.size -= 1\n        \n\nclass LFUCache(NodeList):\n\n    def __init__(self, capacity: int):\n        self.keyNode = {}\n        self.freqNodeList = {}\n        self.maxSizeCache = capacity\n        self.currSize = 0\n        self.minFreq = 0\n        \n        \n    def updateFreqNodeList(self, node):\n        del self.keyNode[node.key]\n        nodelist = self.freqNodeList[node.cnt]\n        nodelist.removeNode(node)\n        \n        if node.cnt == self.minFreq and self.freqNodeList[node.cnt].size == 0:\n            self.minFreq += 1\n            \n        if (node.cnt+1) in self.freqNodeList:\n            nextHigherFreqNodeList = self.freqNodeList[node.cnt+1]\n        else:\n            nextHigherFreqNodeList = NodeList()\n            \n        node.cnt += 1\n        nextHigherFreqNodeList.addFront(node)\n        \n        self.freqNodeList[node.cnt] = nextHigherFreqNodeList\n        self.keyNode[node.key] = node\n        \n\n    def get(self, key: int) -> int:\n        if key in self.keyNode:\n            node = self.keyNode[key]\n            ans = node.val\n            self.updateFreqNodeList(node)\n            \n            return ans\n        \n        else:\n            return -1\n        \n\n    def put(self, key: int, value: int) -> None:\n        if self.maxSizeCache == 0:\n            return\n        \n        if key in self.keyNode:\n            node = self.keyNode[key]\n            node.val = value\n            self.updateFreqNodeList(node)\n            return\n        \n        else:\n            if self.currSize == self.maxSizeCache:\n                nodelist = self.freqNodeList[self.minFreq]\n                del self.keyNode[nodelist.tail.prev.key]\n                nodelist.removeNode(nodelist.tail.prev)\n                self.currSize -= 1\n                \n            self.currSize += 1\n            self.minFreq = 1\n            \n            if self.minFreq in self.freqNodeList:\n                nodelist = self.freqNodeList[self.minFreq]\n            else:\n                nodelist = NodeList()\n                \n            node = Node(key, value)\n            nodelist.addFront(node)\n            \n            self.keyNode[key] = node\n            self.freqNodeList[self.minFreq] = nodelist\n        \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)",
        "solution_js": "/**\n * @param {number} capacity\n */\nvar LFUCache = function(capacity) {\n    this.capacity = capacity;\n    this.cache = [];\n};\n\n/** \n * @param {number} key\n * @return {number}\n */\nLFUCache.prototype.get = function(key) {\n    let val = -1;\n    if (!this.capacity) return val;\n    const existIndex = this.cache.findIndex(item => item.key === key);\n    if (existIndex > -1) {\n        const item = this.cache[existIndex];\n        val = item.value;\n        item.count++;\n        this.cache.splice(existIndex, 1);\n        this.cache.unshift(item);\n    }\n    return val;\n};\n\n/** \n * @param {number} key \n * @param {number} value\n * @return {void}\n */\nLFUCache.prototype.put = function(key, value) {\n    if (!this.capacity) return;\n    const existIndex = this.cache.findIndex(item => item.key === key);\n    if (existIndex > -1) {\n        // new item already exists,rewrite the value and increase count\n        const existItem = this.cache[existIndex];\n        existItem.value = value;\n        existItem.count++;\n        this.cache.splice(existIndex, 1);\n        this.cache.unshift(existItem);\n    } else {\n        // new item doesn't exist\n        if (this.cache.length === this.capacity) {\n            // reach the capacity, need to clear LFU\n            let lfuIndex = 0;\n            let leastCount = this.cache[lfuIndex].count;\n            for (let i = 1; i < this.cache.length; i++) {\n                const item = this.cache[i];\n                if (item.count <= leastCount) {\n                    leastCount = item.count;\n                    lfuIndex = i;\n                }\n            }\n            this.cache.splice(lfuIndex, 1);\n            // after clear LFU, push the new item\n            this.cache.unshift({\n                key,\n                value,\n                count: 1\n            });\n        } else {\n            // new item can be pushed\n            this.cache.unshift({\n                key,\n                value,\n                count: 1\n            });\n        }\n    }\n};\n\n/** \n * Your LFUCache object will be instantiated and called as such:\n * var obj = new LFUCache(capacity)\n * var param_1 = obj.get(key)\n * obj.put(key,value)\n */",
        "solution_java": "\tclass LFUCache {\n    // Declare Node class for Doubly Linked List \n    class Node{\n        int key,value,freq;// to store key,value and frequency\n        Node prev,next;// Next and Previous Pointers\n        Node(int k,int v){\n        // initializing in constructor\n            key=k;\n            value=v;\n            freq=1;\n        }\n        \n    }\n    // Declare class for List of Doubly Linked List\n    class List{\n        int size;\n        Node head,tail;\n        List(){\n        // initializing in constructor\n            size=0;\n            head=new Node(-1,-1);// Default values\n            tail=new Node(-1,-1);\n            head.next=tail;\n            tail.prev=head;\n        }\n        // To insert at the start of the list\n        void ins(Node newNode){\n            Node temp=head.next;\n            head.next=newNode;\n            newNode.prev=head;\n            newNode.next=temp;\n            temp.prev=newNode;\n            size++;\n            \n        }\n        // To delete specific node\n        void del(Node newNode){\n            Node pr=newNode.prev;\n            Node nx=newNode.next;\n            pr.next=nx;\n            nx.prev=pr;\n            size--;\n        }\n    }\n    Map<Integer,Node>mp;// to store key and Node\n    Map<Integer,List>listMap;// to store frequency and Doubly Linked List\n    int maxSize,minFreq,currSize;// to store total size , minimum frequency and current size of the list\n    public LFUCache(int capacity) {\n        // initializing in constructor\n        maxSize=capacity;\n        minFreq=0;\n        currSize=0;\n        mp=new HashMap<Integer,Node>();\n        listMap=new HashMap<Integer,List>();\n    }\n    \n    public int get(int key) {\n        // if map contains the specific key \n        if(mp.containsKey(key)){\n            Node node=mp.get(key);\n            int val=node.value;\n            updateFreq(node);// to update the frequency of the node\n            return val;            \n        }\n        //otherwise\n        return -1;\n    }\n    \n    public void put(int key, int value) {\n        // one of the corner case\n        if(maxSize==0)\n            return;\n        // if map contains the specific key \n        if(mp.containsKey(key)){\n            Node node=mp.get(key);\n            node.value=value; // update the value of the node\n            updateFreq(node);// to update the frequency of the node\n        }\n        else{\n        // if current size is equal to spcified capacity of the LFU list\n            if(maxSize==currSize){\n                List list=listMap.get(minFreq);\n                mp.remove(list.tail.prev.key);// to remove the LRU of the LFU from key-node map\n                \n                // here LFU is list and even if its is a single element or multiple tail.prev(LRU) is the required element\n                \n                list.del(list.tail.prev);// to remove the LRU of the LFU from freq-list map\n                currSize--;\n            }\n            currSize++;\n            minFreq=1;// reset minFreq to 1 because of adding new node\n            List list= new List();\n            // If listMap already contains minFreq list\n            if(listMap.containsKey(minFreq)){\n                list=listMap.get(minFreq);\n            }\n            Node node = new Node(key,value);// creating a new node\n            list.ins(node); // inserting new node to the list\n            mp.remove(key); \n            mp.put(key,node); // inserting updated new node to the key-node map\n            listMap.remove(minFreq);\n            listMap.put(minFreq,list);// inserting updated list to the listMap        \n        }\n    }\n    public void updateFreq(Node newNode){\n        mp.remove(newNode.key);// to remove the node from key-node map\n        listMap.get(newNode.freq).del(newNode);// to remove the node from listmap\n        \n        // If node's freq was minimum and after removing it from the listMap, size is 0\n        if(newNode.freq==minFreq && listMap.get(newNode.freq).size==0){\n            minFreq++;\n        }\n        List higherFreqList= new List();\n        // If listMap already contains node's freq +1 th list\n        if(listMap.containsKey(newNode.freq+1)){\n            higherFreqList= listMap.get(newNode.freq+1);\n        }\n        newNode.freq++; // updating node's frequency\n        higherFreqList.ins(newNode); // inserting node to list\n        listMap.remove(newNode.freq);\n        listMap.put(newNode.freq,higherFreqList);// reinserting list to listMap\n        mp.remove(newNode.key);\n        mp.put(newNode.key,newNode);// reinserting node to key-node map\n    }\n}",
        "solution_c": "class list_node {\npublic:\n    int key, val, cnt;\n    list_node* next;\n    list_node* prev;\n    list_node(int k, int v, list_node* n, list_node* p) {\n        key = k; val = v; cnt = 1;\n        next = n; prev = p;\n    }\n};\nclass LFUCache {\npublic:\n    int min_cnt;\n    bool zero;\n    unordered_map<int, list_node*> key2node;\n    unordered_map<int, pair<list_node*, list_node*>> cnt2list;\n    LFUCache(int capacity) {\n        cin.tie(0); ios_base::sync_with_stdio(0);\n        min_cnt = 0;\n        c = capacity;\n        zero = (c == 0);\n    }\n    \n    int get(int key) {\n        if(zero) return -1;\n        auto it = key2node.find(key);\n        if(it == key2node.end() || it->second == NULL) return -1;\n        addcnt(key);\n        return it->second->val;\n    }\n    \n    void put(int key, int value) {\n        if(zero) return;\n        auto it = key2node.find(key);\n        if(it != key2node.end() && it->second != NULL) {\n            addcnt(key);\n            it->second->val = value;\n            return;\n        }\n        if(c) --c;\n        else {\n            key2node[cnt2list[min_cnt].first->key] = NULL;\n            list_node* tmp = cnt2list[min_cnt].first;\n            if(tmp->next) tmp->next->prev = NULL;\n            cnt2list[min_cnt].first = tmp->next;\n            if(cnt2list[min_cnt].second == tmp) cnt2list[min_cnt].second = NULL; \n        }\n\n        min_cnt = 1;\n        list_node* node = new list_node(key, value, NULL, NULL);\n        key2node[key] = node;\n        if(cnt2list.find(1) == cnt2list.end() || cnt2list[1].first == NULL) {\n            cnt2list[1].first = cnt2list[1].second = node;\n        }\n        else {\n            node->prev = cnt2list[1].second;\n            cnt2list[1].second->next = node;\n            cnt2list[1].second = node;\n        }\n    }\nprivate:\n    int c;\n    void addcnt(int key) {\n        if(cnt2list[key2node[key]->cnt].first == key2node[key]) \n            cnt2list[key2node[key]->cnt].first = key2node[key]->next;\n        if(cnt2list[key2node[key]->cnt].second == key2node[key]) \n            cnt2list[key2node[key]->cnt].second = key2node[key]->prev;\n        if(min_cnt == key2node[key]->cnt && cnt2list[key2node[key]->cnt].first == NULL) min_cnt++;\n        key2node[key]->cnt++;\n        if(key2node[key]->prev) key2node[key]->prev->next = key2node[key]->next;\n        if(key2node[key]->next) key2node[key]->next->prev = key2node[key]->prev;\n        key2node[key]->next = NULL;\n        auto lit = cnt2list.find(key2node[key]->cnt);\n        if(lit == cnt2list.end() || lit->second.first == NULL) {\n            cnt2list[key2node[key]->cnt].first = cnt2list[key2node[key]->cnt].second = key2node[key];\n            key2node[key]->prev = NULL;\n        }\n        else {\n            key2node[key]->prev = cnt2list[key2node[key]->cnt].second;\n            cnt2list[key2node[key]->cnt].second->next = key2node[key];\n            cnt2list[key2node[key]->cnt].second = key2node[key];\n        }\n    }\n};"
    },
    {
        "title": "Longest Common Prefix",
        "algo_input": "Write a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n&nbsp;\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= strs.length &lt;= 200\n\t0 &lt;= strs[i].length &lt;= 200\n\tstrs[i] consists of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestCommonPrefix(self, strs: List[str]) -> str:\n        cmp=strs[0]\n        for i in range(1,len(strs)):\n            l=0\n            if (len(cmp)>len(strs[i])):\n                l+=len(strs[i])\n            else:\n                l+=len(cmp)\n            ans=\"\"\n            for j in range(l):\n                if (cmp[j]!=strs[i][j]):\n                    if (j==0):\n                        return \"\"\n                    else:\n                        break\n                else:\n                    ans+=strs[i][j]\n            cmp=ans\n        return cmp\n\t\t\nUpvote If you Like!!!",
        "solution_js": " var longestCommonPrefix = function(strs) {\n let commonStr=strs[0];\n for(let i=1; i<strs.length;i++){\n   let currentStr= strs[i]\n    for(let j=0; j<commonStr.length;j++){\n      if (commonStr[j]!==currentStr[j]){\n          commonStr=currentStr.slice(0,j)  \n          break;\n      }\n    }\n}   \nreturn commonStr ",
        "solution_java": "class TrieNode{\n    TrieNode[] childs;\n    int frequency;\n    TrieNode(){\n        childs = new TrieNode[26];\n        this.frequency = 1;\n    }\n}\n\nclass Solution {\n\n    TrieNode root = new TrieNode();\n\n    public String longestCommonPrefix(String[] strs) {\n        if(strs.length == 0) return \"\";\n        if(strs.length == 1) return strs[0];\n        for(String str : strs){\n            insertIntoTrie(str.toLowerCase());\n        }\n        return findCommonPrefix(strs[0], strs.length);\n    }\n\n    private void insertIntoTrie(String str) {\n        TrieNode ptr = root;\n        for(int i=0; i<str.length(); i++){\n            if(ptr.childs[str.charAt(i)-'a'] == null){\n                ptr.childs[str.charAt(i)-'a'] = new TrieNode();\n            } else {\n                ptr.childs[str.charAt(i)-'a'].frequency++;\n            }\n            ptr = ptr.childs[str.charAt(i)-'a'];\n        }\n    }\n\n    private String findCommonPrefix(String str, int n) {\n        String ans = \"\";\n        for(int i=0; i<str.length(); i++){\n            if(root.childs[str.charAt(i) -'a'].frequency != n){\n                return ans;\n            }\n            ans += str.charAt(i);\n            root = root.childs[str.charAt(i)-'a'];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string longestCommonPrefix(vector<string>& strs) {\n        //brute\n        string ans=\"\";\n        string ref=strs[0];\n        for(int i=0;i<ref.size();i++)\n        {\n            int j=1;\n            for(;j<strs.size();j++)\n            {\n                if(ref[i]!=strs[j][i])\n                    break;\n            }\n            if(j==strs.size())\n                ans+=ref[i];\n            else\n                break;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Recent Calls",
        "algo_input": "You have a RecentCounter class which counts the number of recent requests within a certain time frame.\n\nImplement the RecentCounter class:\n\n\n\tRecentCounter() Initializes the counter with zero recent requests.\n\tint ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].\n\n\nIt is guaranteed that every call to ping uses a strictly larger value of t than the previous call.\n\n&nbsp;\nExample 1:\n\nInput\n[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]\nOutput\n[null, 1, 2, 3, 3]\n\nExplanation\nRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1);     // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100);   // requests = [1, 100], range is [-2900,100], return 2\nrecentCounter.ping(3001);  // requests = [1, 100, 3001], range is [1,3001], return 3\nrecentCounter.ping(3002);  // requests = [1, 100, 3001, 3002], range is [2,3002], return 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= t &lt;= 109\n\tEach test case will call ping with strictly increasing values of t.\n\tAt most 104 calls will be made to ping.\n\n",
        "solution_py": "class RecentCounter:\n    # Here we use list to store ping details.\n    def __init__(self):\n        self.store = []\n\n    def ping(self, t: int) -> int:\n        # Basically what we need to return is how many pings fall in the range(t-3000, t).\n        # So here we append every t. Now in loop how many t from left side < t-3000, we just pop them\n        # and return the length of the list, which'd contain elements in range(t-3000, t).\n        # And since every t is going to greater than previous, we don't need to think about duplicates.\n\n        self.store.append(t)\n\n        while self.store[0] < t-3000:\n            self.store.pop(0)\n\n        return len(self.store)",
        "solution_js": "var RecentCounter = function() {\n    this.arr = [];\n};\n\nRecentCounter.prototype.ping = function(t) {\n    this.arr.push(t);\n    while(t > this.arr[0]+3000){\n        this.arr.shift();\n    }\n    return this.arr.length;\n};",
        "solution_java": "class RecentCounter {\n    ArrayList<Integer> calls ;\n    public RecentCounter() {\n        calls = new ArrayList<Integer>();\n        }\n    \n    public int ping(int t) {\n        calls.add(t);\n        int count = 0;\n        for(Integer call:calls){\n            if( t-call<=3000) count++;\n        }\n        return count;\n        \n    }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */",
        "solution_c": "class RecentCounter {\npublic:\n    queue<int> q;\n    RecentCounter() {\n    }\n\n    int ping(int t) {\n        q.push(t);\n        int x = q.front();\n        while(x < t-3000){\n            q.pop(); x = q.front();\n        }\n        return q.size();\n    }\n};"
    },
    {
        "title": "Count Substrings That Differ by One Character",
        "algo_input": "Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.\n\nFor example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way.\n\nReturn the number of substrings that satisfy the condition above.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aba\", t = \"baba\"\nOutput: 6\nExplanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.\n\n​​Example 2:\n\nInput: s = \"ab\", t = \"bb\"\nOutput: 3\nExplanation: The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, t.length &lt;= 100\n\ts and t consist of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def countSubstrings(self, s: str, t: str) -> int:\n        res = 0\n        for i in range(len(s)):\n            for j in range(len(t)):\n                miss, pos = 0, 0\n                while i + pos < len(s) and j + pos < len(t) and miss < 2:\n                    miss += s[i + pos] != t[j + pos]\n                    res += miss == 1\n                    pos += 1\n        return res",
        "solution_js": "var countSubstrings = function(s, t) {\n    const count1 = countAllSubstr(s);\n    const count2 = countAllSubstr(t);\n\n    let res = 0;\n\n    for (const [substr1, freq1] of count1) {\n       for (const [substr2, freq2] of count2) {\n\n           if (differByOneChar(substr1, substr2)) {\n               res += freq1 * freq2;\n           }\n       }\n    }\n\n    return res;\n\n    function countAllSubstr(str) {\n        const n = str.length;\n        const count = new Map();\n\n        for (let i = 0; i < n; i++) {\n            let substr = \"\";\n            for (let j = i; j < n; j++) {\n                substr += str.charAt(j);\n\n                if (!count.has(substr)) count.set(substr, 0);\n                count.set(substr, count.get(substr) + 1);\n            }\n        }\n\n        return count;\n    }\n\n    function differByOneChar(str1, str2) {\n        if (str1.length != str2.length) return false;\n\n        const n = str1.length;\n\n        let missed = 0;\n\n        for (let i = 0; i < n; i++) {\n            const char1 = str1.charAt(i);\n            const char2 = str2.charAt(i);\n\n            if (char1 != char2) missed++;\n\n            if (missed > 1) return false;\n        }\n\n        return missed === 1;\n    }\n\n};",
        "solution_java": "// version 1 : O(mn) space\nclass Solution {\n    public int countSubstrings(String s, String t) {\n        int m = s.length(), n = t.length();\n\n        int[][][] dp = new int[m][n][2];\n        \n        int res = 0;\n        // first col s[0:i] match t[0:0]\n        for (int i = 0; i < m; i++) {\n            dp[i][0][0] = (s.charAt(i) == t.charAt(0)) ? 1 : 0;\n            dp[i][0][1] = (s.charAt(i) == t.charAt(0)) ? 0 : 1;\n            res += dp[i][0][1];\n        }\n      \n        \n        // first row s[0:0] match t[0:j]\n        for (int j = 1; j < n; j++) {\n            dp[0][j][0] = (s.charAt(0) == t.charAt(j)) ? 1 : 0;\n            dp[0][j][1] = (s.charAt(0) == t.charAt(j)) ? 0 : 1;\n            res += dp[0][j][1];\n        }\n        \n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                dp[i][j][0] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][0] + 1 : 0;\n                dp[i][j][1] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][1] : dp[i-1][j-1][0] + 1;\n                res += dp[i][j][1];\n            }\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countSubstrings(string s, string t)\n    {\n        int n=s.size();\n        int m=t.size();\n        int ans=0;\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<m;j++)\n            {\n                int diff=0;\n                for(int k=0;i+k<n&&j+k<m;k++)\n                {\n                    if(s[i+k]!=t[j+k])\n                    {\n                        diff++;\n                    }\n                    if(diff>1)\n                    {\n                        break;\n                    }\n                    ans+=diff;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Design Linked List",
        "algo_input": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list.\nA node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.\nIf you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.\n\nImplement the MyLinkedList class:\n\n\n\tMyLinkedList() Initializes the MyLinkedList object.\n\tint get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.\n\tvoid addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.\n\tvoid addAtTail(int val) Append a node of value val as the last element of the linked list.\n\tvoid addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.\n\tvoid deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]\nOutput\n[null, null, null, null, 2, null, 3]\n\nExplanation\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2);    // linked list becomes 1-&gt;2-&gt;3\nmyLinkedList.get(1);              // return 2\nmyLinkedList.deleteAtIndex(1);    // now the linked list is 1-&gt;3\nmyLinkedList.get(1);              // return 3\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= index, val &lt;= 1000\n\tPlease do not use the built-in LinkedList library.\n\tAt most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.\n\n",
        "solution_py": "class Node:\n    def __init__(self, val: int):\n        self.val = val\n        self.next = None\n        self.prev = None\n        \nclass MyLinkedList:\n    def __init__(self):\n        self.head = Node(0)\n        self.tail = Node(0)\n        self.head.next = self.tail\n        self.tail.prev = self.head\n        self.size = 0\n        \n    def get(self, index: int) -> int:\n        if index < 0 or index >= self.size:\n            return -1\n        # Distance of index is closer to head\n        if index + 1 < self.size - index:\n            curr = self.head\n            for i in range(index + 1):\n                curr = curr.next\n        # Distance of index is closer to tail\n        else:\n            curr = self.tail\n            for i in range(self.size - index):\n                curr = curr.prev\n        return curr.val\n\n    def addAtHead(self, val: int) -> None:\n        curr = Node(val)\n        prevNode = self.head\n        nextNode = self.head.next\n        self.size += 1\n        curr.prev = prevNode\n        curr.next = nextNode\n        prevNode.next = curr\n        nextNode.prev = curr\n\n    def addAtTail(self, val: int) -> None:\n        curr = Node(val)\n        prevNode = self.tail.prev\n        nextNode = self.tail\n        self.size += 1\n        curr.prev = prevNode\n        curr.next = nextNode\n        prevNode.next = curr\n        nextNode.prev = curr\n\n    def addAtIndex(self, index: int, val: int) -> None:\n        curr = Node(val)\n        if index > self.size:\n            return\n        if index < 0:\n            index = 0\n        if index < self.size - index:\n            prevNode = self.head\n            for i in range(index):\n                prevNode = prevNode.next\n            nextNode = prevNode.next\n        else:\n            nextNode = self.tail\n            for i in range(self.size - index):\n                nextNode = nextNode.prev\n            prevNode = nextNode.prev\n        self.size += 1\n        curr.prev = prevNode\n        curr.next = nextNode\n        prevNode.next = curr\n        nextNode.prev = curr\n        \n    def deleteAtIndex(self, index: int) -> None:\n        if index < 0 or index >= self.size:\n            return \n        if index < self.size - index:\n            prevNode = self.head\n            for i in range(index):\n                prevNode = prevNode.next\n            nextNode = prevNode.next.next\n        else:\n            nextNode = self.tail\n            for i in range(self.size - index - 1):\n                nextNode = nextNode.prev\n            prevNode = nextNode.prev.prev\n        self.size -= 1\n        prevNode.next = nextNode\n        nextNode.prev = prevNode\n\n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)",
        "solution_js": "var MyLinkedList = function() {\n    this.linked = [];\n};\n\nMyLinkedList.prototype.get = function(index) {\n    if(index < this.linked.length){\n        return this.linked[index];\n    }\n    return -1;\n};\n\nMyLinkedList.prototype.addAtHead = function(val) {\n    this.linked.unshift(val);\n};\n\nMyLinkedList.prototype.addAtTail = function(val) {\n    this.linked.push(val);\n};\n\nMyLinkedList.prototype.addAtIndex = function(index, val) {\n    if(index <= this.linked.length){\n        this.linked.splice(index,0,val);\n    }\n};\n\nMyLinkedList.prototype.deleteAtIndex = function(index) {\n    this.linked.splice(index,1);\n};",
        "solution_java": "class MyLinkedList {\n\n    public class ListNode {\n        public int val;\n        public ListNode next;\n\n        public ListNode() {\n\n        }\n\n        public ListNode(int val) {\n            this.val = val;\n        }\n\n        public ListNode(int val, ListNode next) {\n            this.val = val;\n            this.next = next;\n        }\n    }\n\n    private ListNode head;\n    private ListNode tail;\n    private int length;\n\n    public MyLinkedList() {\n        length = 0;\n    }\n\n    public int get(int index) {\n        if (index > length - 1 || index < 0) return -1;\n        int thisIndex = 0;\n        ListNode temp = head;\n        while (thisIndex != index) {\n            temp = temp.next;\n            thisIndex++;\n        }\n        return temp.val;\n    }\n\n    public void addAtHead(int val) {\n        head = new ListNode(val, head);\n        length++;\n        if (length == 1) tail = head;\n    }\n\n    public void addAtTail(int val) {\n        length++;\n        if (length == 1) {\n            ListNode onlyNode = new ListNode(val);\n            head = onlyNode;\n            tail = head;\n            return;\n        }\n        tail.next = new ListNode(val);\n        tail = tail.next;\n    }\n\n    public void addAtIndex(int index, int val) {\n        if (index <= length) {\n            if (index == 0) {\n                addAtHead(val);\n                return;\n            }\n            if (index == length) {\n                addAtTail(val);\n                return;\n            }\n            length++;\n            ListNode temp = head;\n            int thisIndex = 0;\n            while (thisIndex != index - 1) {\n                temp = temp.next;\n                thisIndex++;\n            }\n            temp.next = new ListNode(val, temp.next);\n        }\n    }\n\n    public void deleteAtIndex(int index) {\n        if (index >= length || index < 0) return;\n        length--;\n        if (index == 0) {\n            head = head.next;\n            return;\n        }\n        ListNode temp = head;\n        int thisIndex = 0;\n        while (thisIndex != index - 1) {\n            temp = temp.next;\n            thisIndex++;\n        }\n        if (index == length) {\n            tail = temp;\n            temp.next = null;\n        }\n        else temp.next = temp.next.next;\n    }\n}",
        "solution_c": "class MyLinkedList {\n    struct Node{\n        int val;\n        Node *next,*prev;\n        Node(int x){val=x,next=prev=NULL;}\n    };\n    Node *head;int size;\npublic:\n    MyLinkedList() {\n        head=NULL;size=0;\n    }\n    \n    int get(int index) {\n        if(index>=size or index<0) return -1;\n        Node *ptr=head;\n        for(int i=0;i<index;i++) ptr=ptr->next;\n        return ptr->val;\n    }\n    \n    void addAtHead(int val) {\n        Node *newNode=new Node(val);\n        newNode->next=head;\n        if(head) head->prev=newNode;\n        head=newNode;\n        size++;\n    }\n    \n    void addAtTail(int val) {\n        addAtIndex(size,val);\n    }\n    \n    void addAtIndex(int index, int val) {\n        if(index<0 or index>size) return;\n        if(index==0){\n            addAtHead(val);return;\n        }\n        Node *newNode=new Node(val);\n        Node *prev=head;\n        for(int i=0;i<index-1;i++){\n            prev=prev->next;\n        }\n        newNode->next=prev->next;\n        prev->next=newNode;\n        newNode->prev=prev;\n        if(newNode->next) newNode->next->prev=newNode;\n        size++;\n    }\n    \n    void deleteAtIndex(int index) {\n        if(index>=size or index<0) return;\n        if(index==0){\n            Node *temp=head;\n            head=head->next;\n            delete temp;size--;\n            return;\n        }\n        Node *del=head;\n        for(int i=0;i<index;i++){\n            del=del->next;\n        }\n        if(del->prev) del->prev->next=del->next;\n        if(del->next) del->next->prev=del->prev;\n        delete del;\n        size--;\n    }\n};"
    },
    {
        "title": "Range Sum Query - Mutable",
        "algo_input": "Given an integer array nums, handle multiple queries of the following types:\n\n\n\tUpdate the value of an element in nums.\n\tCalculate the sum of the elements of nums between indices left and right inclusive where left &lt;= right.\n\n\nImplement the NumArray class:\n\n\n\tNumArray(int[] nums) Initializes the object with the integer array nums.\n\tvoid update(int index, int val) Updates the value of nums[index] to be val.\n\tint sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\nOutput\n[null, 9, null, 8]\n\nExplanation\nNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2);   // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-100 &lt;= nums[i] &lt;= 100\n\t0 &lt;= index &lt; nums.length\n\t-100 &lt;= val &lt;= 100\n\t0 &lt;= left &lt;= right &lt; nums.length\n\tAt most 3 * 104 calls will be made to update and sumRange.\n\n",
        "solution_py": "class NumArray:\n    nums = []\n    s = 0\n    l = 0\n    \n    def __init__(self, nums: List[int]):\n        self.nums = nums\n        self.s = sum(nums)\n        self.l = len(nums)\n\n    def update(self, index: int, val: int) -> None:\n        self.s -= self.nums[index]\n        self.nums[index] = val\n        self.s += self.nums[index]\n\n    def sumRange(self, left: int, right: int) -> int:\n        if right - left > self.l // 2:\n            ans = sum(self.nums[:left]) + sum(self.nums[right + 1:])\n            return self.s - ans\n        else:\n            return sum(self.nums[left: right + 1])",
        "solution_js": "var NumArray = function(nums) {\n    this.nums = nums;\n    this.n = nums.length;\n    this.fenwickTree = new Array(this.n + 1).fill(0);\n    nums.forEach((num, index) => this.init(index, num));\n};\n\nNumArray.prototype.init = function(index, val) {\n    let j = index + 1;\n    while(j <= this.n) {\n        this.fenwickTree[j] += val;\n        j += this.lsb(j);\n    }\n};\n\nNumArray.prototype.lsb = function(index) {\n    return index & ~(index - 1);\n};\n\nNumArray.prototype.update = function(index, val) {\n    const diff = val - this.nums[index];\n    this.nums[index] = val;\n    this.init(index, diff);\n};\n\nNumArray.prototype.getSum = function(index) {\n    let j = index + 1;\n    let sum = 0;\n\n    while(j > 0) {\n        sum += this.fenwickTree[j];\n        j -= this.lsb(j);\n    }\n\n    return sum;\n};\n\nNumArray.prototype.sumRange = function(left, right) {\n    return this.getSum(right) - this.getSum(left - 1);\n};",
        "solution_java": "class NumArray {\n    SegmentTree s;\n    public NumArray(int[] nums) {\n        s = new SegmentTree(nums);\n        s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built\n    }\n    \n    public void update(int index, int val) {\n        int oldvalue = s.arr[index];//Find old value with traditional array, which is O(1) time complexity\n        s.arr[index] = val;//Set our array so that there will be no contradictions if we ever rebuild.\n        //If we are going use build function only once, then we don't need to update our traditional array. \n        s.update(s.root, val, index, oldvalue);//Call class' function\n    }\n    \n    public int sumRange(int left, int right) {\n        return s.rangeSum(s.root, left, right);\n    }\n}\n\nclass Node {\n    int s;//inclusive label\n    int e;//inclusive label\n    int val;\n    Node left;\n    Node right;\n}\n\nclass SegmentTree {\n    Node root;\n    int[] arr;\n\n    SegmentTree(int [] arr) {\n        this.arr = arr;\n    }\n\n    public Node build(int start, int end, int[] arr) {\n        //Start and End integers have nothing to do with building of our SegmentTree, you may ignore them for now\n        //They are needed for querying and updating, so that we can use binary search.\n        Node temp = new Node();\n        if (arr.length == 1) {//which means we are setting a node equal to an element of arr\n            temp.val = arr[0];\n            temp.s = start;\n            temp.e = end-1;//to make it inclusive\n        } else if (arr.length == 0 || start > end || start < 0 || end < 0) {\n            return new Node();// may be better\n        } else {\n            //left = build(start, mid but add 1 if array's length is not divisible by 2, left half of the passed array)\n            temp.left = build(start, (start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), Arrays.copyOfRange(arr, 0, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0)));\n            //right = build(start, mid but add 1 if array's length is not divisible by 2, right half of the passed array)\n            temp.right = build((start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), end, Arrays.copyOfRange(arr, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0), arr.length));\n            temp.val = temp.left.val + temp.right.val;\n            temp.s = start;\n            temp.e = end-1;//to make it inclusive\n        }\n        return temp;//return this Node to one upper call so that this can be a child of it's parent\n    }\n    \n    public int rangeSum(Node node, int l, int r) {\n        if(node == null)\n        {\n            //Range is completely outside given range\n            return 0;\n        }\n        if(l <= node.s && node.e <= r)\n        {\n            //Range is completely inside given range\n            return node.val;\n        }\n        //Range is partially inside and partially outside the given range\n        int mid = (node.s + node.e) / 2;\n        int left = 0;\n        int right = 0;\n        if (l <= mid) {\n            //For example let's say root's borders are 0:3, l,r=1:2\n            //Then mid will be 1, then we will go into both directions because 1<=1, and 2>=1\n            //Our next calls will be rS(root.left(which is 0:1), 1, 2) and rS(root.right(which is 2:3), 1, 2)\n            //Left call's mid will be mid = (0+1)/2 = 0\n            //Then 1<=0 ? No it's not, this is why left call's variable named left will be 0\n            //Then 2>=0 ? Yes, we will call rS(root.left.right(which is 1:1), 1, 2)\n            //Our left call's right call:\n            //1:1 is completely inside 1:2, return the value it holds(equals to arr[1] if our arr is up to date)\n            //Our original call's left will be arr[1]\n            //Let's calculate our first right function\n            //With same reasoning, our right function will go to left and be root.right.left(which is 2:2)\n            //Our original call's right will be arr[2]\n            //Our original/first function will return left + right, which is in fact [1:2] inclusive\n            left = rangeSum(node.left, l, r);\n        } \n        if (r >= mid) {\n            right = rangeSum(node.right, l, r);\n        }\n        return (left + right);\n    }\n    //What we are doing is, going downwards in our tree while we update the values we touch upon\n    //We need to update root always, since it is sum of every element\n    //After that we find mid which is mid value of our current node's start and end(inclusive)\n    //At first call this will be (0+arr.length)/2 => mid\n    //If given idx is bigger than mid, then we need to keep searching at right branch\n    //That is why we call the function with root.right as our new root\n    //If given idx is smaller and equals to mid, then we search at left branch\n    //Why did we include equality too? Because I built my tree this way.(where equal things go left)\n    //If idx is between our root's borders then we will decrease by the old value, increase by the new value.\n    //If root equals null, we won't do anything\n    //We update our traditional array at above.\n    public void update(Node root, int value, int idx, int oldvalue) {\n        if (root == null) {\n            return;\n        }\n        int mid = (root.e + root.s) / 2;\n        if (idx <= root.e && idx >= root.s) {\n            root.val -= oldvalue;\n            root.val += value;\n        } if (idx > mid) {\n            update(root.right, value, idx, oldvalue);\n        } else if (idx <= mid) {\n            update(root.left, value, idx, oldvalue);\n        }\n    }\n}",
        "solution_c": "class NumArray {\npublic:\n    vector<int>v; //vector to store input vector.\n    int sum; //sum of all element of vector \n    NumArray(vector<int>& nums) {\n        v=nums;\n        sum=0;\n        for(int i=0;i<nums.size();i++){\n            sum+=nums[i];\n        }\n    }\n    \n    void update(int index, int val) {\n        sum-=v[index];     //subtract old element  from sum at index and then update by adding new element val.\n        v[index]=val;\n        sum+=val;\n        \n    }\n    \n    int sumRange(int left, int right) {\n        int res=sum; \n        for(int i=0;i<left;i++){    //subtract all element before left and after right\n            res-=v[i];\n        }\n        for(int i=right+1;i<v.size();i++){\n            res-=v[i];\n        }\n        return res;// return res ie. our answer.\n    }\n};"
    },
    {
        "title": "Make Two Arrays Equal by Reversing Sub-arrays",
        "algo_input": "You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.\n\nReturn true if you can make arr equal to target&nbsp;or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: target = [1,2,3,4], arr = [2,4,1,3]\nOutput: true\nExplanation: You can follow the next steps to convert arr to target:\n1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.\n\n\nExample 2:\n\nInput: target = [7], arr = [7]\nOutput: true\nExplanation: arr is equal to target without any reverses.\n\n\nExample 3:\n\nInput: target = [3,7,9], arr = [3,7,11]\nOutput: false\nExplanation: arr does not have value 9 and it can never be converted to target.\n\n\n&nbsp;\nConstraints:\n\n\n\ttarget.length == arr.length\n\t1 &lt;= target.length &lt;= 1000\n\t1 &lt;= target[i] &lt;= 1000\n\t1 &lt;= arr[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n        target.sort()\n        arr.sort()\n        if len(target)==len(arr):\n            if target==arr:\n                return True\n            else:\n                return False",
        "solution_js": "var canBeEqual = function(target, arr) {\n    if(arr.length==1){\n        if(arr[0]===target[0]){\n            return true\n        }\n    }\n    let obj = {}\n    for(let i =0;i<arr.length; i ++){\n        if(obj[arr[i]]==undefined){\n            obj[arr[i]]=1\n        }else{\n            obj[arr[i]]++\n        }\n    }\n    for(let i =0;i<target.length; i ++){\n        if(obj[target[i]]==undefined){\n            return false\n        }else{\n            obj[target[i]]++\n        }\n    }\n   let result = Object.values(obj)\n   \n   for(let i =0; i <result.length; i ++){\n       if(result[i]%2!==0){\n           return false\n       }\n   }\n    return true\n};",
        "solution_java": "class Solution {\n    public boolean canBeEqual(int[] target, int[] arr) {\n        HashMap<Integer,Integer>hm1=new HashMap();\n        for(int i: arr){\n            if(hm1.containsKey(i))\n                hm1.put(i,hm1.get(i)+1);\n            else\n                hm1.put(i,1);\n        }\n        for(int i: target){\n            if(hm1.containsKey(i)){\n                hm1.put(i,hm1.getOrDefault(i,0)-1);\n                if(hm1.get(i)==0)\n                    hm1.remove(i);\n            }\n            else\n                return false;\n            \n        }\n        if(hm1.size()==0)\n            return true;\n        \n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canBeEqual(vector<int>& target, vector<int>& arr) {\n        int arr1[1001]={0};\n        int arr2[1001]={0};\n        \n        for(int i =0 ; i<target.size(); i++)\n        {\n            arr1[arr[i]]++;\n            arr2[target[i]]++;\n        }\n        \n        for(int i =0 ;i<=1000;i++)\n        {\n            if(arr1[i]!=arr2[i])\n                return false;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Minimum Difficulty of a Job Schedule",
        "algo_input": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 &lt;= j &lt; i).\n\nYou have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.\n\nYou are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].\n\nReturn the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n\n&nbsp;\nExample 1:\n\nInput: jobDifficulty = [6,5,4,3,2,1], d = 2\nOutput: 7\nExplanation: First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7 \n\n\nExample 2:\n\nInput: jobDifficulty = [9,9,9], d = 4\nOutput: -1\nExplanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n\n\nExample 3:\n\nInput: jobDifficulty = [1,1,1], d = 3\nOutput: 3\nExplanation: The schedule is one job per day. total difficulty will be 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= jobDifficulty.length &lt;= 300\n\t0 &lt;= jobDifficulty[i] &lt;= 1000\n\t1 &lt;= d &lt;= 10\n\n",
        "solution_py": "class Solution:\n    def solve(self, nums, index, d):\n        if index == len(nums) or d == 1:\n            #print(max(nums[index:]))\n            return max(nums[index:])\n        ans = float(\"inf\")\n        for i in range(index, len(nums)-d+1):\n            curr = max(nums[index:i+1]) + self.solve(nums, i+1, d-1)\n            ans = min(ans, curr)\n        return ans\n    \n    def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n        ans = self.solve(jobDifficulty, 0, d)\n        if ans == float(\"inf\"):\n            return -1\n        else:\n            return ans",
        "solution_js": "var minDifficulty = function(jobDifficulty, d) {\n    // don't have enought jobs to distribute\n    if (jobDifficulty.length < d) {\n        return -1;\n    }\n\n    // in dynamic programming top-down approach\n    // we need to have memoisation to not repeat calculations\n    let memo = new Array(d+1).fill(-1).map(\n        () => new Array(jobDifficulty.length+1).fill(-1)\n    )\n\n    const dp = function(D, N) {\n\n        // if we calculated this before, just return\n        if (-1 != memo[D][N]) {\n            return memo[D][N];\n        }\n\n        // if we have only 1 day, we just need to take all jobs\n        // and return the highest difficulty\n        if (1 == D) {\n            memo[D][N] = 0;\n            for (let i = 0; i < N; i++) {\n                if (memo[D][N] < jobDifficulty[i]) {\n                    memo[D][N] = jobDifficulty[i];\n                }\n            }\n            return memo[D][N];\n        }\n\n        // otherwise, we use our recurrence relation to calculate\n        memo[D][N] = 1000 * D;\n\n        let max_job_per_day = N - D + 1;\n        let max_difficulty = 0;\n\n        // iteration for recurrence relation\n        for (let X = 1; X <= max_job_per_day; X++) {\n            // count max in the current range\n            // len - X is the starting point for\n            // the last day in D days\n            if (jobDifficulty[N - X] > max_difficulty) {\n                max_difficulty = jobDifficulty[N - X];\n            }\n            // recurrence relation\n            // we took X jobs,\n            // so we still have N - X jobs for D - 1 days\n            let min_sum = max_difficulty + dp(D - 1, N - X);\n\n            // pick the min only\n            if (min_sum < memo[D][N]) {\n                memo[D][N] = min_sum;\n            }\n        }\n\n        return memo[D][N];\n    }\n\n    return dp(d, jobDifficulty.length);\n}",
        "solution_java": "class Solution {\n    // Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray.\n    public int minDifficulty(int[] jobDifficulty, int d) {\n        if(d>jobDifficulty.length){\n            return -1;\n        }\n        \n        int[][] memo = new int[d+1][jobDifficulty.length];\n        for(int[] m : memo){\n            Arrays.fill(m, -1);\n        }\n        \n        return getMinDays(jobDifficulty, d, memo, 0);\n    }\n    \n    private int getMinDays(int[] jobDifficulty, int d, int[][] memo, int idx){\n        if(d==1){\n            int max=0;\n            while(idx < jobDifficulty.length){\n                max=Math.max(max, jobDifficulty[idx]);\n                idx++;\n            }\n            return max;\n        }\n        \n        if(memo[d][idx] != -1) return memo[d][idx];\n        \n        int max=0;\n        int res=Integer.MAX_VALUE;\n        // [6,5,4,3,2,1], d=5 => we don't want the cut at 4th position in the array because we won't be able to divide it into 5 parts\n        for(int i=idx; i<jobDifficulty.length-d+1; i++){\n            max = Math.max(max, jobDifficulty[i]);\n            res = Math.min(res, max + getMinDays(jobDifficulty, d-1, memo, i+1));\n        }\n        \n        memo[d][idx]=res;\n        return memo[d][idx];\n    }\n}",
        "solution_c": "class Solution {\n    vector<int> v;\n    int len;\n    int dp[301][11];\n    int dfs(int idx, int d){//n*d\n        if(idx>=len)\n            return 0;\n        if(d==1)\n            return *max_element(v.begin()+idx,v.end());\n        if(dp[idx][d]!=-1)\n            return dp[idx][d];\n        int maxx=INT_MIN;\n        int res=INT_MAX;\n        for(int i=idx;i<=len-d;i++){//n\n            maxx=max(v[i],maxx);\n            res=min(maxx+dfs(i+1,d-1),res);\n        }\n        return dp[idx][d]=res;\n    }\npublic:\n    int minDifficulty(vector<int>& jobDifficulty, int d) {\n        v=jobDifficulty;\n        len=v.size();\n        if(d>len)\n            return -1;\n        memset(dp,-1,sizeof(dp));\n        return dfs(0,d);\n    }\n};"
    },
    {
        "title": "Path With Minimum Effort",
        "algo_input": "You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e.,&nbsp;0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.\n\nA route's effort is the maximum absolute difference in heights between two consecutive cells of the route.\n\nReturn the minimum effort required to travel from the top-left cell to the bottom-right cell.\n\n&nbsp;\nExample 1:\n\n\n\nInput: heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput: 2\nExplanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n\n\nExample 2:\n\n\n\nInput: heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput: 1\nExplanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n\n\nExample 3:\n\nInput: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput: 0\nExplanation: This route does not require any effort.\n\n\n&nbsp;\nConstraints:\n\n\n\trows == heights.length\n\tcolumns == heights[i].length\n\t1 &lt;= rows, columns &lt;= 100\n\t1 &lt;= heights[i][j] &lt;= 106\n",
        "solution_py": "class Solution:\n    def minimumEffortPath(self, heights: List[List[int]]) -> int:\n        di = (0, 1, 0, -1)\n        dj = (1, 0, -1, 0)\n        m, n = len(heights), len(heights[0])\n        visited = [[False] * n for _ in range(m)]\n        h = [(0, 0, 0)]\n        while h:\n            effort, i, j = heappop(h)\n            if visited[i][j]:\n                continue\n            visited[i][j] = True\n            if i + 1 == m and j + 1 == n:\n                return effort ## have reached the (m-1, n-1) cell\n            for k in range(4):\n                ii, jj = i + di[k], j + dj[k]\n                if 0 <= ii < m and 0 <= jj < n and not visited[ii][jj]:\n                    neffort = max(effort, abs(heights[i][j] - heights[ii][jj]))\n                    heappush(h, (neffort, ii, jj))\n        return ## cell (m-1, n-1) not reachable, should never happen",
        "solution_js": "/**\n * @param {number[][]} heights\n * @return {number}\n * T: O((M*N)log(M*N))\n * S: O(M*N)\n */\nvar minimumEffortPath = function(heights) {\n    const directions = [\n        [1, 0],\n        [0, 1],\n        [-1, 0],\n        [0, -1],\n    ];\n    const row = heights.length;\n    const col = heights[0].length;\n    const differences = [];\n    for (let i = 0; i < row; i++) {\n        for (let j = 0; j < col; j++) {\n            if (!differences[i]) {\n                differences[i] = [Infinity];\n            } else {\n                differences[i].push(Infinity);\n            }\n        }\n    }\n    differences[0][0] = 0;\n    const pq = new PriorityQueue();\n    pq.push([0, 0], 0);\n    while (pq.data.length > 0) {\n        const node = pq.shift();\n        const difference = node.priority;\n        const [x, y] = node.val;\n        directions.forEach(([dx, dy]) => {\n            const newX = x + dx;\n            const newY = y + dy;\n            if (newX >= 0 && newX < row && newY >= 0 && newY < col) {\n                const currentDiff = Math.abs(heights[newX][newY] - heights[x][y]);\n                const maxDiff = Math.max(currentDiff, differences[x][y]);\n                if (differences[newX][newY] > maxDiff) {\n                    differences[newX][newY] = maxDiff;\n                    pq.push([newX, newY], maxDiff);\n                }\n            }\n        });\n    }\n    return differences[row - 1][col - 1];\n};\n\nconst swap = (arr, i, j) => {\n    const temp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = temp;\n};\n\nfunction Node(val, priority) {\n    this.val = val;\n    this.priority = priority;\n}\n\nfunction PriorityQueue() {\n    this.data = [];\n}\n\nPriorityQueue.prototype.push = function push(val, priority) {\n    const node = new Node(val, priority);\n    this.data.push(node);\n    let index = this.data.length - 1;\n    while (index > 0) {\n        const parentIndex = Math.floor((index - 1) / 2);\n        const parent = this.data[parentIndex];\n        if (parent.priority > node.priority) {\n            swap(this.data, parentIndex, index);\n            index = parentIndex;\n        } else {\n            break;\n        }\n    }\n};\n\nPriorityQueue.prototype.shift = function shift() {\n    const minNode = this.data[0] || {};\n    const lastNode = this.data.pop();\n    if (this.data.length < 1) {\n        return minNode;\n    }\n    this.data[0] = lastNode;\n    let index = 0;\n    while (index < this.data.length) {\n        const leftIndex = 2 * index + 1;\n        const rightIndex = 2 * index + 2;\n        const leftNode = this.data[leftIndex] || {};\n        const rightNode = this.data[rightIndex] || {};\n        let smallerIndex;\n        if (leftNode.priority < lastNode.priority) {\n            smallerIndex = leftIndex;\n        }\n        if (!smallerIndex && rightNode.priority < lastNode.priority) {\n            smallerIndex = rightIndex;\n        }\n        if (smallerIndex && rightNode.priority < leftNode.priority) {\n            smallerIndex = rightIndex;\n        }\n        if (!smallerIndex) {\n            break;\n        }\n        swap(this.data, index, smallerIndex);\n        index = smallerIndex;\n    }\n    return minNode;\n};",
        "solution_java": "class Tuple {\n\n    int distance;\n\n    int row;\n\n    int col;\n\n    \n\n    Tuple(int distance, int row, int col) {\n\n        this.distance = distance;\n\n        this.row = row;\n\n        this.col = col;\n\n    }\n\n}\n\n\n\nclass Solution {\n\n    public int minimumEffortPath(int[][] heights) {\n\n        // Create a min heap based on the distance\n\n        PriorityQueue<Tuple> minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);\n\n        \n\n        int rows = heights.length;\n\n        int cols = heights[0].length;\n\n        \n\n        // Create a 2D array to store the minimum effort to reach each cell\n\n        int effort[][] = new int[rows][cols];\n\n        \n\n        // Initialize all efforts to maximum initially\n\n        for (int i = 0; i < rows; i++) {\n\n            Arrays.fill(effort[i], Integer.MAX_VALUE);\n\n        }\n\n        \n\n        effort[0][0] = 0; // Initial effort at the starting cell\n\n        \n\n        // Add the starting cell to the min heap\n\n        minHeap.add(new Tuple(0, 0, 0));\n\n        \n\n        // Arrays to represent row and column changes for 4 directions\n\n        int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left\n\n        int dc[] = {0, 1, 0, -1};\n\n        \n\n        while (!minHeap.isEmpty()) {\n\n            Tuple current = minHeap.poll(); // Get the cell with the minimum effort\n\n            int distance = current.distance;\n\n            int row = current.row;\n\n            int col = current.col;\n\n            \n\n            if (row == rows - 1 && col == cols - 1) {\n\n                return distance; // If reached the destination, return the effort\n\n            }\n\n            \n\n            // Explore each of the 4 possible directions\n\n            for (int i = 0; i < 4; i++) {\n\n                int newRow = row + dr[i]; // Calculate new row index\n\n                int newCol = col + dc[i]; // Calculate new column index\n\n                \n\n                // Check if the new cell is within bounds\n\n                if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\n\n                    \n\n                    // Calculate the new effort based on the maximum of height difference and current effort\n\n                    int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);\n\n                    \n\n                    // If the new effort is less than the stored effort for the cell, update and add to heap\n\n                    if (newEffort < effort[newRow][newCol]) {\n\n                        effort[newRow][newCol] = newEffort;\n\n                        minHeap.add(new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration\n\n                    }\n\n                }\n\n            }\n\n        }\n\n        return 0; // This value should be replaced with the actual minimum effort\n\n    }\n\n}",
        "solution_c": "#define pii pair<int, pair<int,int>>\n\nclass Solution {\npublic:\n    //Directions (top, right, bottom, left)\n    const int d4x[4] = {-1,0,1,0}, d4y[4] = {0,1,0,-1};\n    \n    int minimumEffortPath(vector<vector<int>>& h) {\n        int n = h.size(), m = h[0].size();\n        //min-heap\n        priority_queue <pii, vector<pii>, greater<pii>> pq;\n        //to store distances from (0,0)\n        vector<vector<int>> dis(n, vector<int>(m, INT_MAX));\n        dis[0][0] = 0;\n        pq.push({0, {0, 0}});\n        \n        //Dijstra algorithm\n        while(!pq.empty()) {\n            pii curr = pq.top(); pq.pop();\n            int d = curr.first, r = curr.second.first, c = curr.second.second;\n            // bottom right position\n            if(r==n-1 && c==m-1) return d;\n            for(int i=0; i<4; ++i) {\n                int nx = r + d4x[i], ny = c + d4y[i];\n                //check if new position is invalid\n                if(nx < 0 || nx >= n || ny < 0 || ny >= m)continue;\n\t\t\t\t//nd => new distance: which is max of distance till now(d) and curr distance (difference between heights of current cells)\n                int nd = max(d, abs(h[nx][ny] - h[r][c]));\n                if (nd < dis[nx][ny]) {\n                    dis[nx][ny] = nd;\n                    pq.push({nd, {nx, ny}});\n                }\n            }\n        }\n        return 0;\n        //please upvote\n    }\n};"
    },
    {
        "title": "First Missing Positive",
        "algo_input": "Given an unsorted integer array nums, return the smallest missing positive integer.\n\nYou must implement an algorithm that runs in O(n) time and uses constant extra space.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,0]\nOutput: 3\nExplanation: The numbers in the range [1,2] are all in the array.\n\n\nExample 2:\n\nInput: nums = [3,4,-1,1]\nOutput: 2\nExplanation: 1 is in the array but 2 is missing.\n\n\nExample 3:\n\nInput: nums = [7,8,9,11,12]\nOutput: 1\nExplanation: The smallest positive integer 1 is missing.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def firstMissingPositive(self, nums: List[int]) -> int:\n        mn = float('inf')\n        mx = 0\n        numsSet = set()\n\n        for i in range(len(nums) - 1, -1, -1):\n            if nums[i] > 0:\n                if nums[i] < mn:\n                    mn = nums[i]\n                if nums[i] > mx:\n                    mx = nums[i]\n                numsSet.add(nums[i])\n            del nums[i]\n\n        if mn >= 2:\n            return 1\n        if len(numsSet) == mx:\n            return mx + 1\n        for i in range(2, len(numsSet) + 1):\n            if i not in numsSet:\n                return i",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar firstMissingPositive = function (nums) {\n\n    //first make all negative numbers to zero =>zero means we ignore whis number\n    for (let index = 0; index < nums.length; index++) {\n        if (nums[index] < 0)\n            nums[index] = 0\n    }\n\n    for (let index = 0; index < nums.length; index++) {\n        const temp = Math.abs(nums[index])\n        const element = temp - 1\n\n        if (element < nums.length && element >= 0)\n            nums[element] = nums[element] === 0 ? -(nums.length + 1) : Math.abs(nums[element]) * -1\n\n    }\n\n    for (let index = 0; index < nums.length; index++) {\n        const element = (nums[index])\n        if (element >= 0) return index + 1\n\n    }\n    return nums.length+1\n\n};",
        "solution_java": "class Solution {\n   public int firstMissingPositive(int[] nums) {\n       //cyclic sort\n        int i = 0;\n        while (i<nums.length){\n            int correct = nums[i]-1;\n            if(nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[correct]){\n                swap(nums,i,correct);\n            }else{\n                i++;\n            }\n        }\n       //linear search to find the missing number\n        for(int index=0;index<nums.length;index++){\n            if (nums[index] != index+1) {\n                return index+1;\n            }\n        }\n       //if array has all the elements match to its index then 1st missing num will be\n       //nums.length+1\n        return nums.length+1;\n    }\n    static void swap(int[]arr,int a , int b){\n        int temp = arr[a];\n        arr[a]=arr[b];\n        arr[b]=temp;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int firstMissingPositive(vector<int>& nums) {\n        int n = nums.size();\n        for(int i=0; i<n; i++){\n            if(nums[i]==i+1 || nums[i]<=0 || nums[i]>n) continue;\n            while(nums[i]!=i+1 && nums[i]>0 && nums[i]<=n && nums[nums[i]-1] != nums[i]){\n                swap(nums[i],nums[nums[i]-1]);\n            }\n        }\n        int ans = -1;\n        for(int i=0; i<n; i++){\n            if(nums[i]!=i+1){\n                ans = i+1;\n                break;\n            }\n        }\n        if(ans==-1){\n            return n+1;\n        }else{\n            return ans;\n        }\n    }\n};"
    },
    {
        "title": "Divisor Game",
        "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nInitially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:\n\n\n\tChoosing any x with 0 &lt; x &lt; n and n % x == 0.\n\tReplacing the number n on the chalkboard with n - x.\n\n\nAlso, if a player cannot make a move, they lose the game.\n\nReturn true if and only if Alice wins the game, assuming both players play optimally.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: true\nExplanation: Alice chooses 1, and Bob has no more moves.\n\n\nExample 2:\n\nInput: n = 3\nOutput: false\nExplanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def divisorGame(self, n: int) -> bool:\n                \n        \"\"\"\n        let's forget about Alice and Bob for a second and just concentrate on the n and plays\n        if played optimally :\n        \n        1 - player at 1 will loose since no factors\n        2 - player at 2 will win by choosing 1\n        3 - player at 3 will loose always since he/she has to choose 1. and then next player will always win because they are at 2\n        4 - player at 4 will win by choosing 1 as a factor as next player will have to play at 3\n        5 - player at 5 will loose because he has to choose 1, and player at 4 will always win\n        6 - player at 6 will always win by choosing 3 as a factor\n        7 - player at 7 will have to choose 1, and hence result 6 will make player at 6 to win\n        8 - player at 8 can choose 1 and win always\n        .\n        .\n        .\n        .\n        Pattern detected\n        \n        Now, since Alice is the first player we can return bool values accordingly\n        \n        \n        \"\"\"\n        \n        return n%2 == 0\n        \n        ",
        "solution_js": "var divisorGame = function(n) {\n    let count = 0;\n    while(true){\n        let flag = true;\n        for(let i = 1;i<n;i++){\nif(n%i==0){\n    flag = false;\n    n = n-i;\n    break;\n}\n            \n        }\n        if(flag){\nif(count %2==0) return false;\n            else return true;\n}\n        count++;\n    }\n};",
        "solution_java": "class Solution {\n    public boolean divisorGame(int n) {\n        return n%2==0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool divisorGame(int n) {\n        if(n%2==0) return true;\n        return false;\n    }\n};"
    },
    {
        "title": "Naming a Company",
        "algo_input": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:\n\n\n\tChoose 2 distinct names from ideas, call them ideaA and ideaB.\n\tSwap the first letters of ideaA and ideaB with each other.\n\tIf both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.\n\tOtherwise, it is not a valid name.\n\n\nReturn the number of distinct valid names for the company.\n\n&nbsp;\nExample 1:\n\nInput: ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]\nOutput: 6\nExplanation: The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.\n\n\nExample 2:\n\nInput: ideas = [\"lack\",\"back\"]\nOutput: 0\nExplanation: There are no valid selections. Therefore, 0 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= ideas.length &lt;= 5 * 104\n\t1 &lt;= ideas[i].length &lt;= 10\n\tideas[i] consists of lowercase English letters.\n\tAll the strings in ideas are unique.\n\n",
        "solution_py": "class Solution:\n    def distinctNames(self, ideas: List[str]) -> int:\n        \n        names=defaultdict(set)\n        res=0  \n        \n        #to store first letter as key and followed suffix as val\n        for i in ideas:\n            names[i[0]].add(i[1:])\n            \n        #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)\n        arr=list(names.keys())\n        ans,n=0,len(arr)\n        \n        for i in range(n):\n            for j in range(i+1,n):\n                #a,b => 2 distinct first letters\n                a,b=arr[i],arr[j]\n                # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be \"newword1 newword2\" or \"newword2 newword1\"\n                res+=len(names[a]-names[b])*len(names[b]-names[a])*2\n                \n        return res\n\t",
        "solution_js": "/**\n * @param {string[]} ideas\n * @return {number}\n */\nvar distinctNames = function(ideas) {\n    let res = 0;\n    let lMap = new Map();\n\n    for(let i=0; i<ideas.length; i++){\n        let idea = ideas[i];\n        // extract first letter\n        let l = idea[0].charCodeAt() - 97;\n        // extract substring\n        let s = idea.substr(1);\n        // group substring by first letter\n        if(lMap.has(l)){\n\t\t    // must use map not array\n            let m = lMap.get(l);\n            m.set(s, 1);\n            lMap.set(l, m);\n        }else{\n            let m = new Map();\n            m.set(s, 1);\n            lMap.set(l, m);\n        }\n    }\n\n    for(let i=1; i<26; i++){\n        for(let j=0; j<i; j++){\n            // count substring with different first letter\n            let m = 0;\n            let m1 = lMap.has(i) ? lMap.get(i) : new Map();\n            let m2 = lMap.has(j) ? lMap.get(j) : new Map();\n\t\t\t// both map must exist\n            if(m1.size > 0 && m2.size > 0){\n                let k1 = Array.from(m1.keys());\n                for(let k=0; k<k1.length; k++){\n                    if(m2.has(k1[k])){\n                        m ++;\n                    }\n                }\n                // the rest substring satisfy condition\n                res += (m1.size - m) * (m2.size-m);\n            }\n        }\n    }\n    // double for count A + B and B + A\n    res = res * 2;\n    return res;    \n};",
        "solution_java": "class Solution {\n    public long distinctNames(String[] ideas) {\n        // HashSet + String Manipulation; TC: O(26*26*n); SC: O(26*n)\n        HashSet<String> [] arr = new HashSet[26];\n        for(int i=0; i<26; i++) {\n            arr[i] = new HashSet<>();\n        }\n        for(String s: ideas) {\n            arr[s.charAt(0)-'a'].add(s.substring(1));\n        }\n        long ans=0, cnt;\n        for(int i=0; i<26; i++) {\n            for(int j=i+1; j<26; j++) {\n                cnt=0;\n                for(String str: arr[j]) {\n                    if(arr[i].contains(str)) cnt++;\n                }\n                ans+=2*(arr[i].size()-cnt)*(arr[j].size()-cnt);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long distinctNames(vector<string>& ideas) {\n        unordered_map <char,unordered_set<string>> mp;\n        for(auto u : ideas) mp[u[0]].insert(u.substr(1,u.size()-1));\n        \n        long long ans = 0;\n        \n        for(int i = 0; i<26; i++){\n            for(int j = i+1; j<26; j++){\n                unordered_set <string> s1 = mp[i+'a'], s2 = mp[j+'a'];\n                \n                int comm = 0;\n                for(auto u : s1)\n                    if(s2.find(u)!=s2.end()) comm++;\n                \n                ans += (long long)(s1.size()-comm)*(long long)(s2.size()-comm)*2;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Rearrange Characters to Make Target String",
        "algo_input": "You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.\n\nReturn the maximum number of copies of target that can be formed by taking letters from s and rearranging them.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ilovecodingonleetcode\", target = \"code\"\nOutput: 2\nExplanation:\nFor the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.\n\n\nExample 2:\n\nInput: s = \"abcba\", target = \"abc\"\nOutput: 1\nExplanation:\nWe can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".\n\n\nExample 3:\n\nInput: s = \"abbaccaddaeea\", target = \"aaaaa\"\nOutput: 1\nExplanation:\nWe can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\t1 &lt;= target.length &lt;= 10\n\ts and target consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def rearrangeCharacters(self, s: str, target: str) -> int:\n        counter_s = Counter(s)\n        return min(counter_s[c] // count for c,count in Counter(target).items())",
        "solution_js": "/**\n * @param {string} s\n * @param {string} target\n * @return {number}\n */\nvar rearrangeCharacters = function(s, target) {\n    let cnt = Number.MAX_VALUE;\n\n    let m1 = new Map();\n    for(const x of target) m1.set(x , m1.get(x)+1 || 1);\n\n    let m2 = new Map();\n    for(const x of s) m2.set(x , m2.get(x)+1 || 1);\n\n    for(let it of m1){\n        let ch = it[0];\n        let x = it[1];\n        let y = m2.get(ch);\n        if(y === undefined) y=0;\n        cnt = Math.min(cnt,Math.floor(y/x));\n    }\n    return cnt;\n};",
        "solution_java": "class Solution\n{\n    public int rearrangeCharacters(String s, String target)\n    {\n        int[] freq = new int[26], freq2 = new int[26];\n        for(char ch : s.toCharArray())\n            freq[ch-'a']++;\n        for(char ch : target.toCharArray())\n            freq2[ch-'a']++;\n\n        int min = Integer.MAX_VALUE;\n        for(char ch : target.toCharArray())\n            min = Math.min(min,freq[ch-'a']/freq2[ch-'a']);\n        \n        return min;\n    }\n}",
        "solution_c": "Approach :\n       => Take two map,  one to store frequency of target, and another for sentence. \n\t   => Traverse over the mp(frequency of target ) and calculate the minimum frequency ratio \n\t                            mn =  min(mn ,   frequency of a char in sentance / frequency of same char in target) ; \t\t  \n\t\t\t\t\t\t\t\t\t\t \n\t\tSpace : O(n) \n\t\tTime : O(n)\nclass Solution {\npublic:\n    int rearrangeCharacters(string s, string target) {\n        unordered_map<char,int> targetFreq ; \n        for(auto a : target) {\n             targetFreq[a] ++;\n        }\n        unordered_map<char , int> sentFreq ; \n        for(auto a : s) {\n            sentFreq[a] ++ ; \n        }\n        int mn = INT_MAX  ; \n        for(auto a : targetFreq ) {\n             mn = min(mn , sentFreq[a.first]/a.second); \n        }\n        return mn ; \n    }\n};"
    },
    {
        "title": "Remove Duplicates from Sorted List",
        "algo_input": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,1,2]\nOutput: [1,2]\n\n\nExample 2:\n\nInput: head = [1,1,2,3,3]\nOutput: [1,2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 300].\n\t-100 &lt;= Node.val &lt;= 100\n\tThe list is guaranteed to be sorted in ascending order.\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if head is None:\n            return head\n        cur=head.next\n        prev=head\n        while cur is not None:\n            if cur.val==prev.val:\n                prev.next=cur.next\n            else:\n                prev=cur\n            cur=cur.next\n        return head",
        "solution_js": "var deleteDuplicates = function(head) {\n    // Special case...\n    if(head == null || head.next == null)\n        return head;\n    // Initialize a pointer curr with the address of head node...\n    let curr = head;\n    // Traverse all element through a while loop if curr node and the next node of curr node are present...\n    while( curr != null && curr.next != null){\n        // If the value of curr is equal to the value of prev...\n        // It means the value is present in the linked list...\n        if(curr.val == curr.next.val){\n            // Hence we do not need to include curr again in the linked list...\n            // So we increment the value of curr...\n            curr.next = curr.next.next;\n        }\n        // Otherwise, we increment the curr pointer...\n        else{\n            curr = curr.next; \n        }\n    }\n    return head;        // Return the sorted linked list without any duplicate element...\n};",
        "solution_java": "class Solution {\n    public ListNode deleteDuplicates(ListNode head) {\n\n        if (head == null) {\n            return head;\n        }\n\n        ListNode result = head;\n\n        while (result != null) {\n            if (result.next == null) {\n                break;\n            }\n\n            if (result.val == result.next.val) {\n                result.next = result.next.next;\n            } else {\n                result = result.next;\n            }\n        }\n\n        return head;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    // Recursive Approach\n    ListNode* deleteDuplicates(ListNode* head){\n        // base case\n        if(head==NULL || head->next==NULL)\n            return head;\n        // 1-1-2-3-3\n        //we are giving next pointer to recursion and telling it to get it done for me\n        ListNode* newNode=deleteDuplicates(head->next); // 1-2-3-3\n        // after recursion we will get-- 1-2-3\n        \n        //now we will compare the head node with the newNode \n        // if both are same then return the newNode\n        //else return the current head\n        if(head->val==newNode->val) \n            return newNode;\n        else{\n            head->next=newNode;\n            return head;\n        } \n    }\n};\n\n\nclass Solution {\npublic:\n    // Iterative Approach\n    ListNode* deleteDuplicates(ListNode* head){\n        if(head==NULL || head->next==NULL) return head;\n        \n        ListNode* temp =head;\n        while(temp->next!=NULL){\n            // if the 2 consecutive nodes are equal then just delete the in between\n            if(temp->val==temp->next->val){\n                temp->next=temp->next->next;\n                //dont need to update the temp variable as there can be more than 2 duplicates\n                // 1-1-1-1-2-3-4-4-NULL\n            }\n            else{\n                temp=temp->next; //update the temp variable\n            }\n        }\n        return head;\n    }\n};"
    },
    {
        "title": "Robot Bounded In Circle",
        "algo_input": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:\n\n\n\tThe north direction is the positive direction of the y-axis.\n\tThe south direction is the negative direction of the y-axis.\n\tThe east direction is the positive direction of the x-axis.\n\tThe west direction is the negative direction of the x-axis.\n\n\nThe robot can receive one of three instructions:\n\n\n\t\"G\": go straight 1 unit.\n\t\"L\": turn 90 degrees to the left (i.e., anti-clockwise direction).\n\t\"R\": turn 90 degrees to the right (i.e., clockwise direction).\n\n\nThe robot performs the instructions given in order, and repeats them forever.\n\nReturn true if and only if there exists a circle in the plane such that the robot never leaves the circle.\n\n&nbsp;\nExample 1:\n\nInput: instructions = \"GGLLGG\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --&gt; (0, 1) --&gt; (0, 2) --&gt; (0, 1) --&gt; (0, 0).\nBased on that, we return true.\n\n\nExample 2:\n\nInput: instructions = \"GG\"\nOutput: false\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.\n\n\nExample 3:\n\nInput: instructions = \"GL\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --&gt; (0, 1) --&gt; (-1, 1) --&gt; (-1, 0) --&gt; (0, 0).\nBased on that, we return true.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= instructions.length &lt;= 100\n\tinstructions[i] is 'G', 'L' or, 'R'.\n\n",
        "solution_py": "class Solution:\n    def isRobotBounded(self, instructions: str) -> bool:\n        pos, d = [0,0], \"N\"\n        def move(d, pos, instructions):\n            for i in instructions:\n                if i == \"G\":\n                    if d == \"N\": pos[1] += 1\n                    elif d == \"S\": pos[1] -= 1\n                    elif d == \"W\": pos[0] -= 1\n                    else: pos[0] += 1\n                elif i == \"L\":\n                    if d == \"N\": d = \"W\"\n                    elif d == \"W\": d = \"S\"\n                    elif d == \"S\": d = \"E\"\n                    else: d = \"N\"\n                else:\n                    if d == \"N\": d = \"E\"\n                    elif d == \"W\": d = \"N\"\n                    elif d == \"S\": d = \"W\"\n                    else: d = \"S\"\n            return (d, pos)\n        for i in range(4):\n            d, pos = (move(d, pos, instructions))\n        return True if pos == [0,0] else False",
        "solution_js": "var isRobotBounded = function(instructions) {\n        // north = 0, east = 1, south = 2, west = 3\n        let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n        // Initial position is in the center\n        let x = 0, y = 0;\n        // facing north\n        let idx = 0;\n        let movements = [...instructions];\n\n        for (let move of movements) {\n            if (move == 'L')\n                idx = (idx + 3) % 4;\n            else if (move == 'R')\n                idx = (idx + 1) % 4;\n            else {\n                x += directions[idx][0];\n                y += directions[idx][1];\n            }\n        }\n\n        // after one cycle:\n        // robot returns into initial position\n        // or robot doesn't face north\n        return (x == 0 && y == 0) || (idx != 0);\n};",
        "solution_java": "class Solution {\n    public boolean isRobotBounded(String instructions) {\n        if (instructions.length() == 0) {\n            return true;\n        }\n\n        Robot bender = new Robot();\n        int[] start = new int[]{0, 0};\n\n        // 4 represents the max 90 degree turns that can restart initial orientation.\n        for (int i = 0; i < 4; i++) {\n            boolean orientationChanged = bender.performSet(instructions);\n\n            int[] location = bender.location;\n            if (location[0] == start[0] && location[1] == start[1]) {\n                return true;\n            }\n\n            // If robot never turns and the first instruction isn't at start, exit.\n            else if (!orientationChanged) {\n                return false;\n            }\n        }\n\n        return false;\n    }\n}\n\nclass Robot {\n    int[] location;\n    int[] orientation;\n    int[][] orientations;\n    int orientationPos;\n    boolean orientationChangeCheck;\n\n    Robot() {\n        // Start in center\n        location = new int[]{0, 0};\n\n        // N, E, S, W\n        orientations = new int[][]{{1,0}, {0, 1}, {-1, 0}, {0, -1}};\n\n        // Start pointing north\n        orientationPos = 0;\n        orientation = orientations[orientationPos];\n\n        // Track if robot has turned\n        orientationChangeCheck = false;\n    }\n\n    public boolean performSet(String orders) {\n        this.orientationChangeCheck = false;\n\n        for (int i = 0; i < orders.length(); i++) {\n            this.perform(orders.charAt(i));\n        }\n\n        return this.orientationChangeCheck;\n    }\n\n    public void perform(char order) {\n        if (order == 'G') {\n            this.go();\n        } else if (order == 'L' || order == 'R') {\n            this.turn(order);\n        } else {\n           // do nothing\n        }\n    }\n\n    public void turn(char direction) {\n        if (direction == 'L') {\n            this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;\n        } else if (direction == 'R') {\n            this.orientationPos = (this.orientationPos + 1) % 4;\n        }\n\n        this.orientation = this.orientations[this.orientationPos];\n        this.orientationChangeCheck = true;\n    }\n\n    public int[] go() {\n        this.location[0] += this.orientation[0];\n        this.location[1] += this.orientation[1];\n        return this.location;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isRobotBounded(string instructions) {\n        char direction = 'N';\n        int x = 0, y = 0;\n        for (char &instruction: instructions) {\n            if (instruction == 'G') {\n                if (direction == 'N') y++;\n                else if (direction == 'S') y--;\n                else if (direction == 'W') x--;\n                else x++;\n            } else if (instruction == 'L') {\n                if (direction == 'N') direction = 'W';\n                else if (direction == 'S') direction = 'E';\n                else if (direction == 'W') direction = 'S';\n                else direction = 'N';\n            } else {\n                if (direction == 'N') direction = 'E';\n                else if (direction == 'S') direction = 'W';\n                else if (direction == 'W') direction = 'N';\n                else direction = 'S';\n            }\n        }\n        return (x == 0 && y == 0) || direction != 'N';\n    }\n};"
    },
    {
        "title": "Contains Duplicate",
        "algo_input": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,3,1]\nOutput: true\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: false\nExample 3:\nInput: nums = [1,1,1,3,3,4,3,2,4,2]\nOutput: true\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def containsDuplicate(self, nums: List[int]) -> bool:\n        return len(nums) != len(set(nums))",
        "solution_js": "var containsDuplicate = function(nums) {\n    if(nums.length <= 1) return false;\n    let cache = {};\n    let mid = Math.floor(nums.length /2)\n    let left = mid -1;\n    let right  = mid;\n    while(left >= 0 || right < nums.length) {\n        if(nums[left] === nums[right]) {\n            return true;\n        };\n        if(cache[nums[left]]){\n            return true\n        } else {\n            cache[nums[left]] = true; \n        }\n        if(cache[nums[right]]){\n            return true;\n        } else{\n            cache[nums[right]] = true;\n        }\n        left--;\n        right++;\n    }\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean containsDuplicate(int[] nums) {\n        Arrays.sort(nums);\n        int n = nums.length;\n        for (int i = 1; i < n; i++) {\n            if (nums[i] == nums[i - 1])\n                return true;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool containsDuplicate(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n        for (int i=0; i<n-1; i++){\n            if (nums[i]==nums[i+1])\n        return true;\n            }\n        return false;\n\n    }\n};"
    },
    {
        "title": "Rectangle Area II",
        "algo_input": "You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.\n\nCalculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.\n\nReturn the total area. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.\n\n\nExample 2:\n\nInput: rectangles = [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 1018 modulo (109 + 7), which is 49.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rectangles.length &lt;= 200\n\trectanges[i].length == 4\n\t0 &lt;= xi1, yi1, xi2, yi2 &lt;= 109\n\n",
        "solution_py": "class SegmentTree:\n    def __init__(self, xs):\n        #cnts[v] means that the node's interval is active\n        self.cnts = defaultdict(int)\n        #total[v] length of active intervals that are contained the node's interval\n        self.total = defaultdict(int)\n        self.xs = xs\n\n    def update(self, v, tl, tr, l, r, h):\n        #node interval [tl,tr] does not overlap with query interval [l,r]\n        if r < tl or tr < l: return\n        #node interval is included in the query interval\n        if l <= tl and tr <= r:\n            self.cnts[v] += h\n        else:\n            tm = (tl + tr)//2\n            self.update(v*2, tl, tm, l, r, h)\n            self.update(v*2+1, tm+1, tr, l, r, h)\n        #node interval is included in the active interval\n        if self.cnts[v] > 0:\n            self.total[v] = self.xs[tr + 1] - self.xs[tl]\n        else:\n            self.total[v] = self.total[v*2] + self.total[v*2+1]\n        return self.total[v]\n\nclass Solution:\n    def rectangleArea(self, rectangles):\n        #index i means the interval from xs[i] to xs[i+1]\n        xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))\n        xs_i = {x:i for i, x in enumerate(xs)}\n        st = SegmentTree(xs)\n        L = []\n        for x1, y1, x2, y2 in rectangles:\n            L.append([y1, 1, x1, x2])\n            L.append([y2, -1, x1, x2])\n        L.sort()\n        cur_y = cur_x_sum = area = 0\n        for y, open_close, x1, x2 in L:\n            area += (y - cur_y) * cur_x_sum\n            cur_y = y\n            #one index corresponds to one interval, that's why we use xs_i[x2]-1 instead of xs_i[x2]\n            st.update(1, 0, len(xs) - 1, xs_i[x1], xs_i[x2]-1, open_close)\n            cur_x_sum = st.total[1]\n\n        return area % (10 ** 9 + 7)",
        "solution_js": "var rectangleArea = function(rectangles) {\n  let events = [], active = [], area = 0n;\n  let mod = BigInt(1000000007);\n  for (var rec of rectangles) {\n    events.push([rec[1], 'open', rec[0], rec[2]]);\n    events.push([rec[3], 'close', rec[0], rec[2]]);\n  }  \n  events = events.sort((a, b) => a[0] - b[0]);\n  let y = events[0][0];\n  for (var event of events) {\n    let currY = event[0], type = event[1], x1 = event[2], x2 = event[3];\n    let maxLength = 0, curr = -1;\n    for (var ev of active) {\n      curr = Math.max(curr, ev[0]);\n      maxLength += Math.max(0, ev[1] - curr);\n      curr = Math.max(curr, ev[1]);\n    }\n    area += (BigInt(maxLength) * BigInt(currY - y));\n    area %= mod;\n    if (type === 'open') {\n      active.push([x1, x2]);\n      active = active.sort((a, b) => a[0] - b[0]);\n    } else {\n      for (var i = 0; i < active.length; i++) {\n        let e = active[i];\n        if (e[0] === x1 && e[1] === x2) {\n          active.splice(i, 1);\n          break;\n        }\n      }\n    }\n    y = currY;\n  }\n  return area % mod;\n};",
        "solution_java": "class Solution {\n      public int rectangleArea(int[][] rectangles) {\n          int n = rectangles.length;\n          Set<Integer> coorx = new HashSet<>();\n          Set<Integer> coory = new HashSet<>();\n          for (int[] rec : rectangles) {\n              coorx.add(rec[0]); coorx.add(rec[2]);\n              coory.add(rec[1]); coory.add(rec[3]);\n          }\n\n          Integer[] compressx = coorx.toArray(new Integer[0]);\n          Arrays.sort(compressx);\n          Integer[] compressy = coory.toArray(new Integer[0]);\n          Arrays.sort(compressy);\n\n          Map<Integer, Integer> mapx = new HashMap<>();\n          for(int i = 0; i < compressx.length; i++) {\n              mapx.put(compressx[i], i);\n          }\n          Map<Integer, Integer> mapy = new HashMap<>();\n          for(int i = 0; i < compressy.length; i++) {\n              mapy.put(compressy[i], i);\n          }\n\n          boolean[][] grid = new boolean[compressx.length][compressy.length];\n          for (int[] rec: rectangles) {\n              for (int x = mapx.get(rec[0]); x < mapx.get(rec[2]); x++) {\n                  for (int y = mapy.get(rec[1]); y < mapy.get(rec[3]); y++) {\n                      grid[x][y] = true;\n                  }\n              }\n          }\n\n          long res = 0L;\n          for (int i = 0; i < grid.length; i++) {\n              for (int j = 0; j < grid[0].length; j++) {\n                  if (grid[i][j]) {\n                      res += (long)(compressx[i + 1] - compressx[i]) * (compressy[j + 1] - compressy[j]);\n                  }\n              }\n          }\n          res %= 1000000007;\n          return (int)res;\n      }\n  }",
        "solution_c": "struct Point\n{\n    int X;\n    int delta;\n};\n\nclass Solution\n{\npublic:\n    int rectangleArea(vector<vector<int>>& rectangles)\n    {\n        map<int, vector<Point>> lines; // y -> array of Points\n        for (auto&r : rectangles)\n        {\n            auto x1 = r[0];\n            auto y1 = r[1];\n            auto x2 = r[2];\n            auto y2 = r[3];\n\n            lines[y1].push_back(Point {x1, +1});\n            lines[y1].push_back(Point {x2, -1});\n            lines[y2].push_back(Point {x1, -1});\n            lines[y2].push_back(Point {x2, +1});\n        }\n\n        long area = 0;\n        int prevy = 0;\n        int length = 0;\n\n        map<int, int> scanline; // x -> delta\n        for (const auto& [y, points] : lines)\n        {\n            area += (y - prevy) * (long)length;\n\n            // Update scanline for new y: add new rectanhgles,\n            // remove old\n            for (auto point : points)\n            {\n                auto xdelta = scanline.find(point.X);\n                if (xdelta != end(scanline))\n                {\n                    xdelta->second += point.delta;\n                    if (xdelta->second == 0)\n                        scanline.erase(xdelta);\n                }\n                else\n                    scanline[point.X] = point.delta;\n            }\n\n            // For current y-line calc the length of\n            // intersection with rectangles\n            int startX = -1;\n            int rectCount = 0;\n            length = 0;\n            for (const auto& [x, delta] : scanline)\n            {\n                int oldcount = rectCount;\n                rectCount += delta;\n                if (oldcount == 0)\n                    startX = x;\n                else if (rectCount == 0)\n                    length += x - startX;\n            }\n\n            if (rectCount > 0)\n                length += scanline.rbegin()->first - startX;\n\n            prevy = y;\n        }\n\n        return area % (1000000007);\n    }\n};"
    },
    {
        "title": "Maximum Sum BST in Binary Tree",
        "algo_input": "Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).\n\nAssume a BST is defined as follows:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput: 20\nExplanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n\n\nExample 2:\n\n\n\nInput: root = [4,3,null,1,2]\nOutput: 2\nExplanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n\n\nExample 3:\n\nInput: root = [-4,-2,-5]\nOutput: 0\nExplanation: All values are negatives. Return an empty BST.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 4 * 104].\n\t-4 * 104 &lt;= Node.val &lt;= 4 * 104\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def maxSumBST(self, root: Optional[TreeNode]) -> int:\n        # declaire a variable maxSum to hold the max path sum\n        self.maxSum=0\n        def getMax(root):\n            # return max,min,val - if root is null, valid BST\n            if not root : return (float(\"-inf\"),float(\"inf\"),0)\n            # traverse left and right part\n            leftMax,leftMin,leftMaxSum=getMax(root.left)\n            rightMax,rightMin,rightMaxSum=getMax(root.right)\n            # if a valid BST\n            if root.val>leftMax and root.val<rightMin:\n                # update maxSum\n                self.maxSum=max(self.maxSum,root.val+leftMaxSum+rightMaxSum)\n                # return maximum and minimum node values starting from that node and pathSum\n                return max(root.val,rightMax),min(root.val,leftMin),root.val+leftMaxSum+rightMaxSum\n            # if not a BST - set an impossible condition such than the root is also returned as non-BST\n            return  (float(\"inf\"),float(\"-inf\"),0)\n        getMax(root)    \n        return self.maxSum\n        \n            ",
        "solution_js": "var maxSumBST = function(root) {\n    let max = 0;\n    const dfs = (node) => {\n        // NoNode\n        if(!node) return [true, 0, Infinity, -Infinity];\n\n        // LeafNode\n        if(node && !node.left && !node.right) {\n            max = Math.max(max, node.val);\n            return [true, node.val, node.val, node.val]\n        };\n\n        const [isLeftValid, leftVal, leftMin, leftMax] = dfs(node.left);\n        const [isRightValid, rightVal, rightMin, rightMax] = dfs(node.right);\n\n        /**\n        * To establish that the current node is also a valid BST, we need to verify the following:\n        * 1. Left sub tree is a valid BST\n        * 2. Right sub tree is a valid BST\n        * 3. The values in the left BST are smaller than current node's value\n        * 4. The values in the right BST are greater than current node's value\n        **/\n        if(isLeftValid && isRightValid && node.val > leftMax && node.val < rightMin) {\n            max = Math.max(max, leftVal + rightVal + node.val);\n            return [\n                true,\n                leftVal + rightVal + node.val,\n                /**\n                * 12\n                * / \\\n                * 8 16\n                * \\ /\n                * 9 15\n                * \\ /\n                * 10 14\n                * \\ /\n                * Infinity -Infinity\n                * [Infinity and -Infinity are to depict NoNode cases]\n                **/\n                Math.min(node.val, leftMin),\n                Math.max(node.val, rightMax)\n            ];\n        }\n\n        return [false, 0, leftMax, rightMin];\n    }\n    dfs(root);\n\n    return max;\n};",
        "solution_java": "class Solution {\n\n    int ans = 0;\n    public int maxSumBST(TreeNode root) {\n        solve(root);\n        return ans;\n    }\n    // int[] = { min, max, sum };\n    private int[] solve(TreeNode root) {\n        if(root == null)\n            return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 };\n\n        int[] left = solve(root.left);\n        int[] right = solve(root.right);\n\n        if(root.val > left[1] && root.val < right[0]) {\n             int sum = left[2] + right[2] + root.val;\n             ans = Math.max(ans, sum);\n             return new int[] { Math.min(left[0], root.val), Math.max(root.val, right[1]), sum };\n        }\n\n        return new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = 0 ;\n\n    array<int,4> solve(TreeNode * root){\n        if(!root) return {1,0,INT_MIN,INT_MAX} ;\n\n        array<int,4> l = solve(root->left) ;\n        array<int,4> r = solve(root->right) ;\n\n        if(l[0] and r[0]){\n            if(root->val > l[2] and root->val < r[3]){\n                ans = max({ans,l[1],r[1]}) ;\n                return {1,l[1] + r[1] + root->val,max({root->val,l[2],r[2]}),min({root->val,l[3],r[3]})} ;\n            }\n        }\n\n        return {0,max(l[1],r[1]),INT_MIN,INT_MAX} ;\n    }\n\n    int maxSumBST(TreeNode* root) {\n        auto arr = solve(root) ;\n        return max(ans,arr[1]) ;\n    }\n};"
    },
    {
        "title": "Intersection of Two Arrays",
        "algo_input": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2]\n\n\nExample 2:\n\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [9,4]\nExplanation: [4,9] is also accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 1000\n\t0 &lt;= nums1[i], nums2[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n        nums1.sort()\n        nums2.sort()\n        ans = []\n        i, j = 0, 0\n        while i < len(nums1) and j < len(nums2):\n            if nums1[i] < nums2[j]:\n                i += 1\n            elif nums1[i] > nums2[j]:\n                j += 1\n            else:\n                if len(ans) == 0 or nums1[i] != ans[-1]:\n                    ans.append(nums1[i])\n                i += 1\n                j += 1\n        return ans",
        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\nvar intersection = function(nums1, nums2) {\n    let set = new Set(nums1);\n    let set2 = new Set(nums2);\n    let result = [];\n    for (const val of set) {\n        if (set2.has(val)) {\n            result.push(val);\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] intersection(int[] nums1, int[] nums2) {\n        int[] dp = new int[1000];\n        for(int i:nums1){\n            dp[i]++;\n        }\n        int[] ans = new int[1000];\n\n        //declaring ptr to track ans array index\n        int ptr = 0;\n        for(int i:nums2){\n            if(dp[i] != 0){\n                dp[i] = 0;\n                ans[ptr] = i;\n                ptr++;\n            }\n        }\n        return Arrays.copyOfRange(ans, 0, ptr);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    //what i think is we have to return the intersection elements from both nums\n    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n\n        //result vector which will store those values which will be intersecting in both nums\n        vector<int> result;\n\n        //map intersection, which will store values of all the elements in num1\n        unordered_map<int,int> intersection;\n\n        //map will store all the values of num1(as key),with corresponding value 1\n        for(auto character : nums1)\n        {\n            intersection[character] = 1;\n        }\n\n        //this loop will check if any element of num1 is there in num2? if yes, insert it in result\n        //after inserting it once, make its corresponding value to 0\n        //so that if you find any elements, that is repeating in num2, as well as present in num1\n        //so you dont enter it twice in result, you should enter it once only\n        for(auto character : nums2)\n        {\n            //if found once, it's value would be 1, so entered in result\n            //after it is entered in result, its value we change to 0\n            //so agin if that same element repeats, due to 0 as its value, we avoid pushing it to result\n            if(intersection[character])\n            {\n                result.push_back(character);\n                intersection[character] = 0;\n            }\n        }\n\n        //after getting all the intersecting elements,we return result\n        return result;\n    }\n};"
    },
    {
        "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree",
        "algo_input": "Given two binary trees original and cloned and given a reference to a node target in the original tree.\n\nThe cloned tree is a copy of the original tree.\n\nReturn a reference to the same node in the cloned tree.\n\nNote that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.\n\n&nbsp;\nExample 1:\n\nInput: tree = [7,4,3,null,null,6,19], target = 3\nOutput: 3\nExplanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\n\n\nExample 2:\n\nInput: tree = [7], target =  7\nOutput: 7\n\n\nExample 3:\n\nInput: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\tThe values of the nodes of the tree are unique.\n\ttarget node is a node from the original tree and is not null.\n\n\n&nbsp;\nFollow up: Could you solve the problem if repeated values on the tree are allowed?\n",
        "solution_py": "class Solution:\n    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n        def DFS(node1,node2):\n            if node1==target:\n                return node2\n            if node1 and node1.left is None and node1.right is None:\n                return\n\n            res1 = DFS(node1.left,node2.left) if node1 else None\n            if res1 is not None:\n                return res1\n            res2 = DFS(node1.right,node2.right) if node1 else None\n            if res2 is not None:\n                return res2\n        res=DFS(original,cloned)\n        return res",
        "solution_js": "var getTargetCopy = function(original, cloned, target) {\n    \n    if( original == null ){\n        \n        // Base case aka stop condition\n        // empty tree or empty node\n        return null;\n    }\n    \n    // General cases\n    if( original == target ){\n       \n        // current original node is target, so is cloned\n        return cloned;\n    }\n    \n    // Either left subtree has target, or right subtree has target\n    return getTargetCopy(original.left, cloned.left, target) || \n           getTargetCopy(original.right, cloned.right, target);\n    \n};",
        "solution_java": "class Solution {\n    public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {\n        TreeNode[] ref = new TreeNode[]{null};\n        dfs(cloned, target, ref);\n        return ref[0];\n    }\n    public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) {\n        if (root == null) return;\n        if (root.val == target.val) {\n            ref[0] = root;\n            return;\n        } else {\n            dfs(root.left, target, ref);\n            dfs(root.right, target, ref);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {\n        if(original == target || original == NULL)\n            return cloned;\n        TreeNode* found_left = getTargetCopy(original->left, cloned->left, target);\n        TreeNode* found_right = getTargetCopy(original->right, cloned->right, target);\n        if(found_left)\n            return found_left;\n        else\n            return found_right;\n    }\n};"
    },
    {
        "title": "Average Salary Excluding the Minimum and Maximum Salary",
        "algo_input": "You are given an array of unique integers salary where salary[i] is the salary of the ith employee.\n\nReturn the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500\n\n\nExample 2:\n\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= salary.length &lt;= 100\n\t1000 &lt;= salary[i] &lt;= 106\n\tAll the integers of salary are unique.\n\n",
        "solution_py": "class Solution:\n    def average(self, salary: List[int]) -> float:       \n\n        return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)",
        "solution_js": "var average = function(salary) {\n    let max = salary[0], min = salary[salary.length-1], sum = 0;\n    for(let i = 0; i < salary.length; i++) {\n        if(salary[i] > max) {\n            max = salary[i];\n        }\n        else if(salary[i] < min) {\n            min = salary[i];\n        }\n        sum += salary[i];\n    }\n    return (sum-min-max)/(salary.length-2);\n};",
        "solution_java": "class Solution {\n    public double average(int[] salary) {\n        int n = salary.length-2;\n        int max = Integer.MIN_VALUE;\n        int min = Integer.MAX_VALUE;\n        int sum = 0;\n        for(int i=0;i<n+2;i++){\n            sum += salary[i];\n            max = Math.max(max,salary[i]);\n            min = Math.min(min,salary[i]);\n        }\n        return (double)(sum-max-min)/n;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double average(vector<int>& salary) {\n        int n = salary.size();\n        double ans=0;\n        sort(salary.begin(),salary.end());\n        for(int i=1;i<n-1;i++){\n            ans+=salary[i];\n        }\n        return ans/(n-2);\n    }\n};"
    },
    {
        "title": "Valid Tic-Tac-Toe State",
        "algo_input": "Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.\n\nThe board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.\n\nHere are the rules of Tic-Tac-Toe:\n\n\n\tPlayers take turns placing characters into empty squares ' '.\n\tThe first player always places 'X' characters, while the second player always places 'O' characters.\n\t'X' and 'O' characters are always placed into empty squares, never 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\n&nbsp;\nExample 1:\n\nInput: board = [\"O  \",\"   \",\"   \"]\nOutput: false\nExplanation: The first player always plays \"X\".\n\n\nExample 2:\n\nInput: board = [\"XOX\",\" X \",\"   \"]\nOutput: false\nExplanation: Players take turns making moves.\n\n\nExample 3:\n\nInput: board = [\"XOX\",\"O O\",\"XOX\"]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == 3\n\tboard[i].length == 3\n\tboard[i][j] is either 'X', 'O', or ' '.\n\n",
        "solution_py": "class Solution:\n    def validTicTacToe(self, board: List[str]) -> bool:\n                                            # The two criteria for a valid board are:\n                                            #   1) num of Xs - num of Os is 0 or 1\n                                            #   2) X is not a winner if the # of moves is even, and\n                                            #      O is not a winner if the # of moves is odd.\n\n        d = {'X': 1, 'O': -1, ' ': 0}               # transform the 1x3 str array to a 1x9 int array\n        s = [d[ch] for ch in ''.join(board)]        # Ex: [\"XOX\",\" X \",\"   \"] --> [1,-1,1,0,1,0,0,0,0]\n        sm = sum(s)\n\n        if sm>>1: return False                                      # <-- criterion 1\n        \n        n = -3 if sm == 1 else 3                                    # <-- criterion 2.\n        if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], \n                 s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8],         # the elements of the set are \n                 s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False           # the rows, cols, and diags\n        \n        return True                                                 # <-- both criteria are true",
        "solution_js": "var validTicTacToe = function(board) {\n    let playerX = 0 , playerO = 0;\n    let horizontal = [0,0,0];\n    let vertical = [0,0,0];\n    let diagnol = [0, 0];\n    \n    const transformConfig=(row,col,val)=>{\n        horizontal[row] +=val; \n        vertical[col]+=val;\n        if(row ===col ){\n           diagnol[0]+=val; \n            if(row+col == board.length-1){\n             diagnol[1]+=val; \n            }\n        }else if(row+col == board.length-1){\n             diagnol[1]+=val; \n        }\n    }\n    \n    board.forEach((data,row)=>{\n        data.split(\"\").forEach((turn,col)=>{\n            if(turn == 'X'){\n                playerX++\n                transformConfig(row,col,1)\n            }else if(turn == 'O'){\n                playerO++;\n                transformConfig(row,col,-1);\n            }\n        });\n    });\n    if(playerX<playerO ||playerX-playerO>1 ) return false;\n    if(horizontal.includes(3)&&playerX<= playerO)return false;\n    if(vertical.includes(3)&&playerX <= playerO)return false;\n    if(diagnol.includes(3)&&playerX <=playerO)return false;\n    if(horizontal.includes(-3)&&playerX> playerO)return false;\n    if(vertical.includes(-3)&&playerX> playerO)return false;\n    if(diagnol.includes(-3)&&playerX>playerO)return false;\n    \n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean validTicTacToe(String[] board) {\n        //cnt number of X and O\n        int x = cntNumber('X', board);\n        //this check can be omitted, it can be covered in the second number check.\n        if(x >5){\n            return false;\n        }\n        int o = cntNumber('O', board);\n        if(x < o || x > o + 1){\n            return false;\n        }\n        //if(x <3 ) true, no need to see winning\n        if(o >= 3){\n            //if x has won, but game doesnt stop\n            if(x == o && hasWon('X', board)){\n                return false;\n            }\n            //if o has won, but game doesnt stop\n            if( x > o && hasWon('O', board) ){\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private int cntNumber(char target, String[] board){\n        int res = 0;\n        for(int i = 0; i<3; i++) {\n            for(int j = 0; j<3; j++) {\n                if(target == board[i].charAt(j)){\n                    res++;\n                }\n            }\n        }\n        return res;\n    }\n\n    private boolean hasWon(char target, String[] board){\n        String toWin = Character.toString(target).repeat(3);\n        for(int i = 0; i<3; i++) {\n            if(board[i].equals(toWin)){\n                return true;\n            }\n        }\n        for(int j = 0; j<3; j++) {\n            boolean col = true;\n            for(int i = 0; i<3; i++) {\n                col = col && target == board[i].charAt(j);\n                if(!col){\n                    break;\n                }\n            }\n            if(col){\n                return true;\n            }\n        }\n        //check diagonal. If center is not target, not possible to form diag win.\n        if(target != board[1].charAt(1)){\n            return false;\n        }\n\n        boolean diagonal1 = target == board[0].charAt(0);\n        //only proceed if the first letter match. Otherwise might get false positive\n        if(diagonal1){\n            if(target == board[2].charAt(2)){\n                return true;\n            }\n        }\n\n        boolean diagonal2 = target == board[0].charAt(2);\n        if(diagonal2){\n            if(target == board[2].charAt(0)){\n                return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool win(vector<string> board, char player, int size){\n        int row_win=0, col_win=0, diagonal_win=0, rev_diagonal_win=0;\n        \n        for(int i=0;i<3;i++){\n            \n            row_win=0; \n            col_win=0;\n            \n            for(int j=0;j<3;j++){\n                \n                if(player == board[i][j]){\n                    row_win++; \n                    if(row_win == 3)\n                        return 1;\n                }\n                \n                if(player == board[j][i]){\n                    col_win++;\n                    if(col_win == 3)\n                        return 1;\n                }\n                    \n                if(i==j && player==board[i][j]){\n                    diagonal_win++;\n                }\n                \n                if(i+j == size-1 && player==board[i][j]){\n                    rev_diagonal_win++;\n                }\n                    \n            }\n        }\n        \n        if(diagonal_win==3 || rev_diagonal_win==3)\n            return 1;\n        \n        return 0;\n    }\n    \n    bool validTicTacToe(vector<string>& board) {\n        int count_x=0, count_o=0, size = board.size();\n        for(auto i:board){\n            for(auto j:i){\n                if(j=='X') count_x++;\n                else if(j=='O') count_o++;\n            }\n        }\n        if(count_o>count_x || count_x-count_o>=2)\n            return false;\n        if(count_x>=3 && count_x==count_o && win(board, 'X', size))\n            return false;\n        if(count_o>=3 && count_x>count_o && win(board, 'O', size))\n            return false;\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Number of Visible People in a Queue",
        "algo_input": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.\n\nA person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i &lt; j and min(heights[i], heights[j]) &gt; max(heights[i+1], heights[i+2], ..., heights[j-1]).\n\nReturn an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.\n\n&nbsp;\nExample 1:\n\n\n\nInput: heights = [10,6,8,5,11,9]\nOutput: [3,1,2,1,1,0]\nExplanation:\nPerson 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.\n\n\nExample 2:\n\nInput: heights = [5,1,2,3,10]\nOutput: [4,1,1,1,0]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == heights.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= heights[i] &lt;= 105\n\tAll the values of heights are unique.\n\n",
        "solution_py": "class Solution:\n    def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n        ans=[]\n        stack=[]\n        n=len(heights)\n        for i in range(n-1,-1,-1):\n            if len(stack)==0:\n                ans.append(0)\n                stack.append(heights[i])\n            else:\n                if heights[i]<stack[-1]:\n                    ans.append(1)\n                    stack.append(heights[i])\n                else:\n                    ctr=0\n                    while(len(stack)>0 and stack[-1]<heights[i]):\n                        ctr+=1\n                        stack.pop()\n                    if len(stack)==0:\n                        ans.append(ctr)\n                    else:\n                        ans.append(ctr+1)\n                    stack.append(heights[i])\n        return ans[::-1]",
        "solution_js": "var visibleToRight = function(heights){\n    const result = new Array(heights.length).fill(0)\n    const stack = []\n\n    let i = heights.length-1\n    \n    // loop from right to left\n    while(i >= 0){ \n        let popCount = 0\n        \n        // Keep Popping untill top ele is smaller\n        while(stack.length > 0 && stack[stack.length-1][0] < heights[i]){\n\t\t\tstack.pop()\n            popCount+=1\n        }\n        \n        /////////////////////\n        /// After Popping ///\n        ////////////////////\n        \n        // Case1: if ALL elements got popped\n        if(stack.length === 0)\n            result[i] = popCount // mark\n        \n        // Case2: if NO elements were popped\n        else if(popCount === 0)\n            result[i] = 1 // mark\n            \n        // Case3: if SOME elements were popped\n        else\n            result[i] = popCount+1 // mark\n        \n        // store\n        stack.push([heights[i],popCount])\n        \n        i-=1\n    }\n    \n    return result\n}\nvar canSeePersonsCount = function(heights) {\n    return visibleToRight(heights)\n};",
        "solution_java": "class Solution {\n    public int[] canSeePersonsCount(int[] heights) {\n        Stack<Integer> stack = new Stack<>();\n        int result[] = new int[heights.length];\n        for(int i = heights.length - 1; i >= 0; i--) {\n            int visibility = 0;\n            while(!stack.isEmpty() && heights[i] > stack.peek()) {\n                stack.pop();\n                visibility++;\n            }\n            if(!stack.isEmpty()) visibility++;\n            stack.push(heights[i]);\n            result[i] = visibility;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> canSeePersonsCount(vector<int>& h) {\n        vector<int>ans ;\n        stack<int>s ;\n        int a = 0;\n        for(int i = h.size()-1 ; i >= 0 ; i--){\n            if(s.empty()){\n                ans.push_back(a);\n                s.push(h[i]);a++;\n            }\n            else{\n                if(s.top() > h[i]){\n                    ans.push_back(1);\n                    s.push(h[i]);a++;\n                }\n                else{\n                int b = 0;\n                while(!s.empty() && s.top() < h[i]){\n                    s.pop() ; a--;b++;\n                }\n                if(!s.empty())b++;\n                ans.push_back(b);\n                s.push(h[i]); a++;\n                } \n            }\n        }\n        reverse(ans.begin() , ans.end());\n        return ans;\n    }\n};"
    },
    {
        "title": "Largest Number After Mutating Substring",
        "algo_input": "You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].\n\nYou may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\n\nReturn a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.\n\nA substring is a contiguous sequence of characters within the string.\n\n&nbsp;\nExample 1:\n\nInput: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\nOutput: \"832\"\nExplanation: Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.\n\n\nExample 2:\n\nInput: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\nOutput: \"934\"\nExplanation: Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.\n\n\nExample 3:\n\nInput: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\nOutput: \"5\"\nExplanation: \"5\" is already the largest number that can be created, so return it.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 105\n\tnum consists of only digits 0-9.\n\tchange.length == 10\n\t0 &lt;= change[d] &lt;= 9\n\n",
        "solution_py": "class Solution:\ndef maximumNumber(self, num: str, change: List[int]) -> str:\n    flag=0\n    ls=list(num)\n    for i in range(len(ls)):\n        k=int(ls[i])\n        if change[k]>k:\n            ls[i]=str(change[k])\n            flag=1\n        elif flag==1 and change[k]<k:\n            break\n    \n    return \"\".join(ls)",
        "solution_js": "var maximumNumber = function(num, change) {\n    const digits = num.split(\"\");\n\n    let started = false;\n\n    for (let i = 0; i < digits.length; ++i) {\n        const origDig = digits[i];\n        const changeDig = change[origDig];\n\n        if (changeDig > origDig) {\n            started = true;\n            digits[i] = changeDig;\n        }\n        else if (changeDig < origDig && started) {\n            break;\n        }\n    }\n\n    return digits.join(\"\");\n};",
        "solution_java": "class Solution {\n    public String maximumNumber(String num, int[] change) {\n        int i=0, n=num.length(), startIndex=-1, substringLength=0;\n        \n        // traverse through each digit in the input string\n        while(i<n) {\n            int digit=num.charAt(i)-48;\n            // when we encounter a digit which has greater change\n            if(change[digit] > digit) {\n                startIndex = i;\n                // keep on replacing subsequent characters with with the change if they also have greater change\n                while(i<n) {\n                    digit=num.charAt(i)-48;\n                    if(change[digit] < digit) {\n                        break;\n                    }\n                    i+=1;\n                }\n                substringLength = i-startIndex;\n                break;\n            }\n            i+=1;\n        }\n        \n        // Note: Using String Builder to ensure linear time complexity as java strings are immutable\n        StringBuilder result=new StringBuilder(\"\");\n        for(int j=0; j<n; j++) {\n            int digit=num.charAt(j)-48;\n            if(j>=startIndex && j<startIndex+substringLength) {\n                result.append(change[digit]);    \n            } else {\n                result.append(digit);   \n            }\n        }\n        \n        return result.toString();\n    }\n}",
        "solution_c": "//change first longest encountered substring from left which can make string greater in value\nclass Solution {\npublic:\n    string maximumNumber(string num, vector<int>& change){\n        int n=num.size();\n        for(int i=0;i<n;i++){\n            int x=num[i]-'0';\n            if(x < change[x]){//checking whether mutating this char will increment the value or not\n            //the mutation continues till mutating the char will increase the value\n                while(i<n and num[i]-'0'<=change[num[i]-'0']){\n                    num[i++]=change[num[i]-'0']+'0';\n                }\n                //break the loop when substring ends\n                break;\n            }\n        }\n        return num;\n    }\n};"
    },
    {
        "title": "Keyboard Row",
        "algo_input": "Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.\n\nIn the American keyboard:\n\n\n\tthe first row consists of the characters \"qwertyuiop\",\n\tthe second row consists of the characters \"asdfghjkl\", and\n\tthe third row consists of the characters \"zxcvbnm\".\n\n\n&nbsp;\nExample 1:\n\nInput: words = [\"Hello\",\"Alaska\",\"Dad\",\"Peace\"]\nOutput: [\"Alaska\",\"Dad\"]\n\n\nExample 2:\n\nInput: words = [\"omk\"]\nOutput: []\n\n\nExample 3:\n\nInput: words = [\"adsdf\",\"sfd\"]\nOutput: [\"adsdf\",\"sfd\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 20\n\t1 &lt;= words[i].length &lt;= 100\n\twords[i] consists of English letters (both lowercase and uppercase).&nbsp;\n\n",
        "solution_py": "class Solution:\n    def findWords(self, words: List[str]) -> List[str]:\n        first_row = \"qwertyuiopQWERTYUIOP\"\n        second_row = \"asdfghjklASDFGHIJKL\"\n        third_row = \"zxcvbnmZXCVBNM\"\n        first_list = []\n        second_list = []\n        third_list = []\n        one_line_words = []\n\n        for word in words:\n            if set(word).issubset(first_row):\n                one_line_words.append(word)\n            if set(word).issubset(second_row):\n                one_line_words.append(word)\n            if set(word).issubset(third_row):\n                one_line_words.append(word)\n\n        return one_line_words",
        "solution_js": "var findWords = function(words) {\nconst firstRow = {\"q\":true,\"w\":true,\"e\":true,\"r\":true,\"t\":true,\"y\":true,\"u\":true,\"i\":true,\"o\":true,\"p\":true }\nconst secondRow = {\"a\":true,\"s\":true,\"d\":true,\"f\":true,\"g\":true,\"h\":true,\"j\":true,\"k\":true,\"l\":true }\nconst thirdRow = {\"z\":true,\"x\":true,\"c\":true,\"v\":true,\"b\":true,\"n\":true,\"m\":true }\nlet result = [];\n\nconst helperFunc= (word)=>{\n    let targetRow;\n        //Determine in which row the word should be;\n        if(firstRow[word[0].toLowerCase()]) targetRow = firstRow;\n        if(secondRow[word[0].toLowerCase()]) targetRow = secondRow;\n        if(thirdRow[word[0].toLowerCase()]) targetRow = thirdRow;\n    \n    for(let i = 1;i<word.length;i++) {\n        if(!targetRow[word[i].toLowerCase()]) {\n            return false;\n        }\n    }\n    return true;\n    }\n\n    for(let i =0;i<words.length;i++) {\n        if(helperFunc(words[i])) {\n            result.push(words[i])\n        }\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public String[] findWords(String[] words) {\n        String row1 = \"qwertyuiop\";\n        String row2 = \"asdfghjkl\";\n        String row3 = \"zxcvbnm\";\n        String res = \"\";\n        for(int i=0; i<words.length; i++) {\n            int sum1 = 0;\n            int sum2 = 0;\n            int sum3 = 0;\n            for(int j=0; j<words[i].length(); j++) {\n                if(row1.contains(\"\" + words[i].toLowerCase().charAt(j))) {\n                    sum1++;\n                }\n                else if(row2.contains(\"\" + words[i].toLowerCase().charAt(j))) {\n                    sum2++;\n                }\n                else if(row3.contains(\"\" + words[i].toLowerCase().charAt(j))) {\n                    sum3++;\n                }\n            }\n            if(words[i].length()==sum1) {\n                res += i;\n            }\n            else if(words[i].length()==sum2) {\n            \tres += i;\n            }\n            else if(words[i].length()==sum3) {\n            \tres += i;\n            }\n        }\n\t\tString[] resArr = new String[res.length()];\n\t\tfor(int i=0; i<resArr.length; i++) {\n\t\t\tresArr[i] = words[Integer.parseInt(\"\" + res.charAt(i))];\n\t\t\tSystem.out.println(resArr[i]);\n\t\t}\n        return resArr;\n    }\n}",
        "solution_c": "class DSU {\n    vector<int> parent, size;\n\n    vector<int> Q{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};\n    vector<int> A{'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};\n    vector<int> Z{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};\n\npublic:\n    DSU(){\n        for(int i= 0;i<123;i++) parent.push_back(i),size.push_back(1);\n        for(int i = 0; i<Q.size()-1;i++) findUnion(Q[i],Q[i+1]);\n        for(int i = 0; i<A.size()-1;i++) findUnion(A[i],A[i+1]);\n        for(int i = 0; i<Z.size()-1;i++) findUnion(Z[i],Z[i+1]);\n    }\n\n    int findParent(int x){\n        if(x==parent[x]) return x;\n        return parent[x] = findParent(parent[x]);\n    }\n\n    void findUnion(int a, int b){\n        a = findParent(a);\n        b = findParent(b);\n        if(a!=b) if(size[b]>size[a]) swap(a,b);parent[b] = a,size[a]+=size[b];\n    }\n};\n\nclass Solution {\npublic:\n    vector<string> findWords(vector<string>& words) {\n        int n = words.size();\n        DSU dsu;\n        vector<string> ans;\n        for(int i = 0;i<n;i++){\n            int ss = words[i].size();\n            string s = words[i];\n            if(ss==1) {ans.push_back(s);continue;}\n\n            bool sameSet = true;\n            for(int j = 0;j<ss-1;j++)\n                if(dsu.findParent(s[j])!=dsu.findParent(s[j+1])){\n                    sameSet = false;break;\n                }\n            if(sameSet)ans.push_back(s);\n        }return ans;\n    }\n};"
    },
    {
        "title": "Jump Game VI",
        "algo_input": "You are given a 0-indexed integer array nums and an integer k.\n\nYou are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.\n\nYou want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.\n\nReturn the maximum score you can get.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\n\n\nExample 2:\n\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\n\n\nExample 3:\n\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length, k &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def maxResult(self, nums, k):\n        deq, n = deque([0]), len(nums)\n\n        for i in range(1, n):\n            while deq and deq[0] < i - k: deq.popleft()\n            nums[i] += nums[deq[0]]   \n            while deq and nums[i] >= nums[deq[-1]]: deq.pop()\n            deq.append(i)\n            \n        return nums[-1]",
        "solution_js": "var maxResult = function(nums, k) {\n   let n = nums.length, deq = [n-1]\n    for (let i = n - 2; ~i; i--) {\n        if (deq[0] - i > k) deq.shift()\n        nums[i] += nums[deq[0]]\n        while (deq.length && nums[deq[deq.length-1]] <= nums[i]) deq.pop()\n        deq.push(i)\n    }\n    return nums[0] \n};",
        "solution_java": "class Solution {\n    public int maxResult(int[] nums, int k) {\n        int n = nums.length, a = 0, b = 0;\n        int[] deq = new int[n];\n        deq[0] = n - 1;\n        for (int i = n - 2; i >= 0; i--) {\n            if (deq[a] - i > k) a++;\n            nums[i] += nums[deq[a]];\n            while (b >= a && nums[deq[b]] <= nums[i]) b--;\n            deq[++b] = i;\n        }\n        return nums[0];\n    }\n}",
        "solution_c": "#define pii pair<int, int>\nclass Solution {\npublic:\n    int maxResult(vector<int>& nums, int k)\n    {\n        int n=nums.size();\n        int score[n];\n        priority_queue<pii> pq;\n        \n        for(int i=n-1 ; i>=0 ; i--)\n        {\n            while(pq.size() && pq.top().second>i+k)\n                pq.pop();\n            \n            score[i]=nums[i];\n            score[i]+=(pq.size() ? pq.top().first : 0);\n            pq.push({score[i], i});\n        }\n        \n        return score[0];\n    }\n};"
    },
    {
        "title": "Check If a String Can Break Another String",
        "algo_input": "Given two strings: s1 and s2 with the same&nbsp;size, check if some&nbsp;permutation of string s1 can break&nbsp;some&nbsp;permutation of string s2 or vice-versa. In other words s2 can break s1&nbsp;or vice-versa.\n\nA string x&nbsp;can break&nbsp;string y&nbsp;(both of size n) if x[i] &gt;= y[i]&nbsp;(in alphabetical order)&nbsp;for all i&nbsp;between 0 and n-1.\n\n&nbsp;\nExample 1:\n\nInput: s1 = \"abc\", s2 = \"xya\"\nOutput: true\nExplanation: \"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".\n\n\nExample 2:\n\nInput: s1 = \"abe\", s2 = \"acd\"\nOutput: false \nExplanation: All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\n\n\nExample 3:\n\nInput: s1 = \"leetcodee\", s2 = \"interview\"\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\ts1.length == n\n\ts2.length == n\n\t1 &lt;= n &lt;= 10^5\n\tAll strings consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n        s1, s2 = sorted(s1), sorted(s2)\n        return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2))",
        "solution_js": "const canAbreakB = (s1, s2) => {\n    const s1Heap = new MinPriorityQueue();\n    const s2Heap = new MinPriorityQueue();\n    \n    for(let c of s1) {\n        s1Heap.enqueue(c.charCodeAt(0));\n    }\n    \n    for(let c of s2) {\n        s2Heap.enqueue(c.charCodeAt(0));\n    }\n    \n    while(s2Heap.size()) {\n        const s1Least = s1Heap.dequeue().element;\n        const s2Least = s2Heap.dequeue().element;\n        if(s1Least > s2Least) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvar checkIfCanBreak = function(s1, s2) {\n    return canAbreakB(s1, s2) || canAbreakB(s2, s1);\n};",
        "solution_java": "class Solution {\n    public boolean checkIfCanBreak(String s1, String s2) {\n        int n = s1.length();\n        char[] one = s1.toCharArray();\n        char[] two = s2.toCharArray();\n        Arrays.sort(one);\n        Arrays.sort(two);\n        if(check(one,two,n) || check(two,one,n)){\n            return true;\n        }\n        return false;\n    }\n    public boolean check(char[] one,char[] two,int n){\n        for(int i=0;i<n;i++){\n            if(one[i]-'a'>two[i]-'a'){\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    bool checkIfCanBreak(string s1, string s2)\n    {\n       vector<int>freq1(26,0),freq2(26,0);\n        for(int i=0;i<s1.size();i++)\n        {\n            freq1[s1[i]-'a']++;\n        }\n        for(int i=0;i<s2.size();i++)\n        {\n            freq2[s2[i]-'a']++;\n        }\n        int count1 =0,count2=0;\n        bool check1 = true,check2=true;\n        for(int i=0;i<25;i++)\n        {\n            count1 += freq1[i]-freq2[i];\n            count2 += freq2[i] - freq1[i];\n            if(count1<0)\n            {\n                check1 = false;\n            }\n            if(count2<0)\n            {\n                check2 = false;\n            }\n            if(count1<0 && count2<0)\n            {\n                break;\n            }\n        }\n        return check1 || check2;\n    }\n};"
    },
    {
        "title": "Sign of the Product of an Array",
        "algo_input": "There is a function signFunc(x) that returns:\n\n\n\t1 if x is positive.\n\t-1 if x is negative.\n\t0 if x is equal to 0.\n\n\nYou are given an integer array nums. Let product be the product of all values in the array nums.\n\nReturn signFunc(product).\n\n&nbsp;\nExample 1:\n\nInput: nums = [-1,-2,-3,-4,3,2,1]\nOutput: 1\nExplanation: The product of all values in the array is 144, and signFunc(144) = 1\n\n\nExample 2:\n\nInput: nums = [1,5,0,2,-3]\nOutput: 0\nExplanation: The product of all values in the array is 0, and signFunc(0) = 0\n\n\nExample 3:\n\nInput: nums = [-1,1,-1,1,-1]\nOutput: -1\nExplanation: The product of all values in the array is -1, and signFunc(-1) = -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t-100 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def arraySign(self, nums: List[int]) -> int:\n\t\treturn 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1",
        "solution_js": "var arraySign = function(nums) {\n    // use filter to find total negative numbers in the array\n    let negativeCount = nums.filter(n => n<0).length;\n\n    // check if the nums array has zero. If it does, then return 0\n    if(nums.includes(0)) return 0;\n\n    // If negativeCount variable is even answer is 1 else -1\n    return negativeCount % 2 === 0 ? 1 : -1\n};",
        "solution_java": "class Solution {\n    public int arraySign(int[] nums) {\n        int prod=1;\n        for(int i=0;i<nums.length;i++){\n            int val=signFunc(nums[i]);\n            prod*=val;\n        }\n        return prod;\n    }\n    \n    private int signFunc(int x){\n        if(x<0) return -1;\n        else if(x>0) return 1;\n        return 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int arraySign(vector<int>& nums) {\n        int res = 1;\n        for(auto x : nums)\n        {\n            if(x < 0) res *= -1;\n            else if(x == 0) return 0;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Flip Binary Tree To Match Preorder Traversal",
        "algo_input": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.\n\nAny node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:\n\nFlip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.\n\nReturn a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2], voyage = [2,1]\nOutput: [-1]\nExplanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\n\n\nExample 2:\n\nInput: root = [1,2,3], voyage = [1,3,2]\nOutput: [1]\nExplanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\n\nExample 3:\n\nInput: root = [1,2,3], voyage = [1,2,3]\nOutput: []\nExplanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\tn == voyage.length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= Node.val, voyage[i] &lt;= n\n\tAll the values in the tree are unique.\n\tAll the values in voyage are unique.\n\n",
        "solution_py": "class Solution:\n    def flipMatchVoyage(self, root, voyage):\n        \n        # ------------------------------\n        \n        def dfs(root):\n            \n            if not root:\n                # base case aka stop condition\n\t\t\t\t# empty node or empty tree\n                return True\n            \n            \n            ## general cases\n            if root.val != voyage[dfs.idx]:\n                \n                # current node mismatch, no chance to make correction by flip\n                return False\n            \n            # voyage index moves forward\n            dfs.idx += 1\n            \n            if root.left and (root.left.val != voyage[dfs.idx]):\n                \n                # left child mismatch, flip with right child if right child exists\n                root.right and result.append( root.val )\n                \n                # check subtree in preorder DFS with child node flip\n                return dfs(root.right) and dfs(root.left)\n                \n            else:\n                \n                # left child match, check subtree in preorder DFS\n                return dfs(root.left) and dfs(root.right)\n                \n      \n        # --------------------------\n        \n        # flip sequence\n        result = []\n        \n        # voyage index during dfs\n        dfs.idx = 0\n        \n        # start checking from root node\n        good = dfs(root)\n        \n        return result if good else [-1]",
        "solution_js": "var flipMatchVoyage = function(root, voyage) {\n    const output = []\n    let idx = 0;\n    \n    function run(node) {\n        if(!node) return true;\n        if(voyage[idx] !== node.val) return false;\n        idx++;\n        \n        if(node.left && node.left.val !== voyage[idx]) {\n            output.push(node.val);\n            return run(node.right) && run(node.left);\n        }\n        return run(node.left) && run(node.right);\n    }\n    return run(root) ? output : [-1];\n};",
        "solution_java": "class Solution {\n    private int i = 0;\n    \n    public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {\n        List<Integer> list = new ArrayList<>();\n        flipMatchVoyage(root,voyage,list);\n        return list;\n    }\n    \n    private void flipMatchVoyage(TreeNode root, int[] voyage,List<Integer> list) {\n        if(root == null || list.contains(-1)){\n            return;\n        }\n        if(root.val != voyage[i++]){\n            list.clear();\n            list.add(-1);\n            return;\n        }\n        if(root.left != null && root.right != null && root.left.val != voyage[i]){\n            list.add(root.val);\n            flipMatchVoyage(root.right,voyage,list);\n            flipMatchVoyage(root.left,voyage,list);\n            return;\n        }\n        flipMatchVoyage(root.left,voyage,list);    \n        flipMatchVoyage(root.right,voyage,list);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){\n        if(root == NULL || ind == voyage.size()){\n            ind--;\n            return true;\n        }\n\n        // Not possible to create\n        if(root->val != voyage[ind]){\n            ans.clear();\n            ans.push_back(-1);\n            return false;\n        }\n\n        // If voyage value not equal to its left child, then swap both childs and check\n        if(root->left && root->left->val != voyage[ind+1]){\n            TreeNode *temp = root->left;\n            root->left = root->right;\n            root->right = temp;\n\n            // Pusing root into ans\n            ans.push_back(root->val);\n        }\n\n        return helper(++ind, root->left, voyage, ans) &&\n            helper(++ind, root->right, voyage, ans);\n    }\n\n    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {\n        int ind = 0;\n        vector<int> ans;\n        helper(ind, root, voyage, ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Next Greater Node In Linked List",
        "algo_input": "You are given the head of a linked list with n nodes.\n\nFor each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.\n\nReturn an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.\n\n&nbsp;\nExample 1:\n\nInput: head = [2,1,5]\nOutput: [5,5,0]\n\n\nExample 2:\n\nInput: head = [2,7,4,3,5]\nOutput: [7,0,5,5,0]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 &lt;= n &lt;= 104\n\t1 &lt;= Node.val &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n        stack = []\n        ans = []\n        node = head\n        \n        i = 0\n        while node is not None:\n            while stack and stack[-1][0] < node.val:\n                ans[stack[-1][1]] = node.val\n                stack.pop()\n            \n            stack.append((node.val, i))\n            ans.append(0)\n            i += 1\n            node = node.next\n            \n        return ans",
        "solution_js": "var nextLargerNodes = function(head) {\n    let arr = [];\n    while(head){\n        arr.push(head.val);\n        head = head.next\n    }\n    return nextGreaterElement(arr)\n    \n};\n\nfunction nextGreaterElement(arr){\n    let temp = [];\n    let n = arr.length;\n    let stack = [];\n    for(let i=n-1; i>=0; i--){\n        while(stack.length != 0 && arr[stack[stack.length-1]] <= arr[i]){\n            stack.pop()\n        }\n        \n        if(stack.length == 0){\n            temp[i] = 0\n        }else{\n            temp[i] = arr[stack[stack.length-1]]\n        }\n        stack.push(i)\n    }\n    return temp\n}",
        "solution_java": "class Solution {\n    public int[] nextLargerNodes(ListNode head) {\n        ListNode length=head;\n        int l=0;\n        while(length!=null)\n        {\n            length=length.next;\n            l++;\n        }\n        int[] res=new int[l];\n        int i=0;\n        ListNode temp=head;\n\n        while(temp!=null)\n        {\n            ListNode temp1=temp.next;\n            int max=temp.val;\n\n            while(temp1!=null)\n            {\n                if(temp1.val>max)\n                {\n                    max=temp1.val;\n                    res[i]=max;\n                    break;\n                }\n\n                temp1=temp1.next;\n            }\n            temp=temp.next;\n            i++;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nextLargerNodes(ListNode* head) {\n        vector<int> ans;\n        ListNode* curr = head;\n        if(head->next == NULL){\n            ans.push_back(0);\n            return ans;\n        }\n\n        while(curr != NULL){\n            ListNode* next = curr->next;\n            while(next != NULL){\n                if(next->val > curr->val){\n                    ans.push_back(next->val);\n                    break;\n                }\n                next = next->next;\n            }\n            if(next == NULL){\n                ans.push_back(0);\n            }\n            curr = curr->next;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Kth Missing Positive Number",
        "algo_input": "Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.\n\nReturn the kth positive integer that is missing from this array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th&nbsp;missing positive integer is 9.\n\n\nExample 2:\n\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 1000\n\t1 &lt;= arr[i] &lt;= 1000\n\t1 &lt;= k &lt;= 1000\n\tarr[i] &lt; arr[j] for 1 &lt;= i &lt; j &lt;= arr.length\n\n\n&nbsp;\nFollow up:\n\nCould you solve this problem in less than O(n) complexity?\n",
        "solution_py": "class Solution:\n    def findKthPositive(self, arr: List[int], k: int) -> int:\n        arr = set(arr)\n        i = 0\n        missed = 0\n        while missed != k:\n            i += 1\n            if i not in arr:\n                missed += 1\n        return i",
        "solution_js": "var findKthPositive = function(arr, k) {\n    let newArr = [];\n    for(let i=0,j=1; j<=arr.length+k; j++){\n        arr[i]!=j?newArr.push(j):i++;\n    }\n    return newArr[k-1]; \n    \n};",
        "solution_java": "class Solution {\n    public int findKthPositive(int[] arr, int k) {\n        if(arr[0] > k) {\n            return k;\n        }\n        \n        for(int i=0; i<arr.length; i++) {\n            if(arr[i] <= k) {\n                k++;\n            }else {\n                break;\n            }\n        }\n        return k;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findKthPositive(vector<int>& arr, int k) {\n\n    int n=arr.size();\n    if(arr[n-1]==n)\n        return n+k;\n    else\n    {\n        int start=0;\n        int end=n-1;\n        int ans;\n        while(start<=end)\n        {\n            int mid=start+(end-start)/2;\n            if((arr[mid]-(mid+1))<k)\n                start=mid+1;\n            else\n                end=mid-1;\n        }\n        return start+k;\n    }\n\n    }\n};"
    },
    {
        "title": "Wiggle Sort II",
        "algo_input": "Given an integer array nums, reorder it such that nums[0] &lt; nums[1] &gt; nums[2] &lt; nums[3]....\n\nYou may assume the input array always has a valid answer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,5,1,1,6,4]\nOutput: [1,6,1,5,1,4]\nExplanation: [1,4,1,5,1,6] is also accepted.\n\n\nExample 2:\n\nInput: nums = [1,3,2,2,3,1]\nOutput: [2,3,1,3,1,2]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t0 &lt;= nums[i] &lt;= 5000\n\tIt is guaranteed that there will be an answer for the given input nums.\n\n\n&nbsp;\nFollow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?",
        "solution_py": "class Heap:\n\tdef __init__(self):\n\t\tself.q = []\n\tdef push(self,data):\n\t\ti = len(self.q)\n\t\tself.q.append(data)\n\t\twhile i>0:\n\t\t\tif self.q[i] > self.q[(i-1)//2]:\n\t\t\t\tself.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i]\n\t\t\t\ti = (i-1)//2\n\t\t\telse: return \n\tdef pop(self):\n\t\tif len(self.q)==0:return\n\t\tself.q[0] = self.q[-1]\n\t\tself.q.pop()\n\t\tdef heapify(i):\n\t\t\tind = i\n\t\t\tl = 2*i+1\n\t\t\tr = 2*i+2\n\t\t\tif r<len(self.q) and self.q[ind] < self.q[r]: ind = r\n\t\t\tif l<len(self.q) and self.q[ind] < self.q[l]: ind = l            \n\t\t\tif ind != i:\n\t\t\t\tself.q[i], self.q[ind] = self.q[ind], self.q[i]\n\t\t\t\theapify(ind)\n\t\theapify(0)\n\tdef top(self):  \n\t\treturn self.q[0] \n\n\nclass Solution:\n\tdef wiggleSort(self, nums: List[int]) -> None:\n\t\tn = len(nums)\n\t\th = Heap()\n\t\tfor i in nums: h.push(i)\n\t\tfor i in range(1,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()\n\t\tfor i in range(0,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()",
        "solution_js": "var wiggleSort = function(nums) {\n    nums.sort((a,b) => a - b);\n\n    let temp = [...nums];\n\n    let low = Math.floor((nums.length-1)/2), high = nums.length-1;\n\n    for(let i=0; i < nums.length; i++){\n        if(i % 2 === 0){\n            nums[i] = temp[low];\n            low--;\n        }else{\n            nums[i] = temp[high];\n            high--;\n        }\n    }\n\n    return nums;\n};",
        "solution_java": "class Solution {\n    public void wiggleSort(int[] nums) {\n        int a[]=nums.clone();\n        Arrays.sort(a);\n        int left=(nums.length-1)/2;\n        int right=nums.length-1;\n        for(int i=0;i<nums.length;i++){\n            if(i%2==0){\n                nums[i]=a[left];\n                left--;\n            }\n            else{\n                nums[i]=a[right];\n                right--;\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void wiggleSort(vector<int>& nums) {\n\n        priority_queue<int> pq;\n        for(auto &i : nums)\n            pq.push(i);\n\n        for(int i = 1; i < nums.size(); i += 2)\n            nums[i] = pq.top(), pq.pop();\n\n        for(int i = 0; i < nums.size(); i += 2)\n            nums[i] = pq.top(), pq.pop();\n    }\n};"
    },
    {
        "title": "Count Vowels Permutation",
        "algo_input": "Given an integer n, your task is to count how many strings of length n can be formed under the following rules:\n\n\n\tEach character is a lower case vowel&nbsp;('a', 'e', 'i', 'o', 'u')\n\tEach vowel&nbsp;'a' may only be followed by an 'e'.\n\tEach vowel&nbsp;'e' may only be followed by an 'a'&nbsp;or an 'i'.\n\tEach vowel&nbsp;'i' may not be followed by another 'i'.\n\tEach vowel&nbsp;'o' may only be followed by an 'i' or a&nbsp;'u'.\n\tEach vowel&nbsp;'u' may only be followed by an 'a'.\n\n\nSince the answer&nbsp;may be too large,&nbsp;return it modulo 10^9 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 5\nExplanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n\n\nExample 2:\n\nInput: n = 2\nOutput: 10\nExplanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n\n\nExample 3:&nbsp;\n\nInput: n = 5\nOutput: 68\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 10^4\n\n",
        "solution_py": "class Solution:\n    def countVowelPermutation(self, n: int) -> int:\n        # dp[i][j] means the number of strings of length i that ends with the j-th vowel.\n        dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]\n        moduler = math.pow(10, 9) + 7\n        for i in range(1, n):\n            # For vowel a\n            dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler\n            # For vowel e\n            dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler\n            # For vowel i\n            dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler\n            # For vowel o\n            dp[i][3] = (dp[i - 1][2]) % moduler\n            # For vowel u\n            dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler\n\n        return int(sum(dp[-1]) % moduler)",
        "solution_js": "var countVowelPermutation = function(n) {\n    let a = 1, e = 1, i = 1, o = 1, u = 1, mod = 1000000007\n    while(n-- > 1){\n        let new_a = a % mod, new_e = e % mod, new_i = i % mod, new_o = o % mod, new_u = u % mod\n        a = new_e + new_i + new_u\n        e = new_a + new_i\n        i = new_e + new_o\n        o = new_i\n        u = new_i + new_o\n    }\n    return (a + e + i + o + u) % mod\n};",
        "solution_java": "class Solution {\n    private long[][] dp;\n    private int mod = (int)1e9 + 7;\n\n    public int countVowelPermutation(int n) {\n        dp = new long[6][n+1];\n        if(n == 1) return 5;\n\n        for(int i = 0; i < 5; i++)\n            dp[i][0] = 1;\n\n        helper(n,'z');\n        return (int)dp[5][n];\n    }\n\n    private long helper(int n, char vowel)\n    {\n        long ans = 0;\n        if(n == 0) return 1;\n\n        if(vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels\n        {\n            ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'i') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n            dp[5][n] = ans;\n        }\n        // from here as per our assumptions of Vowels we will make calls & store results\n        else if(vowel == 'a') // for Nth number we would store Result for \"a\" in dp[0][n]\n        {\n            if(dp[0][n] != 0) return dp[0][n];\n            ans = (ans + helper(n-1,'e'))%mod;\n            dp[0][n] = ans;\n        }\n\n        else if(vowel == 'e') // for Nth number we would store Result for \"e\" in dp[1][n]\n        {\n            if(dp[1][n] != 0) return dp[1][n];\n            ans = (ans + helper(n-1,'a') + helper(n-1,'i'))%mod;\n            dp[1][n] = ans;\n        }\n\n        else if(vowel == 'i') // for Nth number we would store Result for \"i\" in dp[2][n]\n        {\n            if(dp[2][n] != 0) return dp[2][n];\n            ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n            dp[2][n] = ans;\n        }\n\n        else if(vowel == 'o') // for Nth number we would store Result for \"o\" in dp[3][n]\n        {\n            if(dp[3][n] != 0) return dp[3][n];\n            ans = (ans + helper(n-1,'i') + helper(n-1,'u'))%mod;\n            dp[3][n] = ans;\n        }\n\n        else // for Nth number we would store Result for \"u\" in dp[4][n]\n        {\n            if(dp[4][n] != 0) return dp[4][n];\n            ans = (ans + helper(n-1,'a'))%mod;\n            dp[4][n] = ans;\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countVowelPermutation(int n) {\n        long a = 1, e = 1, i = 1, o = 1, u = 1, mod = pow(10, 9)+7;\n        long a2, e2, i2, o2, u2;\n\n        for (int j = 2; j <= n; j++) {\n            a2 = (e + i + u) % mod;\n            e2 = (a + i) % mod;\n            i2 = (e + o) % mod;\n            o2 = i;\n            u2 = (o + i) % mod;\n\n            a = a2, e = e2, i = i2, o = o2, u = u2;\n        }\n\n        return (a + e + i + o + u) % mod;\n    }\n};"
    },
    {
        "title": "Stickers to Spell Word",
        "algo_input": "We are given n different types of stickers. Each sticker has a lowercase English word on it.\n\nYou would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\n\nReturn the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.\n\nNote: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.\n\n&nbsp;\nExample 1:\n\nInput: stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput: 3\nExplanation:\nWe can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.\n\n\nExample 2:\n\nInput: stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput: -1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == stickers.length\n\t1 &lt;= n &lt;= 50\n\t1 &lt;= stickers[i].length &lt;= 10\n\t1 &lt;= target.length &lt;= 15\n\tstickers[i] and target consist of lowercase English letters.\n\n",
        "solution_py": "from functools import lru_cache\nfrom collections import Counter\nclass Solution(object):\n    def minStickers(self, stickers, target):\n        counter = [Counter(sticker) for sticker in stickers] \n        n = len(counter)\n        @lru_cache(None)\n        def dfs(target):\n            if not target: return 0\n            targ_counter = Counter(target)\n            res = float('inf')\n            #using sticker[i] if it contains the first letter of target\n            for i in range(n):\n                if counter[i][target[0]] == 0:\n                    continue\n                s = ''\n                for j in 'abcdefghijklmnopqrstuvwxyz':\n                    s += j*max(targ_counter[j] - counter[i][j], 0) \n                res = min(res, 1 + dfs(s)) if dfs(s) != -1 else res\n            return -1 if res == float('inf') else res\n        return dfs(target)",
        "solution_js": "/**\n * @param {string[]} stickers\n * @param {string} target\n * @return {number}\n */\n\n// Backtracking\nvar minStickers = function(stickers, target) {\n    //* Inits *//\n    let dp = new Map();\n\n    //* Helpers *//\n    const getStringDiff = (str1, str2) => {\n        for(let c of str2) {\n            if(str1.includes(c)) str1 = str1.replace(c, '');\n        }\n        return str1;\n    }\n    dp.set('', 0);\n\n    //* Main *//\n    function calcStickers(restStr) {\n        // if(restStr === \"\") return 0; <-- without memoization\n        if (dp.has(restStr)) return dp.get(restStr);\n        let res = Infinity;\n\n        for (let s of stickers.filter(s => s.includes(restStr[0]))) { // if current sticker does not contain the FIRST char, continue\n            let str = getStringDiff(restStr, s); //aabbc - bc = aab\n            res = Math.min(res, 1 + calcStickers(str)); // RECURSE.... calculate min stickers for the remaining letters.. try combination for all strings and get min\n        }\n\n        dp.set(restStr, res === Infinity || res === 0 ? -1 : res); //Memoize the result in dp;\n        return dp.get(restStr);\n        // return res; <-- without memoization\n    }\n    return calcStickers(target)\n}",
        "solution_java": "class Solution {\n    HashMap<String,HashMap<Character,Integer>>map;\n    public int minStickers(String[] stickers, String target) {\n        map = new HashMap<>();\n        for(String sticker:stickers){\n            HashMap<Character,Integer> temp = new HashMap<>();\n            for(char ch:sticker.toCharArray())\n                temp.put(ch,temp.getOrDefault(ch,0)+1);\n            map.put(sticker,temp);\n        }\n        int count = memoization(target,new HashMap<>());\n        return count<1||count>=Integer.MAX_VALUE?-1:count;\n    }\n    public int memoization(String target, HashMap<String, Integer>dpmap){\n        if(target.length()==0)return 0;\n        if(dpmap.containsKey(target)) return dpmap.get(target);\n        int count = Integer.MAX_VALUE;\n        for(String str: map.keySet()){\n              HashMap<Character,Integer> xd = new HashMap(map.get(str));\n              String temp = target;\n              char ch = temp.charAt(0);\n              if(xd.containsKey(ch)){\n                 for(int i =0;i<temp.length();i++){\n                     ch = temp.charAt(i);\n                     if(xd.containsKey(ch) && xd.get(ch)>0){\n                         xd.put(ch,xd.get(ch)-1);\n                         temp = temp.substring(0,i)+temp.substring(i+1);\n                         i--;\n                     }\n                 }\n                  if(temp.length()!=target.length()){\n                      count  = Math.min(count,1+memoization(temp,dpmap));\n                      dpmap.put(target,count);    \n                  }\n              }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[50][1<<15] ;\n    int solve(int ind, int mask, vector<string>& stickers, string& target)\n    {\n        if (mask == 0)\n            return 0 ;\n        if (ind == stickers.size())\n            return 1e8 ;\n        if (dp[ind][mask] != -1)\n            return dp[ind][mask] ;\n        vector<int> mp(26, 0);\n        bool flag = false ;\n        int ans = 1e8 ;\n        for(int i = 0; i < stickers[ind].size(); i++)\n            mp[stickers[ind][i]-'a'] ++ ;\n        for(int i= 0; i < target.size(); i++)\n        {\n            if (mp[target[i]-'a'] > 0 && (mask & (1<<i)))\n            {\n                flag = true ;\n                break ;\n            }\n        }\n        if (flag) // Check if we can use any of the characters in sticker[ind]\n        {\n            int tempMask = mask ;\n            for(int i = 0; i < target.size(); i++)\n            {\n                if (mp[target[i]-'a'] > 0 && (tempMask & (1<<i)))\n                {\n                    tempMask = tempMask ^ (1<<i) ;\n                    mp[target[i]-'a'] -- ;\n                }\n            }\n            ans = min(ans, 1+solve(ind, tempMask, stickers, target)) ; // Take those characters, and make call on same index\n        }\n        ans = min(ans, solve(ind+1, mask, stickers, target)) ; // Skip sticker[ind] and proceed\n        return dp[ind][mask] = ans;\n    }\n\n    int minStickers(vector<string>& stickers, string target) {\n        int n = target.size();\n        memset(dp, -1, sizeof(dp)) ;\n        int ans = solve(0, (1<<n)-1, stickers, target) ;\n        if (ans == 1e8)\n            return -1 ;\n        return ans ;\n    }\n};"
    },
    {
        "title": "Minimum Possible Integer After at Most K Adjacent Swaps On Digits",
        "algo_input": "You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.\n\nReturn the minimum integer you can obtain also as a string.\n\n&nbsp;\nExample 1:\n\nInput: num = \"4321\", k = 4\nOutput: \"1342\"\nExplanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n\n\nExample 2:\n\nInput: num = \"100\", k = 1\nOutput: \"010\"\nExplanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n\n\nExample 3:\n\nInput: num = \"36789\", k = 1000\nOutput: \"36789\"\nExplanation: We can keep the number without any swaps.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 3 * 104\n\tnum consists of only digits and does not contain leading zeros.\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "from sortedcontainers import SortedList\n\nclass Solution:\n    def minInteger(self, num: str, k: int) -> str:\n        sz, window = len(num), SortedList()\n        remainedIndices, poppedIndices = SortedList(range(sz)), []\n        while k > 0:\n            while len(window) < k + 1 and len(window) < len(remainedIndices):\n                idx = remainedIndices[len(window)]\n                window.add((num[idx], idx))\n            if not window:\n                break\n            index = window.pop(0)[1]\n            k -= remainedIndices.bisect_left(index)\n            remainedIndices.remove(index)\n            poppedIndices.append(index)\n            for idx in remainedIndices[k + 1: len(window)]:\n                window.remove((num[idx], idx))\n        poppedSet = set(poppedIndices)\n        return \"\".join(num[idx] for idx in poppedIndices) + \"\".join(num[idx] for idx in range(sz) if idx not in poppedSet)",
        "solution_js": "/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n \n Idea is based on bubble sorting with limited steps k\n \n */\n\nvar minInteger = function(num, k) {\n    if (num.length == 1)\n        return num;\n    \n    let nums = num.split('');\n    let i = 0, j = 0;\n    \n    while (k && i < num.length-1) {\n//         step 0: if leading zero, check the next digit\n        if (nums[i] == '0') {\n            i++;\n            j++;\n            continue;\n        }\n        \n//         step 1: find the min digit \n        let p = j, steps = 0;\n        while (nums[p] !== '0' && j < nums.length && steps <= k) {\n            if (nums[j] < nums[p])\n                p = j;\n            j++;\n            steps++;\n        }\n        \n//         step 2: nums[i] is the current minimum digit --> check next digit\n        if (p == i) {\n            i++;\n            j = i;\n            continue;\n        }\n            \n//          step 3: move the min digit to i\n        for (; p > i; p--) {\n            [nums[p], nums[p-1]] = [nums[p-1], nums[p]];\n            k--;\n        }\n        \n        i++;\n        j = i;\n        \n    }\n    \n    return nums.join('');\n};",
        "solution_java": "class Solution {\n    public String minInteger(String num, int k) {\n        //pqs stores the location of each digit.\n        List<Queue<Integer>> pqs = new ArrayList<>();\n        for (int i = 0; i <= 9; ++i) {\n            pqs.add(new LinkedList<>());\n        }\n\n        for (int i = 0; i < num.length(); ++i) {\n            pqs.get(num.charAt(i) - '0').add(i);\n        }\n        String ans = \"\";\n        SegmentTree seg = new SegmentTree(num.length());\n\n        for (int i = 0; i < num.length(); ++i) {\n            // At each location, try to place 0....9\n            for (int digit = 0; digit <= 9; ++digit) {\n                // is there any occurrence of digit left?\n                if (pqs.get(digit).size() != 0) {\n                    // yes, there is a occurrence of digit at pos\n                    Integer pos = pqs.get(digit).peek();\n\t\t\t\t\t// Since few numbers already shifted to left, this `pos` might be outdated.\n                    // we try to find how many number already got shifted that were to the left of pos.\n                    int shift = seg.getCountLessThan(pos);\n                    // (pos - shift) is number of steps to make digit move from pos to i.\n                    if (pos - shift <= k) {\n                        k -= pos - shift;\n                        seg.add(pos); // Add pos to our segment tree.\n                        pqs.get(digit).remove();\n                        ans += digit;\n                        break;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n\n    class SegmentTree {\n        int[] nodes;\n        int n;\n\n        public SegmentTree(int max) {\n            nodes = new int[4 * (max)];\n            n = max;\n        }\n\n        public void add(int num) {\n            addUtil(num, 0, n, 0);\n        }\n\n        private void addUtil(int num, int l, int r, int node) {\n            if (num < l || num > r) {\n                return;\n            }\n            if (l == r) {\n                nodes[node]++;\n                return;\n            }\n            int mid = (l + r) / 2;\n            addUtil(num, l, mid, 2 * node + 1);\n            addUtil(num, mid + 1, r, 2 * node + 2);\n            nodes[node] = nodes[2 * node + 1] + nodes[2 * node + 2];\n        }\n\n        // Essentialy it tells count of numbers < num.\n        public int getCountLessThan(int num) {\n            return getUtil(0, num, 0, n, 0);\n        }\n\n        private int getUtil(int ql, int qr, int l, int r, int node) {\n            if (qr < l || ql > r) return 0;\n            if (ql <= l && qr >= r) {\n                return nodes[node];\n            }\n\n            int mid = (l + r) / 2;\n            return getUtil(ql, qr, l, mid, 2 * node + 1) + getUtil(ql, qr, mid + 1, r, 2 * node + 2);\n        }\n    }\n\n}",
        "solution_c": "/*\n    Time: O(nlogn)\n    Space: O(n)\n    Tag: Segment Tree, Greedy (put the possible feasible smallest index in place of cur index), Queue\n    Difficulty: H (Both Logic and Implementation)\n*/\n\nclass SegmentTree {\n    vector<int> tree;\n\npublic:\n    SegmentTree(int size) {\n        tree.resize(4 * size + 1, 0);\n    }\n\n    void printTree() {\n        for (int num : tree) cout << num << \"\";\n        cout << endl;\n    }\n\n    void updateTree(int lo, int hi, int index, int upd) {\n        if (upd < lo || upd > hi) return;\n        if (lo == hi) {\n            tree[index]++;\n            return;\n        }\n        int mid = lo + (hi - lo) / 2;\n        updateTree(lo, mid, 2 * index, upd);\n        updateTree(mid + 1, hi, 2 * index + 1, upd);\n        tree[index] = tree[2 * index] + tree[2 * index + 1];\n    }\n\n    int queryTree(int lo, int hi, int index, int qs, int qe) {\n        if (qe < lo || qs > hi) return 0;\n        if (qe >= hi && qs <= lo) return tree[index];\n\n        int mid = lo + (hi - lo) / 2;\n\n        int left = queryTree(lo, mid, 2 * index, qs, qe);\n        int right = queryTree(mid + 1, hi, 2 * index + 1, qs, qe);\n        return left + right;\n    }\n};\n\nclass Solution {\npublic:\n    string minInteger(string num, int k) {\n        queue<int> pos[10];\n        for (int i = 0; i < num.length(); i++) {\n            pos[num[i] - '0'].push(i);\n        }\n        string res = \"\";\n        SegmentTree *seg = new SegmentTree((int)num.length());\n        for (int i = 0; i < num.length(); i++) {\n            if (num[i] == '-') continue;\n            int digit = num[i] - '0';\n\n            bool swapped = false;\n            for (int j = 0; j < digit; j++) {\n                if (pos[j].size() > 0) {\n                    int curNumIndex = pos[j].front();\n                    int shifts = seg->queryTree(0, num.length() - 1, 1, i, pos[j].front());\n\n                    if (curNumIndex - i - shifts <= k) {\n                        seg->updateTree(0, num.length() - 1, 1, curNumIndex);\n                        k -= curNumIndex - i - shifts;\n                        pos[j].pop();\n                        res += num[curNumIndex];\n                        num[curNumIndex] = '-';\n                        swapped = true;\n                        i--;\n                        break;\n                    }\n                }\n            }\n            if (!swapped) {\n                res += num[i];\n                pos[digit].pop();\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Bulls and Cows",
        "algo_input": "You are playing the Bulls and Cows game with your friend.\n\nYou write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:\n\n\n\tThe number of \"bulls\", which are digits in the guess that are in the correct position.\n\tThe number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.\n\n\nGiven the secret number secret and your friend's guess guess, return the hint for your friend's guess.\n\nThe hint should be formatted as \"xAyB\", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.\n\n&nbsp;\nExample 1:\n\nInput: secret = \"1807\", guess = \"7810\"\nOutput: \"1A3B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n  |\n\"7810\"\n\nExample 2:\n\nInput: secret = \"1123\", guess = \"0111\"\nOutput: \"1A1B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1123\"        \"1123\"\n  |      or     |\n\"0111\"        \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= secret.length, guess.length &lt;= 1000\n\tsecret.length == guess.length\n\tsecret and guess consist of digits only.\n\n",
        "solution_py": "class Solution:\n    def getHint(self, secret: str, guess: str) -> str:\n        \n        # Setup counts for bulls and cows\n        bulls = cows = 0\n        \n        # Copy secret and guess into lists that are easier to work with\n        secretCopy = list(secret)\n        guessCopy = list(guess)\n        \n        # In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls\n        for i in range(len(secret)):\n            \n            # If they match, bulls += 1 and pop() the letters from the copy lists via their .index()\n            if secret[i] == guess[i]:\n                bulls += 1\n                secretCopy.pop(secretCopy.index(secret[i]))\n                guessCopy.pop(guessCopy.index(guess[i]))\n                \n                \n        # Count() the letters remaining in secret and guess lists\n        secretCounter = Counter(secretCopy)\n        guessCounter = Counter(guessCopy)\n        \n        # Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed\n        # secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters\n        # Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters\n        dif = secretCounter - (secretCounter - guessCounter)\n        \n        # The .total() of the dif Counter is the number of cows\n        cows = dif.total()\n\n        # return the formatted string with req. info\n        return f'{bulls}A{cows}B'",
        "solution_js": "var getHint = function(secret, guess) {\n    let ACount = 0, BCount = 0;\n    const secretMap = new Map(), guessMap = new Map();\n    for(let i = 0; i < secret.length; i++) {\n        if(secret[i] == guess[i]) {\n            ACount++;\n        }\n        else {\n            if(secretMap.has(secret[i])) {\n                secretMap.set(secret[i], secretMap.get(secret[i])+1);\n            }\n            else {\n                secretMap.set(secret[i], 1);\n            }\n        }\n    }\n    for(let i = 0; i < guess.length; i++) {\n        if(secret[i] !== guess[i]) {\n            if(secretMap.get(guess[i]) > 0) {\n                secretMap.set(guess[i], secretMap.get(guess[i])-1);\n                BCount++;\n            }\n        }\n    }\n    return ACount+'A'+BCount+'B';\n};",
        "solution_java": "class Solution {\n    public String getHint(String secret, String guess) {\n        int arr[] = new int[10], bulls = 0, cows = 0;\n        for (int i = 0; i < secret.length(); i++) {\n            char sec = secret.charAt(i);\n            char gue = guess.charAt(i); \n            if (sec == gue) bulls++;\n            else {\n                if (arr[sec - '0'] < 0) cows++;\n                if (arr[gue - '0'] > 0) cows++;\n                arr[sec - '0']++;\n                arr[gue - '0']--;\n            }\n        }\n        return new StringBuilder(String.valueOf(bulls)).append(\"A\").append(cows).append(\"B\").toString();\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    string getHint(string secret, string guess)\n    {\n        int bulls = 0;\n        vector<int> v1(10, 0);\n        vector<int> v2(10, 0);\n        for (int i = 0; i < secret.size(); ++i)\n        {\n            if (secret[i] == guess[i])\n            {\n                ++bulls;\n            }\n            else\n            {\n                ++v1[secret[i] - '0'];\n                ++v2[guess[i] - '0'];\n            }\n        }\n        int cows = 0;\n        for (int i = 0; i < 10; ++i)\n        {\n            cows += min(v1[i], v2[i]);\n        }\n        return to_string(bulls) + \"A\" + to_string(cows) + \"B\";\n    }\n};"
    },
    {
        "title": "Check If String Is a Prefix of Array",
        "algo_input": "Given a string s and an array of strings words, determine whether s is a prefix string of words.\n\nA string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.\n\nReturn true if s is a prefix string of words, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput: true\nExplanation:\ns can be made by concatenating \"i\", \"love\", and \"leetcode\" together.\n\n\nExample 2:\n\nInput: s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput: false\nExplanation:\nIt is impossible to make s using a prefix of arr.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 20\n\t1 &lt;= s.length &lt;= 1000\n\twords[i] and s consist of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def isPrefixString(self, s: str, words: List[str]) -> bool:\n        \n        a = ''\n    \n        for i in words:\n            \n            a += i\n            \n            if a == s:\n                return True\n            if not s.startswith(a):\n                break\n                     \n        return False ",
        "solution_js": "var isPrefixString = function(s, words) {\n    let str = words[0];\n    if(s === words[0]){\n        return true;\n    }\n    for(let i=1; i < words.length; i++){\n        if(s === str){\n            return true;\n        }\n        if( s.startsWith(str)){\n            str += words[i];\n            continue;\n        }else{\n            return false;\n        }\n    }\n    if(s !== str){\n            return false;\n        }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isPrefixString(String s, String[] words) {\n        StringBuilder res = new StringBuilder (\"\");\n        for (String word : words) {\n            res.append (word);\n            if (s.equals (res.toString()))\n                return true;\n            if (s.indexOf (res.toString()) == -1)\n                return false;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPrefixString(string s, vector<string>& words) {\n        string n=\"\";\n        for(string str:words){\n            for(char ch:str){\n                n+=ch;\n            }\n            if(n==s){\n                return true;\n            }\n        }\n        \n        return false;\n    }\n};"
    },
    {
        "title": "Sorting the Sentence",
        "algo_input": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.\n\nA sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.\n\n\n\tFor example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\".\n\n\nGiven a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.\n\n&nbsp;\nExample 1:\n\nInput: s = \"is2 sentence4 This1 a3\"\nOutput: \"This is a sentence\"\nExplanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.\n\n\nExample 2:\n\nInput: s = \"Myself2 Me1 I4 and3\"\nOutput: \"Me Myself and I\"\nExplanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 200\n\ts consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.\n\tThe number of words in s is between 1 and 9.\n\tThe words in s are separated by a single space.\n\ts contains no leading or trailing spaces.\n",
        "solution_py": "class Solution:\n    def sortSentence(self, s: str) -> str:\n\n        x = s.split()\n        dic = {}\n        for i in x :\n            dic[i[-1]] = i[:-1]\n        return ' '.join([dic[j] for j in sorted(dic)])",
        "solution_js": "var sortSentence = function(s) {\n    let sortingS = s.split(' ').sort((a,b) => a.substr(-1) - b.substr(-1));\n    slicingS = sortingS.map(word => word.slice(0, -1));\n    return slicingS.join(' ');\n};",
        "solution_java": "class Solution {\n    public String sortSentence(String s) {\n        String []res=new String[s.split(\" \").length];\n        for(String st:s.split(\" \")){\n            res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1);\n        }\n        return String.join(\" \",res);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string sortSentence(string s) \n    {\n        stringstream words(s); \n        string word;\n        pair<int, string> m;\n        vector<pair<int, string> > sent;\n        \n        //SECTION 1\n        while(words>>word)\n        {\n            int len = word.size();\n            int i = int(word[len-1]) - 48;\n            sent.push_back(make_pair(i, word.substr(0, len-1)));\n        }\n        \n        //SECTION 2\n        sort(sent.begin(), sent.end());\n        \n        //SECTION 3\n        string ans = \"\";\n        int len = sent.size();\n        for(int i=0; i<len; i++)\n        {\n            ans += sent[i].second;\n            if(i!= len-1)\n                ans += \" \";\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Count Complete Tree Nodes",
        "algo_input": "Given the root of a complete binary tree, return the number of the nodes in the tree.\n\nAccording to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n\nDesign an algorithm that runs in less than&nbsp;O(n)&nbsp;time complexity.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,6]\nOutput: 6\n\n\nExample 2:\n\nInput: root = []\nOutput: 0\n\n\nExample 3:\n\nInput: root = [1]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 5 * 104].\n\t0 &lt;= Node.val &lt;= 5 * 104\n\tThe tree is guaranteed to be complete.\n\n",
        "solution_py": "class Solution:\n        # @param {TreeNode} root\n        # @return {integer}\n        def countNodes(self, root):\n            if not root:\n                return 0\n            leftDepth = self.getDepth(root.left)\n            rightDepth = self.getDepth(root.right)\n            if leftDepth == rightDepth:\n                return pow(2, leftDepth) + self.countNodes(root.right)\n            else:\n                return pow(2, rightDepth) + self.countNodes(root.left)\n    \n        def getDepth(self, root):\n            if not root:\n                return 0\n            return 1 + self.getDepth(root.left)",
        "solution_js": "var countNodes = function(root) {\n    return root === null ? 0 : countNodes(root.left) + countNodes(root.right) + 1;\n}",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n    static int count = 0;\n\n    static void Postorder(TreeNode root){\n        if(root == null){\n            return;\n        }\n        Postorder(root.left);\n        Postorder(root.right);\n        count++;\n    }\n\n    public int countNodes(TreeNode root) {\n        count = 0;\n        Postorder(root);\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countNodes(TreeNode* root) {\n        if(root==nullptr) return 0;\n        \n        int left = countNodes(root->left);\n        int right = countNodes(root->right);\n        \n        return 1+left+right;\n    }\n};"
    },
    {
        "title": "Strange Printer",
        "algo_input": "There is a strange printer with the following two special properties:\n\n\n\tThe printer can only print a sequence of the same character each time.\n\tAt each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.\n\n\nGiven a string s, return the minimum number of turns the printer needed to print it.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aaabbb\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"bbb\".\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution(object):\n    def strangePrinter(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: int\n        \"\"\"\n        # remove duplicate letters from s.\n        tmp = []\n        for c in s:\n            if len(tmp) == 0 or tmp[-1] != c:\n                tmp.append(c)\n        s = \"\".join(tmp)\n\n        _m = {}\n        def _dp(i, j, background):\n            if j < i:\n                return 0\n            elif i == j:\n                return 1 if background != s[i] else 0\n            elif (i, j, background) in _m:\n                return _m[(i, j, background)]\n\n            ans = len(s)\n\n            # shrink s[i:j+1] to s[i_:j_+1] according to the background letter\n            i_ = i + 1 if s[i] == background else i\n            j_ = j - 1 if s[j] == background else j\n\n            if s[i_] == s[j_]:\n                # case \"AxxxA\" => best strategy is printing A first\n                ans = _dp(i_ + 1, j_ - 1, s[i_]) + 1\n            else:\n                # otherwise, print first letter, try every possible print length\n                for p in range(i_, j_ + 1):\n                    # searching is needed only if s[p] == s[i_]\n                    # e.g. s=\"ABCDEA\"print 'A' on s[0:1] is equivalent to s[0:5]\n                    if s[p] != s[i_]:\n                        continue\n                    l = _dp(i_, p, s[i_])\n                    r = _dp(p + 1, j_, background)\n                    ans = min(ans, l + r + 1)\n            _m[(i, j, background)] = ans\n            return ans\n\n        return _dp(0, len(s) - 1, '')",
        "solution_js": "var strangePrinter = function(s) {\n    if(!s) return 0;\n\n    const N = s.length;    \n    const state = Array.from({length:N}, () => Array.from({length:N}));\n    \n    for(let i = 0; i < N; i++) {\n        // Printing one character always takes one attempt\n        state[i][i] = 1;\n    }\n    \n    const search = (i,j) => {\n        if(state[i][j]) return state[i][j];\n        \n        state[i][j] = Infinity;\n        for(let k = i; k < j; k++) {\n            state[i][j] = Math.min(state[i][j], search(i,k) + search(k+1,j));\n        }\n        if(s[i] === s[j]) state[i][j]--;\n        return state[i][j];\n    }\n    \n    return search(0, N-1);\n}",
        "solution_java": "class Solution {\n\npublic int strangePrinter(String s) {\n    if (s.equals(\"\")) return 0;\n    int len = s.length();\n    int[][] dp = new int[len][len];\n    for (int i = 0; i < len; i++)\n        dp[i][i] = 1;\n    for (int l = 2; l <= len; l++) {\n        for (int i = 0; i < len && l + i - 1 < len; i++) {\n            int j = l + i - 1;\n            dp[i][j] = dp[i][j - 1] + (s.charAt(i) == s.charAt(j) ? 0 : 1);\n            for (int k = i + 1; k < j; k++) {\n                if (s.charAt(k) == s.charAt(j)) {\n                    dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k][j - 1]);\n                }\n            }\n        }\n    }\n    return dp[0][len - 1];\n}\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[101][101];\n    int solve(string s,int i,int j)\n    {\n        if(i>j)\n            return 0;\n        if(dp[i][j]!=-1)\n            return dp[i][j];\n        int ans=0;\n        while(i<j && s[i+1]==s[i])\n            i++;\n        while(i<j && s[j]==s[j-1])\n        {\n            j--;\n        }\n        ans=1+solve(s,i+1,j);\n        for(int k=i+1;k<=j;k++)\n        {\n            if(s[k]==s[i])\n            {\n                int cnt=solve(s,i+1,k-1)+solve(s,k,j);\n                ans=min(ans,cnt);\n            }\n        }\n        return dp[i][j]=ans;\n    }\n    int strangePrinter(string s)\n    {\n        memset(dp,-1,sizeof(dp));\n         return solve(s,0,s.size()-1);\n    }\n};\n// if you like the solution plz upvote."
    },
    {
        "title": "Most Profit Assigning Work",
        "algo_input": "You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:\n\n\n\tdifficulty[i] and profit[i] are the difficulty and the profit of the ith job, and\n\tworker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).\n\n\nEvery worker can be assigned at most one job, but one job can be completed multiple times.\n\n\n\tFor example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.\n\n\nReturn the maximum profit we can achieve after assigning the workers to the jobs.\n\n&nbsp;\nExample 1:\n\nInput: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput: 100\nExplanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.\n\n\nExample 2:\n\nInput: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tn == difficulty.length\n\tn == profit.length\n\tm == worker.length\n\t1 &lt;= n, m &lt;= 104\n\t1 &lt;= difficulty[i], profit[i], worker[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)\n    #Space-Complexity: O(n)\n    def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n        #Approach: First of all, linearly traverse each and every corresponding index\n        #position of first two input arrays: difficulty and profit to group each\n        #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n        #by increasing difficulty of the job! Then, for each worker, perform binary\n        #search and consistently update the max profit the current worker can work and\n        #earn! Add this value to answer variable, which is cumulative for all workers!\n        #this will be the result returned at the end!\n        arr = []\n        for i in range(len(difficulty)):\n            arr.append([difficulty[i], profit[i]])\n        #sort by difficulty!\n        arr.sort(key = lambda x: x[0])\n        #then, I need to update the maximum profit up to each and every item!\n        maximum = float(-inf)\n        for j in range(len(arr)):\n            maximum = max(maximum, arr[j][1])\n            arr[j][1] = maximum\n        ans = 0\n        #iterate through each and every worker!\n        for w in worker:\n            bestProfit = 0\n            #define search space to perform binary search!\n            L, R = 0, len(arr) - 1\n            #as long as search space has at least one element to consider or one job,\n            #continue iterations of binary search!\n            while L <= R:\n                mid = (L + R) // 2\n                mid_e = arr[mid]\n                #check if current job has difficulty that is manageable!\n                if(mid_e[0] <= w):\n                    bestProfit = max(bestProfit, mid_e[1])\n                    #we still need to search right and try higher difficulty\n                    #jobs that might yield higher profit!\n                    L = mid + 1\n                    continue\n                else:\n                    R = mid - 1\n                    continue\n            #once we break from while loop and end binary search, we should have\n            #found bestProfit for current worker performing task that is manageable!\n            ans += bestProfit\n        return ans",
        "solution_js": "var maxProfitAssignment = function(difficulty, profit, worker) {\n    const data = [];\n\n    for (let i = 0; i < difficulty.length; i++) {\n        data.push({ difficulty: difficulty[i], profit: profit[i] });\n    }\n\n    data.sort((a, b) => a.difficulty - b.difficulty);\n\n    let maxProfit = 0;\n\n    for (let i = 0; i < data.length; i++) {\n        data[i].profit = maxProfit = Math.max(maxProfit, data[i].profit);\n    }\n\n    // worker.sort((a, b) => a - b);\n\n    let ans = 0;\n    let min = 0;\n\n    for (const skill of worker) {\n        let left = 0; // min;\n        let right = data.length - 1;\n\n        while (left < right) {\n            const mid = Math.floor((left + right + 1) / 2);\n\n            if (data[mid].difficulty > skill) {\n                right = mid - 1;\n            } else {\n                left = mid;\n            }\n        }\n\n        if (data[left].difficulty > skill) {\n            continue;\n        }\n\n        // min = left;\n        ans += data[left].profit;\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n        PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(b[1]-a[1]));\n        for(int i=0;i<profit.length;i++)\n        {\n            pq.add(new int[]{difficulty[i],profit[i]});\n        }\n        Arrays.sort(worker);\n        int p=0;\n        for(int i=worker.length-1;i>=0 && !pq.isEmpty();i--)\n        {\n            if(worker[i]>=pq.peek()[0])\n                p=p+pq.peek()[1];\n            else\n            {\n                while(!pq.isEmpty() && worker[i]<pq.peek()[0])\n                    pq.poll();\n                if(!pq.isEmpty())\n                  p=p+pq.peek()[1];\n            }\n        }\n        return p;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    static bool cmp(pair<int,int>a, pair<int,int>b){\n        if(a.first == b.first){\n            return a.second<b.second;\n        }\n\n        return a.first>b.first;\n    }\n    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n        int ans = 0;\n        vector<pair<int,int>>vp;\n        for(int i = 0; i<profit.size(); i++){\n            vp.push_back({profit[i], difficulty[i]});\n        }\n        sort(vp.begin(), vp.end(), cmp);\n        sort(worker.begin(), worker.end(), greater<int>());\n\n        //i is for traversing the vp and j is for traversing the worker\n        int i = 0, j = 0;\n\n        while(i<vp.size() and j<worker.size()){\n            if(worker[j]>=vp[i].second){\n                ans+=vp[i].first;\n                j++;\n            }\n            else{\n                i++;\n            }\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Merge Strings Alternately",
        "algo_input": "You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.\n\nReturn the merged string.\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"abc\", word2 = \"pqr\"\nOutput: \"apbqcr\"\nExplanation:&nbsp;The merged string will be merged as so:\nword1:  a   b   c\nword2:    p   q   r\nmerged: a p b q c r\n\n\nExample 2:\n\nInput: word1 = \"ab\", word2 = \"pqrs\"\nOutput: \"apbqrs\"\nExplanation:&nbsp;Notice that as word2 is longer, \"rs\" is appended to the end.\nword1:  a   b \nword2:    p   q   r   s\nmerged: a p b q   r   s\n\n\nExample 3:\n\nInput: word1 = \"abcd\", word2 = \"pq\"\nOutput: \"apbqcd\"\nExplanation:&nbsp;Notice that as word1 is longer, \"cd\" is appended to the end.\nword1:  a   b   c   d\nword2:    p   q \nmerged: a p b q c   d\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word1.length, word2.length &lt;= 100\n\tword1 and word2 consist of lowercase English letters.\n",
        "solution_py": "class Solution(object):\n    def mergeAlternately(self, word1, word2):\n        i=0\n        j=0\n        st=[]\n        while i<len(word1) and j<len(word2):\n            st.append(word1[i])\n            st.append(word2[j])\n            i+=1\n            j+=1\n        while j<len(word2):\n            st.append(word2[j])\n            j+=1\n        while i<len(word1):\n            st.append(word1[i])\n            i+=1\n        return \"\".join(st)",
        "solution_js": "/**\n * @param {string} word1\n * @param {string} word2\n * @return {string}\n */\nvar mergeAlternately = function(word1, word2) {\n    let length = Math.max(word1.length, word2.length), s = '';\n    for(let i = 0; i < length; i++){\n        s+= word1[i] || '';\n        s+= word2[i] || '';\n    }\n    return s;\n};",
        "solution_java": "class Solution {\n    public String mergeAlternately(String word1, String word2) {\n        StringBuilder sb = new StringBuilder();\n        int lenmax = Math.max(word1.length(),word2.length());\n        for(int i=0;i<=lenmax-1;i++)\n        {\n            if(i<word1.length()) sb.append(word1.charAt(i));\n            if(i<word2.length()) sb.append(word2.charAt(i));\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string mergeAlternately(string word1, string word2) {\n        string final=\"\";\n        int p=word1.size();\n        int q=word2.size();\n        int n=max(p,q);\n        for(int i=0;i<n;i++){\n            if(p){\n                final=final+word1[i];\n                p--;\n            }\n            if(q){\n                final=final+word2[i];\n                q--;\n            }\n        }\n        return final;\n    }\n};"
    },
    {
        "title": "Projection Area of 3D Shapes",
        "algo_input": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.\n\nEach value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).\n\nWe view the projection of these cubes onto the xy, yz, and zx planes.\n\nA projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side.\n\nReturn the total area of all three projections.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,2],[3,4]]\nOutput: 17\nExplanation: Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.\n\n\nExample 2:\n\nInput: grid = [[2]]\nOutput: 5\n\n\nExample 3:\n\nInput: grid = [[1,0],[0,2]]\nOutput: 8\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 50\n\t0 &lt;= grid[i][j] &lt;= 50\n\n",
        "solution_py": "class Solution:\n    def projectionArea(self, grid: List[List[int]]) -> int:\n        total = 0\n\t\t\n        # top\n        total += sum([1 for i in grid for j in i if j > 0])\n        \n\t\t# front\n        total +=  sum([max(col) for col in zip(*grid)])\n        \n\t\t# side\n        total +=  sum([max(row) for row in grid])\n        \n\t\treturn total",
        "solution_js": "var projectionArea = function(grid) {\n    let maxs = new Array(grid.length).fill(0);\n\n    grid.forEach(row => row.forEach((val, idx) => {\n        if (maxs[idx] < val) maxs[idx] = val;\n    }))\n    \n    const z = grid.reduce((prev, curr) => prev + curr.filter(val => val !== 0).length, 0);\n    const y = grid.reduce((prev, curr) => prev + Math.max(...curr), 0);\n    const x = maxs.reduce((prev, curr) => prev + curr, 0)\n    \n    return x + y + z;\n};",
        "solution_java": "class Solution {\n    public int projectionArea(int[][] grid) {\n        int totalArea = 0;\n        \n        \n        for(int[] row : grid){\n            int max = row[0];\n            for(int c : row){\n                if(max < c){\n                    max = c;\n                }if(c != 0){\n                    totalArea += 1;\n                }\n                \n            }\n            totalArea += max;\n        }\n        \n        for(int c = 0; c < grid[0].length; c++){\n            int max = grid[0][c];\n            for(int row = 0; row  <  grid.length; row++){\n                if(max < grid[row][c]){\n                    \n                    max = grid[row][c];\n                }\n            }\n            totalArea += max;\n            }\n        return totalArea;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int projectionArea(vector<vector<int>>& grid) {\n        int res=0;\n        // X-Y ( top )\n        for(int i=0;i<grid.size();i++)\n        {\n            for(int j=0;j<grid[0].size();j++)\n            {\n                if(grid[i][j]) // if some cubes are present it is seen as of area 1 from top\n                    res++; \n            }\n        }\n        \n        // Z-X ( front )\n        for(int i=0;i<grid.size();i++)\n        {\n            int m=grid[i][0];\n            for(int j=1;j<grid[0].size();j++)\n            {\n                m=max(m,grid[i][j]);// from front, the tower with heightest height can only be seen in column\n            }\n            res+=m;\n        }\n        \n        // Z-Y ( side )\n        for(int j=0;j<grid[0].size();j++)\n        {\n            int m=grid[0][j];\n            for(int i=1;i<grid.size();i++)\n            {\n                m=max(m,grid[i][j]);// // from side, the tower with heightest height can only be seen in row\n            }\n            res+=m;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Island Perimeter",
        "algo_input": "You are given row x col grid representing a map where grid[i][j] = 1 represents&nbsp;land and grid[i][j] = 0 represents water.\n\nGrid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).\n\nThe island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\nOutput: 16\nExplanation: The perimeter is the 16 yellow stripes in the image above.\n\n\nExample 2:\n\nInput: grid = [[1]]\nOutput: 4\n\n\nExample 3:\n\nInput: grid = [[1,0]]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\trow == grid.length\n\tcol == grid[i].length\n\t1 &lt;= row, col &lt;= 100\n\tgrid[i][j] is 0 or 1.\n\tThere is exactly one island in grid.\n\n",
        "solution_py": "class Solution:\n    def islandPerimeter(self, grid: List[List[int]]) -> int:\n        perimeter = 0\n\n        for i in range(len(grid)):\n            for j in range(len(grid[0])):\n                if grid[i][j] == 1:\n                    perimeter += 4\n                    if i != 0 and grid[i-1][j] == 1:\n                        perimeter -= 2\n                    if j != 0 and grid[i][j-1] == 1:\n                        perimeter -= 2 \n            \n        return perimeter",
        "solution_js": "var islandPerimeter = function(grid) {\n    let perimeter = 0\n    let row = grid.length\n    let col = grid[0].length\n    \n    for (let i = 0; i < grid.length; i++) {\n        for (let j = 0; j < grid[i].length; j++) {\n            if (grid[i][j] === 1) {\n                if (i === 0 || i > 0 && grid[i-1][j] === 0) perimeter++ \n                if (i === row-1 || i < row-1 && grid[i+1][j] === 0) perimeter++              \n                if (j === 0 || j > 0 && grid[i][j-1] === 0) perimeter++\n                if (j === col - 1 || j < col && grid[i][j+1] === 0) perimeter++\n            }\n        }\n    }\n    \n    return perimeter\n};",
        "solution_java": "class Solution {\n    public int islandPerimeter(int[][] grid) {\n        if(grid == null || grid.length == 0) return 0;\n\n        int row=grid.length,col=grid[0].length;\n        int perimeter=0;\n\n        for(int i=0;i<row;i++){\n            for(int j=0;j<col;j++){\n\n                if(grid[i][j]==1){\n                    perimeter+=4;\n\n                    if(i>0 && grid[i-1][j]==1){\n                    perimeter-=2;\n                   }\n\n                    if(j>0 && grid[i][j-1]==1){\n                    perimeter-=2;\n                   }\n                }\n\n            }\n        }\n        return perimeter;\n    }\n}",
        "solution_c": "////**  hindi me samjho ab// \n// agar mje left or right or bottom or top me 1 mila to me aaga badunga agar nahi\n//mila mtlb ya to wo boundary  hai  uske baad 0  ara hai agar esa hai to cnt+=1 \n//kardo kuki wo hi to meri boundary banegi . note : agar boundary hai mtlb \n//i <0 or j<0 or i>=n or j>=m to cnt+=1 kardo or agar box ke side walo me 0 hai to wahan bhi cnt+=1 . \n// hope it make sense \n// please upvote if you like my post \nclass Solution {\npublic:\n     int cnt =0 ;\nbool vis[101][101] ;\n    bool valid( int i , int j, int n , int m){\n        if(i>=n or j>=m or i<0 or j<0 )\n             return false;\n        return true ;\n    }\n    int islandPerimeter(vector<vector<int>>& grid) {\n        memset(vis,false , sizeof(vis)) ;\n        for(int i = 0 ; i <grid.size() ; i ++){ \n              for(int  j=0 ; j<grid[0].size() ; j++) {\n                   \n                  \n                   if(grid[i][j]==1){\n                       \n                     solve(grid, i,j) ;\n                       return cnt ;\n                   }\n              }        \n         }\n        return 69;\n    }\n void  solve(vector<vector<int>>&grid, int i , int j ){\n       int n = grid.size() ; \n     int m = grid[0].size() ;\n vis[i][j]=true ;\n     if(!valid(i-1,j,n,m) or (valid(i-1,j,n,m) and grid[i-1][j]==0)){\n         cnt++ ;\n     }\n     else if(valid(i-1,j,n,m)and !vis[i-1][j])\n         solve(grid, i-1,j) ;\n     \n     if(!valid(i+1,j,n,m) or (valid(i+1,j,n,m) and grid[i+1][j]==0)){\n         cnt++ ;\n     }\n        else if(valid(i+1,j,n,m)and !vis[i+1][j])\n         solve(grid,i+1,j) ;\n     \n     if(!valid(i,j-1,n,m) or (valid(i,j-1,n,m) and grid[i][j-1]==0)){\n         cnt++ ;\n     }\n          else if(valid(i,j-1,n,m)and !vis[i][j-1])\n         solve(grid,i,j-1) ;\n     \n     if(!valid(i,j+1,n,m) or (valid(i,j+1,n,m) and grid[i][j+1]==0)){\n         cnt++ ;\n     }\n          else if(valid(i,j+1,n,m)and !vis[i][j+1])\n         solve(grid,i,j+1) ;\n     \n     \n     \n}\n};"
    },
    {
        "title": "Minimum Cost Homecoming of a Robot in a Grid",
        "algo_input": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).\n\nThe robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.\n\n\n\tIf the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].\n\tIf the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].\n\n\nReturn the minimum total cost for this robot to return home.\n\n&nbsp;\nExample 1:\n\nInput: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput: 18\nExplanation: One optimal path is that:\nStarting from (1, 0)\n-&gt; It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-&gt; It goes right to (2, 1). This move costs colCosts[1] = 2.\n-&gt; It goes right to (2, 2). This move costs colCosts[2] = 6.\n-&gt; It goes right to (2, 3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18\n\nExample 2:\n\nInput: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput: 0\nExplanation: The robot is already at its home. Since no moves occur, the total cost is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == rowCosts.length\n\tn == colCosts.length\n\t1 &lt;= m, n &lt;= 105\n\t0 &lt;= rowCosts[r], colCosts[c] &lt;= 104\n\tstartPos.length == 2\n\thomePos.length == 2\n\t0 &lt;= startrow, homerow &lt; m\n\t0 &lt;= startcol, homecol &lt; n\n\n",
        "solution_py": "class Solution:\n    def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n        def getRange(left, right, array):\n            if left > right:\n                right, left = left, right\n            return sum((array[i] for i in range(left,right+1)))\n        \n        totalRowCost = getRange(startPos[0], homePos[0], rowCosts)\n        totalColCost = getRange(startPos[1], homePos[1], colCosts)\n        \n        #Don't pay for the position you start out on\n        return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]]",
        "solution_js": "var minCost = function(startPos, homePos, rowCosts, colCosts) {\n    let totCosts = 0;\n\n    let rowDir = startPos[0] <= homePos[0] ? 1 : -1;\n    let colDir = startPos[1] <= homePos[1] ? 1 : -1;\n    \n    let row = startPos[0];\n\n    while (row != homePos[0]) {\n        row += rowDir;\n        totCosts += rowCosts[row];\n    }\n\n    let col = startPos[1];\n\n    while (col != homePos[1]) {\n        col += colDir;\n        totCosts += colCosts[col];\n    }\n\n    return totCosts;\n};",
        "solution_java": "class Solution {\n    public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {\n        int total = 0;\n        \n        // if home is to the down of start move, down till there\n        if(homePos[0]>startPos[0]){\n            int i = startPos[0]+1;\n            while(i<=homePos[0]){\n                total += rowCosts[i]; // adding cost while moving corresponding to the cell\n                i++;\n            }\n        }\n        \n        // else if home is up from the start, move up till there\n        else if(homePos[0]<startPos[0]){\n            int i = startPos[0]-1;\n            while(i>=homePos[0]){\n                total += rowCosts[i]; // adding cost while moving corresponding to the cell\n                i--;\n            }\n        }\n        \n        // if home is right to the start, move right till there\n        if(homePos[1]>startPos[1]){\n            int i = startPos[1]+1;\n            while(i<=homePos[1]){\n                total += colCosts[i];  // adding cost while moving corresponding to the cell\n                i++;\n            }\n        }\n        \n        // else if home is left to the start, move left till there\n        else if(homePos[1]<startPos[1]){\n            int i = startPos[1]-1;\n            while(i>=homePos[1]){\n                total += colCosts[i];  // adding cost while moving corresponding to the cell\n                i--;\n            }\n        }\n        \n        return total;\n    }\n}",
        "solution_c": "// This is Straightforward Question becuase you need to travel at least one time the incoming rows and column in path.\n// So why you need to complicate the path just traverse staright and to homePos Row and homePos column and you will get the ans...\n// This Question would have become really tough when negative values also possible in the row and column vectors because that negative values could have decresed the results...but here its simple and concise.\nclass Solution {\npublic:\n    int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {\n        int ans = 0;\n        if(startPos[0] < homePos[0])\n        {\n            for(int i = startPos[0]+1 ; i <=homePos[0] ; i++)\n            {\n                ans+=rowCosts[i];\n            }\n        }\n        if(startPos[0] > homePos[0])\n        {\n            for(int i = startPos[0]-1 ; i >=homePos[0] ; i--)\n            {\n                ans+=rowCosts[i];\n            }\n        }\n        if(startPos[1] < homePos[1])\n        {\n            for(int i = startPos[1]+1 ; i <=homePos[1] ; i++)\n            {\n                ans+=colCosts[i];\n            }\n        }\n         if(startPos[1] > homePos[1])\n        {\n            for(int i = startPos[1]-1 ; i >=homePos[1] ; i--)\n            {\n                ans+=colCosts[i];\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Convert Integer to the Sum of Two No-Zero Integers",
        "algo_input": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.\n\nGiven an integer n, return a list of two integers [A, B] where:\n\n\n\tA and B are No-Zero integers.\n\tA + B = n\n\n\nThe test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: [1,1]\nExplanation: A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.\n\n\nExample 2:\n\nInput: n = 11\nOutput: [2,9]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def getNoZeroIntegers(self, n: int) -> List[int]:\n        for i in range(1,n//2+1):\n            first = str(i)\n            second = str(n-i)\n            if \"0\" not in first and \"0\" not in second:\n                return [i, n-i]",
        "solution_js": "var getNoZeroIntegers = function(n) {\n   for(let i=1;i<=n;i++){\n       if(!haveZero(i) && !haveZero(n-i)){\n           return [i,n-i]\n       }\n   }\n};\n\nconst haveZero = (n) =>{\n    let copy = n;\n    while(copy>0){\n        if(copy%10===0){\n            return true\n        }\n        copy=Math.floor(copy/10)\n    }\n    return false\n}",
        "solution_java": "class Solution {\n    public int[] getNoZeroIntegers(int n) {\n        int B;\n        for (int A = 1; A < n; ++A) {\n            B = n - A;\n            if (!(A + \"\").contains(\"0\") && !(B + \"\").contains(\"0\"))\n            return new int[] {A, B};\n    }\n        return new int[]{};\n}\n}",
        "solution_c": "class Solution {\npublic:\n    int has0(int x)\n{\n    while (x){\n        if (x % 10 == 0)\n          return 1;\n        x /= 10;\n    }\n    return 0;\n}\n    vector<int> getNoZeroIntegers(int n) {\n        for(int i=1;i<=n;i++){\n            if(has0(i)==false && has0(n-i)==false){\n                return {i,n-i};\n            }\n        }\n        return {1,1};\n    }\n};"
    },
    {
        "title": "Largest Rectangle in Histogram",
        "algo_input": "Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n\n&nbsp;\nExample 1:\n\nInput: heights = [2,1,5,6,2,3]\nOutput: 10\nExplanation: The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.\n\n\nExample 2:\n\nInput: heights = [2,4]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= heights.length &lt;= 105\n\t0 &lt;= heights[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def largestRectangleArea(self, heights: List[int]) -> int:\n        maxArea = 0\n        stack = [] # (index, height)\n        \n        for i, h in enumerate(heights):\n            startIndex = i\n            while stack and stack[-1][1] > h:\n                index, height = stack.pop()\n                maxArea = max(maxArea, height * (i - index))\n                startIndex = index\n            stack.append((startIndex, h))\n            \n        \n        \n        for index, height in stack:\n            maxArea = max(maxArea, height * (len(heights) - index))\n            \n            \n        return maxArea",
        "solution_js": "var largestRectangleArea = function (heights) {\n    let maxArea = 0;\n    let stack = []; // [[index, height]]\n\n    for (let i = 0; i < heights.length; i++) {\n        let start = i;\n        while (stack.length != 0 && stack[stack.length - 1][1] > heights[i]) {\n            let [index, height] = stack.pop();\n            maxArea = Math.max(maxArea, height * (i - index));\n            start = index;\n        }\n        stack.push([start, heights[i]]);\n    }\n    for (let i = 0; i < stack.length; i++) {\n        maxArea = Math.max(\n            maxArea,\n            stack[i][1] * (heights.length - stack[i][0])\n        );\n    }\n    return maxArea;\n};",
        "solution_java": "class Solution {\n    public int largestRectangleArea(int[] heights) {\n        Stack<Integer> stack1 = new Stack<>();\n        Stack<Integer> stack2 = new Stack<>();\n        int n = heights.length;\n        int[] left = new int[n];\n        int[] right = new int[n];\n        int[] width = new int[n];\n        \n        for(int i=0; i<n; i++){\n            while(!stack1.isEmpty() && heights[stack1.peek()] >= heights[i])\n                stack1.pop();\n            if(!stack1.isEmpty())\n                left[i] = stack1.peek();\n            else\n                left[i] = -1;\n            stack1.push(i);\n        }\n        \n        for(int i=n-1; i>=0; i--){\n            while(!stack2.isEmpty() && heights[stack2.peek()] >= heights[i])\n                stack2.pop();\n            if(!stack2.isEmpty())\n                right[i] = stack2.peek();\n            else\n                right[i] = n;\n            stack2.push(i);\n        }\n        \n        for(int i=0; i<n; i++){\n            width[i] = right[i] - left[i] - 1;\n        }\n        int mxArea = 0;\n        for(int i=0; i<n; i++){\n            mxArea = Math.max(mxArea, width[i] * heights[i]);\n        }        \n        return mxArea;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    vector<int> nextSmallerElement(vector<int>& arr, int n){\n        \n        stack<int> s;\n        s.push(-1);\n        vector<int> ans(n);\n        \n        for(int i = n-1; i>=0 ; i--){\n            int curr = arr[i];\n            \n            while(s.top()!=-1 && arr[s.top()]>=curr){\n                s.pop();\n            }\n            ans[i] = s.top();\n            s.push(i);\n        }\n        return ans;\n    }\n    vector<int> prevSmallerElement(vector<int>& arr, int n){\n        \n        stack<int> s;\n        s.push(-1);\n        vector<int> ans(n);\n        \n        for(int i = 0; i<n ; i++){\n            int curr = arr[i];\n            \n            while(s.top()!=-1 && arr[s.top()]>=curr){\n                s.pop();\n            }\n            ans[i] = s.top();\n            s.push(i);\n        }\n        return ans;\n    }\npublic:\n    int largestRectangleArea(vector<int>& heights) {\n        int n = heights.size();\n        int area = 1, ans = INT_MIN;\n        \n        vector<int> next(n);\n        next = nextSmallerElement(heights, n);\n        \n        vector<int> prev(n);\n        prev = prevSmallerElement(heights, n);\n        \n        for(int i = 0; i<n ; i++){\n            int l = heights[i];\n            \n            if(next[i] == -1){\n                next[i] = n;\n            }\n            int b = next[i] - prev[i] - 1;\n            \n            area = l*b;\n            ans = max(ans,area);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Deletions to Make String Balanced",
        "algo_input": "You are given a string s consisting only of characters 'a' and 'b'​​​​.\n\nYou can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i &lt; j and s[i] = 'b' and s[j]= 'a'.\n\nReturn the minimum number of deletions needed to make s balanced.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aababbab\"\nOutput: 2\nExplanation: You can either:\nDelete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -&gt; \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -&gt; \"aabbbb\").\n\n\nExample 2:\n\nInput: s = \"bbaaaaabb\"\nOutput: 2\nExplanation: The only solution is to delete the first two characters.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is&nbsp;'a' or 'b'​​.\n\n",
        "solution_py": "class Solution:\n\tdef minimumDeletions(self, s: str) -> int:\n\t\tpreSum = [0] * (len(s) + 1)\n\t\tsufSum = [0] * (len(s) + 1)\n\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == \"a\":\n\t\t\t\tpreSum[i] += 1 + preSum[i-1]\n\n\t\t\telse:\n\t\t\t\tpreSum[i] = preSum[i-1]\n\n\t\t\tif s[len(s)-i-1] == \"b\":\n\t\t\t\tsufSum[len(s)-i-1] += 1 + sufSum[len(s)-i]\n\n\t\t\telse:\n\t\t\t\tsufSum[len(s)-i-1] += sufSum[len(s)-i]\n\n\t\tmaxStringLength = 0\n\t\tfor i in range(len(s)):\n\t\t\tif preSum[i] + sufSum[i] > maxStringLength:\n\t\t\t\tmaxStringLength = preSum[i] + sufSum[i]\n\n\t\treturn len(s) - maxStringLength",
        "solution_js": "var minimumDeletions = function(s) {\n    const dpA = [];\n    let counter = 0;\n    for (let i = 0; i < s.length; i++) {\n        dpA[i] = counter;\n        if (s[i] === 'b') {\n            counter++;\n        }\n    }\n    \n    counter = 0;\n    const dpB = [];\n    for (let i = s.length - 1; i >= 0; i--) {\n        dpB[i] = counter;\n        if (s[i] === 'a') {\n            counter++;\n        }\n    }\n\n    let minDelete = s.length;\n    for (let i = 0; i < s.length; i++) {\n        minDelete = Math.min(minDelete, dpA[i] + dpB[i]);\n    }\n    \n    return minDelete;\n};",
        "solution_java": "class Solution {\n    public int minimumDeletions(String s) {\n        //ideal case : bbbbbbbbb\n        int[] dp = new int[s.length()+1];\n        int idx =1;\n        int bCount=0;\n\n        for(int i =0 ;i<s.length();i++)\n        {\n            if(s.charAt(i)=='a')\n            {\n             dp[idx] = Math.min(dp[idx-1]+1,bCount);\n            }\n            else\n            {\n                dp[idx]=dp[idx-1];\n                bCount++;\n            }\n\n            idx++;\n        }\n        return dp[s.length()];\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumDeletions(string s){\n\n        vector<int> deletions(s.size()+1, 0);\n        int b_count = 0;\n        \n        for(int i = 0; i<s.size(); i++){\n            if(s[i]=='a'){\n                // Either Delete this 'a' or Delete all previous 'b's.\n                deletions[i+1] = min(deletions[i]+1, b_count);\n            } else{\n                deletions[i+1] = deletions[i];\n                b_count++;\n            }\n        }\n\n        return deletions[s.size()];\n\n        // The code is contributed by Mufaddal Saifuddin\n    }\n};"
    },
    {
        "title": "Range Addition II",
        "algo_input": "You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 &lt;= x &lt; ai and 0 &lt;= y &lt; bi.\n\nCount and return the number of maximum integers in the matrix after performing all the operations.\n\n&nbsp;\nExample 1:\n\nInput: m = 3, n = 3, ops = [[2,2],[3,3]]\nOutput: 4\nExplanation: The maximum integer in M is 2, and there are four of it in M. So return 4.\n\n\nExample 2:\n\nInput: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\nOutput: 4\n\n\nExample 3:\n\nInput: m = 3, n = 3, ops = []\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 4 * 104\n\t0 &lt;= ops.length &lt;= 104\n\tops[i].length == 2\n\t1 &lt;= ai &lt;= m\n\t1 &lt;= bi &lt;= n\n\n",
        "solution_py": "class Solution:\n    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n        if not ops:\n            return m*n\n        else:\n            x,y = zip(*ops)\n            return min(x) * min(y)",
        "solution_js": "var maxCount = function(m, n, ops) {\n    if( ops.length === 0 )\n        return m*n\n    let min_a = m , min_b = n\n    for( let [x,y] of ops ){\n        if( x < min_a )\n            min_a = x\n        if( y < min_b )\n            min_b = y\n    }\n    return min_a * min_b\n};",
        "solution_java": "class Solution {\n    public int maxCount(int m, int n, int[][] ops) {\n        int minRow=m,minCol=n;\n        for(int[] op:ops){\n            minRow=Math.min(minRow,op[0]);\n            minCol=Math.min(minCol,op[1]);\n        }\n        return minRow*minCol;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxCount(int m, int n, vector<vector<int>>& ops) {\n\n        int mn_i = m, mn_j = n;\n        for(auto &i : ops)\n            mn_i = min(mn_i, i[0]), mn_j = min(mn_j, i[1]);\n\n        return mn_i * mn_j;\n    }\n};"
    },
    {
        "title": "Maximum Number of Events That Can Be Attended",
        "algo_input": "You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.\n\nYou can attend an event i at any day d where startTimei &lt;= d &lt;= endTimei. You can only attend one event at any time d.\n\nReturn the maximum number of events you can attend.\n\n&nbsp;\nExample 1:\n\nInput: events = [[1,2],[2,3],[3,4]]\nOutput: 3\nExplanation: You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.\n\n\nExample 2:\n\nInput: events= [[1,2],[2,3],[3,4],[1,2]]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= events.length &lt;= 105\n\tevents[i].length == 2\n\t1 &lt;= startDayi &lt;= endDayi &lt;= 105\n\n",
        "solution_py": "class Solution(object):\n    def maxEvents(self, events):\n        \"\"\"\n        :type events: List[List[int]]\n        :rtype: int\n        \"\"\"\n        events = sorted(events, key=lambda x: x[0])\n        current_day = 0\n        min_heap = []\n        event_id = 0\n        total_number_of_days = max(end for start, end in events)\n        total_events_attended = 0\n        #total_number_of_days+1 because I want to include the last day\n        for day in range(1, total_number_of_days+1):\n\n            #Add all the events that can be started on that day\n            while event_id < len(events) and events[event_id][0] == day:\n                heapq.heappush(min_heap, events[event_id][1])\n                event_id+=1\n\n            #while there is something in heap and the event should have been completed before the current day\n            #remove those evenets and consider them not attended\n            while min_heap and min_heap[0] < day :\n                heapq.heappop(min_heap)\n\n            #if theere is an event present in heap\n            #lets mark 1 of those events as complted today and add it to\n            #total_events_attended\n\n            if min_heap:\n                heapq.heappop(min_heap)\n                total_events_attended+=1\n        return total_events_attended",
        "solution_js": "/**\n* O(nlogn)\n*/\nvar maxEvents = function(events) {\n\n    // sort events by their start time\n    events.sort((a,b) => a[0]-b[0]);\n\n    // create priority queue to sort events by end time, the events that have saem start time\n    let minHeap = new PriorityQueue((a, b) => a - b);\n    let i = 0, len = events.length, res = 0, d = 0;\n\n    while(i < len || !minHeap.isEmpty()){\n\n        if (minHeap.isEmpty())\n            d = events[i][0]; // start with event from events list\n\n        while (i < len && events[i][0] <= d) // Add all events that have start time <= day `d` into PQ\n            minHeap.add(events[i++][1]); // add ending time to the minHeap, so when we pull we get event that is ending first\n\n        minHeap.poll(); // make sure we have some event attent\n        ++res;\n        ++d;\n\n        // we finished task of day 'd' Remove events that are already closed ie endTime < d as we cant attend it\n        while (!minHeap.isEmpty() && minHeap.peek() < d)\n            minHeap.poll();\n    }\n    return res;\n};\n\n/*******************standard priority queue implementation used in all leetcode javascript solutions****************/\nclass PriorityQueue {\n\n    /**\n    * Create a Heap\n    * @param {function} compareFunction - compares child and parent element\n    * to see if they should swap. If return value is less than 0 it will\n    * swap to prioritize the child.\n    */\n    constructor(compareFunction) {\n        this.store = [];\n        this.compareFunction = compareFunction;\n    }\n\n    peek() {\n        return this.store[0];\n    }\n\n    size() {\n        return this.store.length;\n    }\n    isEmpty() {\n        return this.store.length === 0;\n    }\n\n    poll() {\n        if (this.size() < 2) {\n            return this.store.pop();\n        }\n        const result = this.store[0];\n        this.store[0] = this.store.pop();\n        this.heapifyDown(0);\n        return result;\n    }\n\n    add(val) {\n        this.store.push(val);\n        this.heapifyUp(this.size() - 1);\n    }\n\n    heapifyUp(child) {\n        while (child) {\n            const parent = Math.floor((child - 1) / 2);\n\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                child = parent;\n            } else {\n                return child;\n            }\n        }\n    }\n\n    heapifyDown(parent) {\n        while (true) {\n            let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n            if (this.shouldSwap(child2, child)) {\n                child = child2;\n            }\n\n            if (this.shouldSwap(child, parent)) {\n                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n                parent = child;\n            } else {\n                return parent;\n            }\n        }\n    }\n\n    shouldSwap(child, parent) {\n        return child && this.compareFunction(this.store[child], this.store[parent]) < 0;\n    }\n}",
        "solution_java": "class Solution {\n    public int maxEvents(int[][] events) {\n        Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]);\n        // here sorting the array on ths basis of last day because we want to finish the events which happens first,fist.\n        \n TreeSet<Integer> set =new TreeSet<>();\n        for(int i =1;i<=100000;i++){\n            set.add(i);\n        }\n        //initliasing a tree set to check available days ;\n        // a day can go maximum to 100000;\n        int ans =0;\n        for(int i =0;i<events.length;i++){\n         Integer  temp = set.ceiling(events[i][0]);\n            if(temp==null || temp >events[i][1])\n                continue;\n            else{\n                set.remove(temp);\n            ans +=1;\n            }\n        }\n        return ans;        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxEvents(vector<vector<int>>& events) {\n        int res=0;\n        int m=0;\n        for(auto x:events)\n            m=max(m,x[1]);\n\n        sort(events.begin(),events.end());\n        int j=0;\n        priority_queue<int,vector<int>,greater<int>> pq;\n        for(int i=1;i<=m;i++)\n        {\n            while(!pq.empty() && pq.top()<i)// end day is less than the current day\n                pq.pop();\n\n            while(j<events.size() && events[j][0]==i)// put all events start at day i\n                pq.push(events[j++][1]);\n\n            if(!pq.empty())// we can attend an event today\n            {\n                pq.pop();// remove the event\n                res++;// count that event\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Day of the Week",
        "algo_input": "Given a date, return the corresponding day of the week for that date.\n\nThe input is given as three integers representing the day, month and year respectively.\n\nReturn the answer as one of the following values&nbsp;{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}.\n\n&nbsp;\nExample 1:\n\nInput: day = 31, month = 8, year = 2019\nOutput: \"Saturday\"\n\n\nExample 2:\n\nInput: day = 18, month = 7, year = 1999\nOutput: \"Sunday\"\n\n\nExample 3:\n\nInput: day = 15, month = 8, year = 1993\nOutput: \"Sunday\"\n\n\n&nbsp;\nConstraints:\n\n\n\tThe given dates are valid dates between the years 1971 and 2100.\n\n",
        "solution_py": "class Solution:\n    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n        LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5\n        DAYS = (\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\n        difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR), (day, month, year))\n        return DAYS[(difference + DAY) % 7]\n\n    def daysBetweenDates(self, date1: tuple, date2: tuple) -> int:\n        LOWEST_YEAR = 1971\n\n        def daysSinceLowest(date: tuple) -> int:\n            day, month, year = date\n\n            isLeapYear = lambda x: 1 if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else 0\n\n            days: int = 0\n            # days between the LOWEST_YEAR and year\n            days += 365 * (year - LOWEST_YEAR) + sum(map(isLeapYear, range(LOWEST_YEAR, year)))\n            # days between year and exact date\n            daysInMonth = (31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n            days += sum(daysInMonth[:month - 1]) + day\n            return days\n\n        return abs(daysSinceLowest(date1) - daysSinceLowest(date2))",
        "solution_js": "/**\n * @param {number} day\n * @param {number} month\n * @param {number} year\n * @return {string}\n */\nvar dayOfTheWeek = function(day, month, year) {\n    var map = {\n        0: \"Sunday\",\n        1: \"Monday\",\n        2: \"Tuesday\",\n        3: \"Wednesday\",\n        4: \"Thursday\",\n        5: \"Friday\",\n        6: \"Saturday\"\n    };\n    var date = new Date(`${month}/${day}/${year}`);\n    return map[date.getDay()];\n};",
        "solution_java": "class Solution {\n    public String dayOfTheWeek(int day, int month, int year) {\n        String[] week = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n        year--;\n        int total = (year/4)*366+(year-year/4)*365;\n        int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n        year++;\n        if(year%4==0 && year!=2100){\n            months[1]++;\n        }\n        for(int i=0;i<month-1;i++){\n            total+= months[i];\n        }\n        total +=day;\n        // for(int i:months){\n        //     System.out.print(i+\" \");\n        // }\n        // System.out.println();\n        return week[(total-1)%7];\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int daysOfMonth[2][12] = {\n        31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n    };\n    string weekName[7] = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n    bool isleapyear(int year)\n    {\n        return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));\n    }\n    int daystill1971(int year, int month, int day)\n    {\n        int count = 0;\n        int year1 = 1970, month1 = 1, day1 = 1;\n        while (year1 != year)\n        {\n            bool b = isleapyear(year1);\n            if (b) count += 366;\n            else count += 365;\n            year1++;\n        }\n        int b = isleapyear(year1) ? 0 : 1;\n        for (int i = 0; i < month - 1; i++) count += daysOfMonth[b][i];\n        count += day - 1;\n        return count;\n    }\n    string dayOfTheWeek(int day, int month, int year) {\n        int days1 = daystill1971(2019, 9, 8);//today(2019,9,8) is Sunday\n        int days2 = daystill1971(year, month, day);\n        int days = (((days2 - days1) % 7) + 7) % 7;//Number of days off\n        return weekName[days];\n    }\n};"
    },
    {
        "title": "Remove Nth Node From End of List",
        "algo_input": "Given the head of a linked list, remove the nth node from the end of the list and return its head.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5], n = 2\nOutput: [1,2,3,5]\n\n\nExample 2:\n\nInput: head = [1], n = 1\nOutput: []\n\n\nExample 3:\n\nInput: head = [1,2], n = 1\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is sz.\n\t1 &lt;= sz &lt;= 30\n\t0 &lt;= Node.val &lt;= 100\n\t1 &lt;= n &lt;= sz\n\n\n&nbsp;\nFollow up: Could you do this in one pass?\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n        if head == None:\n            return None\n        slow = head\n        fast = head\n        for i in range(n):\n            fast = fast.next\n        if fast == None:\n            return head.next\n        while fast != None and fast.next != None:\n            slow = slow.next\n            fast = fast.next\n        slow.next = slow.next.next\n        return head",
        "solution_js": "var removeNthFromEnd = function(head, n) {\n    let start = new ListNode(0, head);\n    let slow = start, fast = start;\n\n    for (let i =1; i <= n; i++) {\n        fast = fast.next;\n    }\n\n    while(fast && fast.next) {\n        slow = slow.next;\n        fast = fast.next;\n    }\n\n    let nthNode = slow.next\n    slow.next = nthNode.next;\n\n    return start.next;\n};",
        "solution_java": "class Solution {\n    public ListNode removeNthFromEnd(ListNode head, int n) {\n        ListNode temp = head;\n        int len=0;\n\n        if(head==null || head.next==null)\n            return null;\n\n        while(temp!=null){\n            temp=temp.next;\n            len++;\n        }\n\n        if(len==n)\n            return head.next;\n\n        int frontlen = len-n-1;\n\n        ListNode first=head.next;\n        ListNode second = head;\n\n        int count=0;\n\n        while(first!=null){\n            if(count==frontlen){\n                second.next=first.next;\n                break;\n            }else{\n                first=first.next;\n                second=second.next;\n                count++;\n            }\n        }\n\n        return head;\n    }\n}",
        "solution_c": " * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* removeNthFromEnd(ListNode* head, int n) {\n        ListNode* n1 = new ListNode();\n         ListNode *temp=head;\n         ListNode *p=head;\n        ListNode *q=n1;\n        n1->next=head;\n        int count;\n        while(temp)\n        { \n         \n            if(n>0){\n                n--;\n            }\n            else if(n==0){\n            cout<val;\n            p=p->next;\n            q=q->next;\n            }\n               temp=temp->next;\n        }\n        q->next=p->next;\n        delete p;\n    return n1->next;\n    }\n};"
    },
    {
        "title": "Find All Duplicates in an Array",
        "algo_input": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.\n\nYou must write an algorithm that runs in&nbsp;O(n)&nbsp;time and uses only constant extra space.\n\n&nbsp;\nExample 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [2,3]\nExample 2:\nInput: nums = [1,1,2]\nOutput: [1]\nExample 3:\nInput: nums = [1]\nOutput: []\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= nums[i] &lt;= n\n\tEach element in nums appears once or twice.\n\n",
        "solution_py": "class Solution:\n    def findDuplicates(self, nums: List[int]) -> List[int]:\n        res = []\n        hm = {}\n        # adding entries in hashmap to check frequency\n        for i, v in enumerate(nums):\n            if v not in hm:\n                hm[v] = 1\n            else:\n                hm[v] += 1\n        # checking frequency of item and adding output to an array\n        for key, value in hm.items():\n            if value > 1:\n                res.append(key)\n        return res",
        "solution_js": "// Approach : Mark Visited Elements in the Input Array itself\nvar findDuplicates = function(nums) {\n    let result = [];\n    for(let i = 0; i < nums.length; i++) {\n        let id = Math.abs(nums[i]) - 1;\n        if(nums[id] < 0) result.push(id + 1);\n        else nums[id] = - Math.abs(nums[id]);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public List<Integer> findDuplicates(int[] nums) {\n        List<Integer> ans = new ArrayList<>();\n        for(int i=0;i<nums.length;i++){\n            int ind = Math.abs(nums[i])-1;\n            if(nums[ind]<0){\n                ans.add(Math.abs(nums[i]));\n            }\n            else{\n                nums[ind] = -1*nums[ind];\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findDuplicates(vector<int>& nums) {\n        int n=nums.size();\n        vector<int> a;\n        vector<int> arr(n+1,0);\n        for(int i=0;i<nums.size();i++)\n            arr[nums[i]]++;\n\n        for(int j=0;j<=n;j++)\n            if(arr[j]==2) a.push_back(j);\n\n        return a;\n    }\n};"
    },
    {
        "title": "Koko Eating Bananas",
        "algo_input": "Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.\n\nKoko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.\n\nKoko likes to eat slowly but still wants to finish eating all the bananas before the guards return.\n\nReturn the minimum integer k such that she can eat all the bananas within h hours.\n\n&nbsp;\nExample 1:\n\nInput: piles = [3,6,7,11], h = 8\nOutput: 4\n\n\nExample 2:\n\nInput: piles = [30,11,23,4,20], h = 5\nOutput: 30\n\n\nExample 3:\n\nInput: piles = [30,11,23,4,20], h = 6\nOutput: 23\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= piles.length &lt;= 104\n\tpiles.length &lt;= h &lt;= 109\n\t1 &lt;= piles[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minEatingSpeed(self, piles: List[int], h: int) -> int:\n        def check(x):\n            return sum(ceil(ele/x) for ele in piles) <= h\n\n        l = 1\n        r = max(piles)\n        while l < r:\n            mid = (l+r) >> 1\n            if not check(mid):\n                l=mid+1\n            else:\n                r=mid\n        return l",
        "solution_js": "var minEatingSpeed = function(piles, h) {\n    /*The range of bananas that Koko can eat is k = 1 to Max(piles)*/\n    let startk = 1;\n    let endk = Math.max(...piles);\n    \n    while(startk <= endk){\n        let midk = Math.floor(startk + (endk - startk)/2);\n        /*midk are the count of bananas that koko decide to eat. \n        So how many hours she will take to finish the piles?*/\n        let hrs = 0;\n        for(let pile of piles){\n            /*pile is the num of bananas in piles*/\n            hrs += Math.ceil(pile/midk);\n        }\n        if(hrs > h){\n            /*Now if hrs > h she will not be to finish the pile so we have \n            to increase the bananas by moving start.*/\n            startk = midk + 1;\n        }else{\n            /*If hrs <= h she will be eating too fast so we can reduce the bananas \n            so she eats slowly. So decrement end.*/\n            endk = midk - 1;\n        }\n    }\n    return startk;\n};",
        "solution_java": "class Solution {\n    public int minEatingSpeed(int[] piles, int h) {\n        int max=0;\n        int ans=0;\n        for(int i=0;i<piles.length;i++)\n        {\n            max=Math.max(piles[i],max);\n        }\n        if(piles.length==h)\n            return max;\n        int left=1;\n        int right=max;\n        while(left<=right)\n        {\n            int mid=left+(right-left)/2;\n            double num=0;\n            int time=0;\n            for(int i=0;i<piles.length;i++)\n            {\n                num=(double)piles[i]/(mid);\n                if(num>piles[i]/mid)\n                    time+=num+1;\n                else\n                    time+=num;\n            }\n            if(time<=h)\n            {\n                ans=mid;\n                right=mid-1;\n            }\n            else\n                left=mid+1;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minEatingSpeed(vector<int>& piles, int h) {\n        \n        int mx=1000000001;\n        \n        \n        int st=1;\n        \n        \n        while(mx>st)\n        {\n            \n            int k = ((mx+st)/2);\n            \n            int sum=0;\n            \n            for(int i =0 ;i < piles.size() ; i++)\n            {\n                sum+=ceil(1.0 *piles[i]/k);\n            }\n            \n            if(sum>h)\n            {\n                st=k+1;\n            }\n            else\n            {\n                mx=k;\n            }\n            \n        }\n        \n        \n        return st;\n        \n        \n        \n    }\n};"
    },
    {
        "title": "Finding the Users Active Minutes",
        "algo_input": "You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.\n\nMultiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.\n\nThe user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.\n\nYou are to calculate a 1-indexed array answer of size k such that, for each j (1 &lt;= j &lt;= k), answer[j] is the number of users whose UAM equals j.\n\nReturn the array answer as described above.\n\n&nbsp;\nExample 1:\n\nInput: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput: [0,2,0,0,0]\nExplanation:\nThe user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n\n\nExample 2:\n\nInput: logs = [[1,1],[2,2],[2,3]], k = 4\nOutput: [1,1,0,0]\nExplanation:\nThe user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= logs.length &lt;= 104\n\t0 &lt;= IDi &lt;= 109\n\t1 &lt;= timei &lt;= 105\n\tk is in the range [The maximum UAM for a user, 105].\n\n",
        "solution_py": "class Solution:\n    def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n        ret = [0] * k  # UAM store\n        user_acts = {}  # User minutes store\n        \n        # Adding user minutes to hash table\n\t\tfor log in logs:\n            if user_acts.get(log[0], 0):\n                user_acts[log[0]].append(log[1])\n            else:\n                user_acts[log[0]] = [log[1]]\n                \n        # Calculating UAM\n\t\tfor k, v in user_acts.items():\n            l = len(set(v))\n            ret[l-1] += 1\n    \n        return ret",
        "solution_js": "var findingUsersActiveMinutes = function(logs, k) {\n    const map = new Map();\n\n    for (const [userID, minute] of logs) {\n        if (!map.has(userID)) map.set(userID, new Set());\n        map.get(userID).add(minute);\n    }\n\n    const count = new Array(k).fill(0);\n\n    for (const actions of map.values()) {\n        count[actions.size - 1]++;\n    }\n\n    return count;\n};",
        "solution_java": "class Solution {\n    public int[] findingUsersActiveMinutes(int[][] logs, int k) {\n        HashMap<Integer, HashSet<Integer>> usersMap = new HashMap();\n        \n        for(int[] log : logs){\n            int user = log[0];\n            int min = log[1];\n            \n            //add current user mapping, if not exist\n            usersMap.putIfAbsent(user, new HashSet<Integer>());\n            \n            //add unique new minute \n            usersMap.get(user).add(min);\n        }\n        \n        \n        \n        int[] result = new int[k];\n        for(int user : usersMap.keySet()){\n            int uam = usersMap.get(user).size();\n            //increment users count\n            result[uam - 1]++;\n         }\n\n\t\treturn result;\n        \n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) \n    {\n        vector<int>ans(k,0);\n        unordered_map<int,unordered_set<int>>m;\n\n        for(int i = 0; i<logs.size(); i++)\n        {\n            m[logs[i][0]].insert(logs[i][1]);\n        }\n        for(auto x : m)\n        {\n            int t = x.second.size();\n            ans[t-1]++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Obstacle Removal to Reach Corner",
        "algo_input": "You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:\n\n\n\t0 represents an empty cell,\n\t1 represents an obstacle that may be removed.\n\n\nYou can move up, down, left, or right from and to an empty cell.\n\nReturn the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,1,1],[1,1,0],[1,1,0]]\nOutput: 2\nExplanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.\n\n\nExample 2:\n\nInput: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\nOutput: 0\nExplanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 105\n\t2 &lt;= m * n &lt;= 105\n\tgrid[i][j] is either 0 or 1.\n\tgrid[0][0] == grid[m - 1][n - 1] == 0\n\n",
        "solution_py": "class Solution:\n    def minimumObstacles(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        q = [(0, 0, 0)]\n        dist = [[float('inf') for _ in range(n)] for _ in range(m)]\n\n        while q:\n            size = len(q)\n            for _ in range(size):\n                obs, x, y = heapq.heappop(q)\n                if dist[x][y] < float('inf'): continue\n                obs += grid[x][y]\n                dist[x][y] = obs\n                if x + 1 < m: heapq.heappush(q, (obs, x + 1, y))\n                if x > 0: heapq.heappush(q, (obs, x - 1, y))\n                if y + 1 < n: heapq.heappush(q, (obs, x, y + 1))\n                if y > 0: heapq.heappush(q, (obs, x, y - 1))\n        return dist[m - 1][n - 1]",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumObstacles = function(grid) {\n    let dx=[[0,1],[0,-1],[1,0],[-1,0]];\n    let distance=[];\n    for(let i=0;i<grid.length;i++){\n        distance[i]=[];\n        for(let j=0;j<grid[i].length;j++){\n            distance[i][j]=Number.MAX_SAFE_INTEGER;\n        }\n    }\n    return bfs(0,0);\n\n    function bfs(row,col){\n        let queue=[];\n        distance[row][col]=0;\n        queue.push([row,col]);\n        while(queue.length>0){\n            let element = queue.shift();\n            let row = element[0];\n            let col = element[1];\n            let originalDist = distance[row][col];\n            for(let d=0;d<dx.length;d++){\n                let i = row + dx[d][0];\n                let j = col + dx[d][1];\n                if(i>=0 && i<=grid.length-1 && j>=0 && j<=grid[i].length-1){\n                    let dist = originalDist;\n                    if(grid[i][j]===1){\n                        dist++;\n                    }\n                    if(distance[i][j]>dist){//Update distance for this neighbour node if the new distance is smaller than the previous distance\n                        queue.push([i,j]);\n                        distance[i][j]=dist;\n                    }\n\n                }\n            }\n        }\n        //return the minimum distance for last cell after completing the process\n        return distance[(grid.length-1)][(grid[row].length-1)];\n    }\n};",
        "solution_java": "class Solution {\n    int [][]grid;\n    int n,m;\n    boolean [][]seen;\n    int []dx = new int[]{0,0,1,-1};\n    int []dy = new int[]{1,-1,0,0};\n    int [][]dp;\n    int finalres;\n    private boolean isValid(int i, int j) {\n        return Math.min(i,j)>=0 && i<n && j<m && !seen[i][j];\n    }\n    \n    private int solve(int i, int j, int cnt) {\n        if(cnt>=finalres) return finalres;\n        if(i == n-1 && j == m-1) {\n            return cnt;\n        }\n        if(dp[i][j]!=Integer.MAX_VALUE) return dp[i][j];\n        int res = n*m+1;\n        seen[i][j]=true;\n        for(int k=0;k<4;k++) {\n            int newI = i+dx[k], newJ = j+dy[k];\n            if(isValid(newI, newJ)) {\n                res = Math.min(res, solve(newI, newJ, cnt+grid[i][j]));\n            }\n        }\n        seen[i][j]=false;\n        return dp[i][j]=Math.min(dp[i][j], res);\n    }\n    \n    public int minimumObstacles(int[][] grid) {\n        this.grid = grid;\n        this.n = grid.length;\n        this.m = grid[0].length;\n        this.seen = new boolean[n][m];\n        dp = new int[n][m];\n        finalres = n*m+1;\n        for(int []row:dp) Arrays.fill(row, Integer.MAX_VALUE);\n        return solve(0,0,0);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumObstacles(vector<vector<int>>& grid) {\n      int m=grid.size(), n=grid[0].size();\n        vector<int> dir={0,1,0,-1,0};\n        vector<vector<int>> dist(m, vector<int> (n,INT_MAX));\n        vector<vector<bool>> vis(m, vector<bool>(n,0));\n        deque<pair<int,int>>q;\n        dist[0][0]=0;\n        q.push_front({0,0});\n        while(!q.empty())\n        {\n            auto cur=q.front();\n            q.pop_front();\n            int x=cur.first;\n            int y=cur.second;\n            for(int i=0;i<4;i++)\n            {\n                int cx=x+dir[i];\n                int cy=y+dir[i+1];\n            if(cx>=0 and cy>=0 and cx<m and cy<n)\n            {\n                if(!vis[cx][cy])\n                {\n                    dist[cx][cy]=dist[x][y]+(grid[cx][cy]==1);\n                    if(grid[cx][cy]==1)\n                        q.push_back({cx,cy});//obstacle cell pushed at the end\n                    else\n                    q.push_front({cx,cy}); //empty cell pushed on top\n                    vis[cx][cy] = true;\n                }\n            }\n        }\n    }\n        return dist[m-1][n-1];\n    }\n};"
    },
    {
        "title": "House Robber III",
        "algo_input": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.\n\nBesides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.\n\nGiven the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,2,3,null,3,null,1]\nOutput: 7\nExplanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\n\n\nExample 2:\n\nInput: root = [3,4,5,1,3,null,1]\nOutput: 9\nExplanation: Maximum amount of money the thief can rob = 4 + 5 = 9.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t0 &lt;= Node.val &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def rob(self, root: Optional[TreeNode]) -> int:\n        hashMap = {}\n        \n        def helper(root: Optional[TreeNode]) -> int:\n            if not root:\n                return 0\n            if root in hashMap:\n                return hashMap[root]\n            ansOption1 = root.val\n            if root.left is not None:\n                ansOption1 += (helper(root.left.left) + helper(root.left.right))\n            if root.right is not None:\n                ansOption1 += (helper(root.right.left) + helper(root.right.right))\n            ansOption2 = helper(root.left) + helper(root.right)\n            ansFinal = max(ansOption1, ansOption2)\n            hashMap[root] = ansFinal\n            return ansFinal\n        \n        return helper(root)\n                ",
        "solution_js": "var rob = function(root) {\n    const dfs = (node = root) => {\n        if (!node || node.val === null) return [0, 0];\n        const { val, left, right } = node;\n        const [robL, notRobL] = dfs(left);\n        const [robR, notRobR] = dfs(right);\n        const rob = val + notRobL + notRobR;\n        const notRob = Math.max(robL, notRobL) + Math.max(robR, notRobR);\n\n        return [rob, notRob];\n    };\n\n    return Math.max(...dfs());\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    static class Pair{\n        int withRob=0;\n        int withoutRob=0;\n    } \n    public int rob(TreeNode root) {\n        Pair nodeRob=rob_(root);\n        \n        return Math.max(nodeRob.withRob,nodeRob.withoutRob);\n    }\n    \n    public Pair rob_(TreeNode root){\n        if(root==null){\n            return new Pair();\n        }\n        \n        Pair l=rob_(root.left);\n        Pair r=rob_(root.right);\n        \n        Pair nodeRob=new Pair();\n        nodeRob.withRob=root.val+l.withoutRob+r.withoutRob;\n                nodeRob.withoutRob=Math.max(l.withRob,l.withoutRob)+Math.max(r.withRob,r.withoutRob);\n        return nodeRob;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> dp(TreeNode* root)\n    {\n        vector<int> ans(2,0); //dp[0]: maximal money you can get by robbing current node. dp[1]: maximal money you can get when not rob this node\n        if(root==NULL) return ans;\n        vector<int> left=dp(root->left);\n        vector<int> right=dp(root->right);\n        ans[0]=root->val+left[1]+right[1];\n        ans[1]=max(left[0],left[1])+max(right[0],right[1]);\n        return ans;\n    }\n    int rob(TreeNode* root) {\n        vector<int> ans=dp(root);\n        return max(ans[0],ans[1]);\n    }\n};"
    },
    {
        "title": "Add Strings",
        "algo_input": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.\n\nYou must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.\n\n&nbsp;\nExample 1:\n\nInput: num1 = \"11\", num2 = \"123\"\nOutput: \"134\"\n\n\nExample 2:\n\nInput: num1 = \"456\", num2 = \"77\"\nOutput: \"533\"\n\n\nExample 3:\n\nInput: num1 = \"0\", num2 = \"0\"\nOutput: \"0\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num1.length, num2.length &lt;= 104\n\tnum1 and num2 consist of only digits.\n\tnum1 and num2 don't have any leading zeros except for the zero itself.\n\n",
        "solution_py": "class Solution:\n    def addStrings(self, num1: str, num2: str) -> str:\n        def func(n):\n            value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}\n            result = 0\n            for digit in n:\n                result = 10 * result + value[digit]\n\n            return result\n\n        ans = func(num1) + func(num2)\n        return str(ans)",
        "solution_js": "var addStrings = function(num1, num2) {\n    let i = num1.length - 1;\n    let j = num2.length - 1;\n    let carry = 0;\n    let sum = '';\n     \n    for (;i >= 0 || j >= 0 || carry > 0;i--, j--) {\n        const digit1 = i < 0 ? 0 : num1.charAt(i) - '0';\n        const digit2 = j < 0 ? 0 : num2.charAt(j) - '0';\n        const digitsSum = digit1 + digit2 + carry;\n        sum = `${digitsSum % 10}${sum}`;\n        carry = Math.floor(digitsSum / 10);\n    }\n    \n    return sum;\n};",
        "solution_java": "import java.math.BigInteger;\nclass Solution {\n    public String addStrings(String num1, String num2) {\n        return new BigInteger(num1).add(new BigInteger(num2)).toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string ans=\"\";\n    int carry=0;\n    string addStrings(string num1, string num2) {\n        while(num1.size() && num2.size()){\n            int sum= (num1.back() -'0' + num2.back() -'0' + carry) ;\n            ans = (char)((sum%10) + '0') + ans;\n            carry= sum/10;\n            num1.pop_back();num2.pop_back();\n        }\n\n        while(num1.size()){\n            int sum= (num1.back() -'0' + carry) ;\n            ans = (char)((sum%10) + '0') + ans ;\n            carry= sum/10;\n            num1.pop_back();\n        }\n        while(num2.size()){\n            int sum= (num2.back() -'0' + carry) ;\n            ans = (char)((sum%10) + '0') + ans ;\n            carry= sum/10;\n            num2.pop_back();\n        }\n        if(carry) ans = (char)(carry+'0') + ans;\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Combinations",
        "algo_input": "Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].\n\nYou may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, k = 2\nOutput: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation: There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.\n\n\nExample 2:\n\nInput: n = 1, k = 1\nOutput: [[1]]\nExplanation: There is 1 choose 1 = 1 total combination.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 20\n\t1 &lt;= k &lt;= n\n\n",
        "solution_py": "class Solution:\n    def combine(self, n: int, k: int) -> List[List[int]]:\n        return itertools.combinations(range(1, n+1), k)",
        "solution_js": "var combine = function(n, k) {\n\n    function helper (start, end, combo, subset, answer) {\n        if (combo==0) {\n            answer.push([...subset])\n            return;\n        }\n        if (end - start + 1 < combo) {\n            return;\n        }\n        if (start > end) {\n            return;\n        }\n        subset.push(start)\n        helper(start+1, end, combo - 1, subset, answer)\n\n        subset.pop()\n        helper(start+1, end, combo, subset, answer)\n    }\n\n    const answer = []\n    helper(1, n, k, [], answer)\n    return answer\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> combine(int n, int k) {\n        List<List<Integer>> subsets=new ArrayList<>();\n        generatesubsets(1,n,new ArrayList(),subsets,k);\n        return subsets;\n    }\n    void generatesubsets(int start,int n,List<Integer> current,List<List<Integer>> subsets,int k){\n        if(current.size()==k){\n            subsets.add(new ArrayList(current));\n        }\n        for(int i=start;i<=n;i++){\n            current.add(i);\n            generatesubsets(i+1,n,current,subsets,k);\n            current.remove(current.size()-1);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void solve(vector<int> arr,vector<vector<int>> &ans,vector<int> &temp,int k,int x){\n        if(temp.size()==k){\n            ans.push_back(temp);\n            return;\n        }\n        if(x>=arr.size()) return ;\n        for(int i = x;i<arr.size();i++){\n            temp.push_back(arr[i]);\n            solve(arr,ans,temp,k,i+1);\n            temp.pop_back();\n        }\n}\n    vector<vector<int>> combine(int n, int k) {\n        vector<vector<int>> ans;\n        vector<int> temp;\n        vector<int> arr;\n        for(int i = 1;i<=n;i++) arr.push_back(i);\n        solve(arr,ans,temp,k,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Palindrome by Concatenating Two Letter Words",
        "algo_input": "You are given an array of strings words. Each element of words consists of two lowercase English letters.\n\nCreate the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.\n\nReturn the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.\n\nA palindrome is a string that reads the same forward and backward.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"lc\",\"cl\",\"gg\"]\nOutput: 6\nExplanation: One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.\n\n\nExample 2:\n\nInput: words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput: 8\nExplanation: One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.\n\n\nExample 3:\n\nInput: words = [\"cc\",\"ll\",\"xx\"]\nOutput: 2\nExplanation: One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 105\n\twords[i].length == 2\n\twords[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution(object):\n    def longestPalindrome(self, words):\n        wc = collections.Counter(words)\n        aa = 0  # count how many words contain only two identical letters like 'aa'\n        center = 0  # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n        abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively\n\n        for w, c in wc.items():\n            if w[0] == w[1]: # like 'aa', 'bb', ...\n                aa += c // 2 * 2 # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively\n                # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n                if c % 2 == 1: center = 2\n            else:\n                abba += min(wc[w], wc[w[::-1]]) * 0.5  # will definitely double counting\n        return aa * 2 + int(abba) * 4 + center",
        "solution_js": "var longestPalindrome = function(words) {\n    const n = words.length;\n    const map = new Map();\n\n    let len = 0;\n\n    for (const word of words) {\n         const backward = word.split(\"\").reverse().join(\"\");\n\n        if (map.has(backward)) {\n            len += (word.length * 2);\n            map.set(backward, map.get(backward) - 1);\n\n            if (map.get(backward) === 0) map.delete(backward);\n        }\n        else {\n            if (!map.has(word)) map.set(word, 0);\n            map.set(word, map.get(word) + 1);\n        }\n    }\n\n    let maxLenSelfPalindrome = 0;\n\n    for (const word of map.keys()) {\n        if (isPalindrome(word)) {\n            maxLenSelfPalindrome = Math.max(maxLenSelfPalindrome, word.length);\n        }\n    }\n\n    return len + maxLenSelfPalindrome;\n\n    function isPalindrome(word) {\n        let left = 0;\n        let right = word.length - 1;\n\n        while (left < right) {\n            if (word[left] != word[right]) return false;\n            left++;\n            --right;\n        }\n\n        return true;\n    }\n};",
        "solution_java": "class Solution {\n  public int longestPalindrome(String[] words) {\n    int[][] freq = new int[26][26];//array for all alphabet combinations\n    for (String word : words)\n      freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word\n    int left = 0;//to store freq counts\n    boolean odd = false;\n    for (int i = 0; i != 26; i++) {//iterate over our array\n      odd |= (freq[i][i] & 1) == 1;//means odd number of freq for similar words are there\n      left += freq[i][i] / 2;\n      for (int j = i + 1; j != 26; j++)//nested iteration to find non similar pairs\n        left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present\n    }\n    int res = left * 2 * 2;//res from total freq found!!\n    if (odd){\n        res+=2;// if odd then adding 2\n    }\n    return res;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestPalindrome(vector<string>& words) {\n\n       int count[26][26] = {};\n       int ans =0;\n\n            for(auto w : words){\n                int a = w[0] - 'a';\n                int b = w[1] - 'a';\n\n                if(count[b][a]){\n                    ans+= 4;\n                    count[b][a]--; // decrement the count as we found mirror word\n                }else\n                    count[a][b]++; //increment the current word count if we not find any mirror word\n            }\n\n            for(int i=0;i<26;i++){\n                if(count[i][i]){\n                    ans+=2;\n                    break;\n                }\n             }\n\n    return ans;\n\n    }\n};"
    },
    {
        "title": "Jump Game IV",
        "algo_input": "Given an array of&nbsp;integers arr, you are initially positioned at the first index of the array.\n\nIn one step you can jump from index i to index:\n\n\n\ti + 1 where:&nbsp;i + 1 &lt; arr.length.\n\ti - 1 where:&nbsp;i - 1 &gt;= 0.\n\tj where: arr[i] == arr[j] and i != j.\n\n\nReturn the minimum number of steps to reach the last index of the array.\n\nNotice that you can not jump outside of the array at any time.\n\n&nbsp;\nExample 1:\n\nInput: arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput: 3\nExplanation: You need three jumps from index 0 --&gt; 4 --&gt; 3 --&gt; 9. Note that index 9 is the last index of the array.\n\n\nExample 2:\n\nInput: arr = [7]\nOutput: 0\nExplanation: Start index is the last index. You do not need to jump.\n\n\nExample 3:\n\nInput: arr = [7,6,9,6,9,6,9,7]\nOutput: 1\nExplanation: You can jump directly from index 0 to index 7 which is last index of the array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 5 * 104\n\t-108 &lt;= arr[i] &lt;= 108\n\n",
        "solution_py": "from collections import deque\nclass Solution:\n    def minJumps(self, arr: List[int]) -> int:\n        minSteps = 0\n        queue = deque()\n        queue.append(0)\n        n = len(arr)\n        visited = set()\n        visited.add(0)\n        \n\t\td = {i:[] for i in arr}\n        \n        for i, val in enumerate(arr):\n            d[val].append(i)\n        \n        while queue:\n            for _ in range(len(queue)):\n                idx = queue.popleft()\n                if idx == n - 1:\n                    return minSteps\n                \n                for i in [*d[arr[idx]], idx - 1, idx + 1]:\n                    if i not in visited and 0 <= i < n:\n                        visited.add(i)\n                        queue.append(i)\n                d[arr[idx]].clear()\n            minSteps += 1",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar minJumps = function(arr) {\n    if(arr.length <= 1) return 0;\n    \n    const graph = {};\n    \n    for(let idx = 0; idx < arr.length; idx ++) {\n        const num = arr[idx];\n        if(graph[num] === undefined) graph[num] = [];\n        graph[num].push(idx);\n    }\n    \n    let queue = [];\n    const visited = new Set();\n    \n    queue.push(0);\n    visited.add(0);\n    \n    let steps = 0;\n    \n    while(queue.length) {\n        const nextQueue = [];\n        \n        for(const idx of queue) {\n            if(idx === arr.length - 1) return steps;\n            \n            const num = arr[idx];\n            \n            for(const neighbor of graph[num]) {\n                if(!visited.has(neighbor)) {\n                    visited.add(neighbor);\n                    nextQueue.push(neighbor);\n                }\n            }\n            \n            if(idx + 1 < arr.length && !visited.has(idx + 1)) {\n                visited.add(idx + 1);\n                nextQueue.push(idx + 1);\n            }\n            \n            if(idx - 1 >= 0 && !visited.has(idx - 1)) {\n                visited.add(idx - 1);\n                nextQueue.push(idx - 1);\n            }\n            \n            graph[num].length = 0;\n        }\n        \n        queue = nextQueue;\n        steps ++;\n    }\n    \n    return -1;\n};",
        "solution_java": "/*\nHere we are using map and queue\nmap for storing the array elements and where are the other indices of the same element\nand queue for BFS\n\nInitially we start with 0 index\nSo we offer it to the queue\nNow until the queue is empty we have to do few things for a given position\ni> check the next index (i+1)\nii> check the previous index(i-1)\niii> check all the indices of the list whih are present in the map\nonce these three things have been done we will\nremove the element that is arr[i]\nbecause if we did not remove it we are going to do the same repeated task over and over again\nand this will result in stack overflow\nso it is important to remove the indices which have been visited once\nevery time we check the queue we incease the answer because viewing a queue means that\nwe are not at the last index\n\nI hope the idea was clear :) you'll understand better when you see the code\n*/\nclass Solution {\n    public int minJumps(int[] arr) {\n        int n = arr.length;\n\n        if(n <= 1) return 0;\n        Map<Integer, List<Integer>> mp = new HashMap<>();\n        for(int i = 0;i < arr.length ; i++) {\n            if(!mp.containsKey(arr[i])) {\n                mp.put(arr[i],new ArrayList<>());\n            }\n            List<Integer> ls = mp.get(arr[i]);\n            ls.add(i);\n        }\n        //System.out.print(mp);\n        Queue<Integer> q = new LinkedList<>();\n        q.offer(0);\n        int ans = 0;\n        while(!q.isEmpty()) {\n            ans++;\n            int size = q.size();\n            for(int i = 0;i < size;i++)\n            {\n                int j = q.poll();\n                //adding j+1\n                if(j+1 < n && mp.containsKey(arr[j+1])) {\n                    if(j+1 == n-1) return ans;\n                    q.offer(j+1);\n                }\n                //adding j-1\n                if(j-1 > 0 && mp.containsKey(arr[j-1])) {\n                    q.offer(j-1);\n                }\n\n                //adding list indices\n                if(mp.containsKey(arr[j])) {\n                    for(int k : mp.get(arr[j])) {\n                        //if(k == n-1) return ans;\n                        if(k != j) {\n                             if(k == n-1) return ans;\n                            q.offer(k);\n                        }\n                    }\n                    mp.remove(arr[j]);\n                }\n             }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minJumps(vector<int>& arr) \n    {\n        int n = arr.size();\n        unordered_map<int, vector<int>>mp;\n        for (int i = 0; i < n; i++) mp[arr[i]].push_back(i);\n        \n        queue<int>q;\n        vector<bool>visited(n, false);\n        q.push(0);\n        int steps = 0;\n        while(!q.empty())\n        {\n            int size = q.size();\n            while(size--)\n            {\n                int currIdx = q.front();\n                q.pop();\n                if (currIdx == n - 1) return steps;\n                //================================================================\n                //EXPLORE ALL POSSIBLE OPTIONS\n                if (currIdx + 1 < n && !visited[currIdx + 1])  //OPTION-1 (Move Forward)\n                {\n                    visited[currIdx + 1] = true;\n                    q.push(currIdx + 1);\n                }\n                if (currIdx - 1 >= 0 && !visited[currIdx - 1]) //OPTION-2 (Move Backward)\n                {\n                    visited[currIdx - 1] = true;\n                    q.push(currIdx - 1);\n                }\n                for (int newIdx : mp[arr[currIdx]])  //OPTION-3 (Move to same valued idx)\n                {                                 //newIdx coud be before currIdx or after currIdx\n                    if (!visited[newIdx]) \n                    {\n                        visited[newIdx] = true;\n                        q.push(newIdx);\n                    }\n                }\n                //===================================================================\n                mp[arr[currIdx]].clear();    //EXPLAINED BELOW :)\n            }\n            steps++;\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Loud and Rich",
        "algo_input": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.\n\nYou are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).\n\nReturn an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.\n\n&nbsp;\nExample 1:\n\nInput: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput: [5,5,2,5,4,5,6,7]\nExplanation: \nanswer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.\n\n\nExample 2:\n\nInput: richer = [], quiet = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == quiet.length\n\t1 &lt;= n &lt;= 500\n\t0 &lt;= quiet[i] &lt; n\n\tAll the values of quiet are unique.\n\t0 &lt;= richer.length &lt;= n * (n - 1) / 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tAll the pairs of richer are unique.\n\tThe observations in richer are all logically consistent.\n\n",
        "solution_py": "class Solution:\n    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n        length = len(quiet)\n        arr = [i for i in range(length)]\n        indegree = [0 for _ in range(length)]\n        graph = collections.defaultdict(list)\n        dq = collections.deque([])\n        \n        for a, b in richer:\n            # Note that the graph is uni-directional\n            graph[a].append(b)\n            indegree[b] += 1\n\n        for i in range(length):\n            if not indegree[i]: \n                dq.append(i)\n    \n        while dq:\n            node = dq.popleft()\n            \n            for vertex in graph[node]:\n                indegree[vertex] -= 1\n                if quiet[arr[node]] < quiet[arr[vertex]]:\n                    arr[vertex] = arr[node]\n                if not indegree[vertex]:\n                    dq.append(vertex)\n        return arr",
        "solution_js": "var loudAndRich = function(richer, quiet) {\n    const map = new Map();\n    for (const [rich, poor] of richer) {\n        map.set(poor, (map.get(poor) || new Set()).add(rich));        \n    }\n    \n    const memo = new Map();\n    const getQuietest = (person) => {\n        if (memo.has(person)) return memo.get(person);\n        const richerList = map.get(person);\n        let min = quiet[person];\n        let quietest = person;\n        if (!richerList) {\n            memo.set(person, quietest);\n            return quietest;\n        }\n        for (const rich of richerList) {         \n            if (quiet[getQuietest(rich)] < min) {\n                min = quiet[getQuietest(rich)];\n                quietest = getQuietest(rich);\n            }            \n        }\n        memo.set(person, quietest);\n        return quietest;\n    }\n    const answer = [];\n    for (let i=0; i<quiet.length; i++) {\n        answer.push(getQuietest(i));\n    }\n    return answer;\n};",
        "solution_java": "class Solution {\n        ArrayList<ArrayList<Integer>> adj =new ArrayList<>();\n        int res[];\n    public int[] loudAndRich(int[][] richer, int[] quiet) {\n        int n=quiet.length;\n        res=new int[n];\n        Arrays.fill(res,-1);\n         for(int i=0;i<n;i++)\n            adj.add(new ArrayList<Integer>());\n        for(int i=0;i<richer.length;i++)\n        {\n            if(adj.get(richer[i][1])==null)\n                adj.add(new ArrayList<>());\n            adj.get(richer[i][1]).add(richer[i][0]);\n        }\n        for(int i=0;i<n;i++)\n            dfs(i,quiet);\n        return res;\n    }\n    public int dfs(int node ,int[] quiet)\n    {\n        if(res[node]==-1)\n        {\n            res[node]=node;\n            for(int v:adj.get(node)){\n                int cand=dfs(v,quiet);\n                if(quiet[cand]<quiet[res[node]])\n                res[node]=cand;\n            }\n        }\n        return res[node];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int dfs(int node,vector<int> &answer,vector<int> adjList[],vector<int>& quiet)\n    {\n        if(answer[node]==-1)\n        {\n            answer[node] = node;\n            for(int child:adjList[node])\n            {\n                int cand = dfs(child,answer,adjList,quiet);\n                if(quiet[cand]<quiet[answer[node]])\n                    answer[node] = cand;\n            }\n        }\n\n        return answer[node];\n    }\n    vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n\n        int n = quiet.size();\n\n        vector<int> adjList[n];\n\n        for(auto x:richer)\n        {\n            int v = x[0];\n            int u = x[1];\n            adjList[u].push_back(v);\n        }\n\n        vector<int> answer(n,-1);\n\n        for(int node =0;node<n;node++)\n        {\n            dfs(node,answer,adjList,quiet);\n        }\n\n        return answer;\n    }\n};"
    },
    {
        "title": "Subtract the Product and Sum of Digits of an Integer",
        "algo_input": "Given an integer number n, return the difference between the product of its digits and the sum of its digits.\n&nbsp;\nExample 1:\n\nInput: n = 234\nOutput: 15 \nExplanation: \nProduct of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15\n\n\nExample 2:\n\nInput: n = 4421\nOutput: 21\nExplanation: \nProduct of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 10^5\n\n",
        "solution_py": "class Solution:\n    def subtractProductAndSum(self, n: int) -> int:\n        n_to_list = list(str(n))\n        \n        sum_of_digits = 0 \n        for num in n_to_list:\n            sum_of_digits = sum_of_digits + int(num)\n        \n        product_of_digits = 1\n        for num in n_to_list:\n            product_of_digits = product_of_digits * int(num)\n            \n        answer = product_of_digits - sum_of_digits\n        \n        return answer",
        "solution_js": "var subtractProductAndSum = function(n) {\n  let product=1,sum=0\n  n=n.toString().split('')\n  n.forEach((x)=>{\n   product *=parseInt(x)\n   sum +=parseInt(x)\n  }\n  )\n    return product-sum\n  };",
        "solution_java": "class Solution {\n    public int subtractProductAndSum(int n) {\n        int mul=1,sum=0;\n        while(n!=0){\n            sum=sum+n%10;\n            mul=mul*(n%10);\n            n=n/10;\n        }\n        return mul-sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int subtractProductAndSum(int n) {\n        vector<int> digit;\n        int product=1;\n        int sum=0;\n        while(n>0){\n            digit.push_back(n%10);\n            n/=10;\n        }\n        for(int i=0;i<digit.size();i++){\n            product*=digit[i];\n            sum+=digit[i];\n        }\n        return product-sum;\n\n    }\n};"
    },
    {
        "title": "DI String Match",
        "algo_input": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:\n\n\n\ts[i] == 'I' if perm[i] &lt; perm[i + 1], and\n\ts[i] == 'D' if perm[i] &gt; perm[i + 1].\n\n\nGiven a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.\n\n&nbsp;\nExample 1:\nInput: s = \"IDID\"\nOutput: [0,4,1,3,2]\nExample 2:\nInput: s = \"III\"\nOutput: [0,1,2,3]\nExample 3:\nInput: s = \"DDI\"\nOutput: [3,2,0,1]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either 'I' or 'D'.\n\n",
        "solution_py": "class Solution:\n    def diStringMatch(self, s: str) -> List[int]:\n        result = []\n        min_ = 0\n        max_ = len(s)\n        for x in s:\n            if x==\"I\":\n                result.append(min_)\n                min_ += 1\n            elif x==\"D\":\n                result.append(max_)\n                max_ -= 1\n        result.append(min_)\n        return result",
        "solution_js": "var diStringMatch = function(s) {\n    let i = 0, d = s.length, arr = [];\n    \n    for(let j = 0; j <= s.length; j += 1) {\n        if(s[j] === 'I') arr.push(i++);\n        else arr.push(d--);\n    }\n    \n    return arr;\n};",
        "solution_java": "class Solution {\n    public int[] diStringMatch(String s) {\n        int low = 0;\n        int high = s.length();\n        int[] ans = new int[s.length() + 1];\n        for(int i = 0; i < s.length(); i++){\n            if(s.charAt(i) == 'I'){\n                ans[i] = low++;\n            } else{\n                ans[i] = high--;\n            }\n        }\n        ans[s.length()] = high;\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> diStringMatch(string s) {\n        int p=0, j=s.size();\n        vector<int>v;\n        for(int i=0; i<=s.size(); i++)\n        {\n            if(s[i]=='I')v.push_back(p++);\n            else v.push_back(j--);\n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Partition Array Such That Maximum Difference Is K",
        "algo_input": "You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.\n\nReturn the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,6,1,2,5], k = 2\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.\n\n\nExample 2:\n\nInput: nums = [1,2,3], k = 1\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].\n\n\nExample 3:\n\nInput: nums = [2,2,4,5], k = 0\nOutput: 3\nExplanation:\nWe can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\t0 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def partitionArray(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        ans = 1\n\t\t# To keep track of starting element of each subsequence\n        start = nums[0]\n        \n        for i in range(1, len(nums)):\n            diff = nums[i] - start\n            if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n                ans += 1\n                start = nums[i]\n        \n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar partitionArray = function(nums, k) {\n\n    nums.sort((a,b) =>{ return a-b})\n\n    let n = nums.length ,ans=0\n\n    for(let i=0 ; i<n; i++){\n        let ele = nums[i]\n        while(i<n && nums[i]-ele<=k) i++\n        i--\n        ans++\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n\n    public int partitionArray(int[] nums, int k) {\n        Arrays.sort(nums);\n        int c = 1, prev = 0;\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] - nums[prev] <= k) continue;\n            c++; prev = i;\n        }\n        return c;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int partitionArray(vector<int>& nums, int k) {\n        \n        int n(size(nums)), res(0);\n        sort(begin(nums), end(nums));\n    \n        for (int start=0, next=0; start<n;) {\n            while (next<n and nums[next]-nums[start] <= k) next++;            \n            start = next;\n            res++;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "K Inverse Pairs Array",
        "algo_input": "For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 &lt;= i &lt; j &lt; nums.length and nums[i] &gt; nums[j].\n\nGiven two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, k = 0\nOutput: 1\nExplanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n\n\nExample 2:\n\nInput: n = 3, k = 1\nOutput: 2\nExplanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\t0 &lt;= k &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def kInversePairs(self, n: int, k: int) -> int:\n        # Complexity:\n        # - Time: O(N*K)\n        # - Space: O(K)\n\n        # Special cases that can be short-circuited right away\n        # - For k=0, there's only one solution, which is having the numbers in sorted order\n        #     DP(n, 0) = 1\n        if k == 0:\n            return 1\n        # - There can't be more than n*(n-1)/2 inverse pairs, which corresponds to the numbers in reverse order\n        #     DP(n, k) = 0 for all k > n*(n-1)/2\n        if k > n * (n - 1) // 2:\n            return 0\n\n        # For the general case, we notice that:\n        #     DP(n+1, k) = sum(DP(n, i) for i in [max(0, k-n), k])\n        # i.e., adding an additional number (the biggest one n+1):\n        # - We can have it at the end, in which case it doesn't create any reverse pairs,\n        #   and so the number of configurations with k reverse pairs is DP(n,k)\n        # - Or we can have it one before the end, in which case it creates exactly reverse pairs,\n        #   and so the number of configurations with k reverse pairs is DP(n,k-1)\n        # - And so on and so forth, such that having it `i` places before the end create exactly `i` reverse pairs,\n        #   and so the number of configurations with k reverse pairs is DP(n,k-i)\n        # This relationship allows us to compute things iteratively with a rolling window sum\n        kLine = [0] * (k + 1)\n        kLine[0] = 1\n        previousKLine = kLine.copy()\n        maxFeasibleK = 0\n        for m in range(2, n + 1):\n            previousKLine, kLine = kLine, previousKLine\n            rollingWindowSum = 1\n            maxFeasibleK += m - 1\n            endKLineIdx = min(k, maxFeasibleK) + 1\n            intermediateKLineIdx = min(endKLineIdx, m)\n            for kLineIdx in range(1, intermediateKLineIdx):\n                rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx]) % _MODULO\n                kLine[kLineIdx] = rollingWindowSum\n            for kLineIdx in range(intermediateKLineIdx, endKLineIdx):\n                rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx] - previousKLine[kLineIdx - m]) % _MODULO\n                kLine[kLineIdx] = rollingWindowSum\n        return kLine[k]\n\n\n_MODULO = 10 ** 9 + 7",
        "solution_js": "var kInversePairs = function(n, k) {\n    const dp = new Array(n+1).fill(0).map(el => new Array(k+1).fill(0))\n    const MOD = Math.pow(10, 9) + 7\n\n    for(let i = 0; i < n+1; i++) {\n        dp[i][0] = 1\n    }\n\n    for(let i = 1; i <= n; i++) {\n        for(let j = 1; j <= k; j++) {\n            dp[i][j] = (dp[i][j-1] + dp[i-1][j] % MOD) - (j >= i ? dp[i-1][j-i] : 0)%MOD\n        }\n    }\n\n    return dp[n][k] % MOD\n};",
        "solution_java": "class Solution {\n    public int kInversePairs(int n, int k) {\n        int MOD = 1000000007;\n        int[][] opt = new int[k + 1][n];\n        for (int i = 0; i <= k; i++) {\n            for (int j = 0; j < n; j++) {\n                if (i == 0) {\n                    opt[i][j] = 1;\n                } else if (j > 0) {\n                    opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD;\n                    if (i >= j + 1) {\n                        opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD;\n                    }\n                }\n            }\n        }\n\n        return opt[k][n - 1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = (int)(1e9 + 7);\n    int dp[1001][1001] = {};\n    \n    int kInversePairs(int n, int k) {\n        //base case\n        if(k<=0) return k==0;\n        \n        if(dp[n][k]==0){\n            dp[n][k] = 1;\n            \n            for(int i=0; i<n; i++){\n                dp[n][k] = (dp[n][k] + kInversePairs(n-1,k-i))%mod;\n            }\n        }\n        return dp[n][k]-1;\n    }\n};"
    },
    {
        "title": "Search in a Binary Search Tree",
        "algo_input": "You are given the root of a binary search tree (BST) and an integer val.\n\nFind the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,7,1,3], val = 2\nOutput: [2,1,3]\n\n\nExample 2:\n\nInput: root = [4,2,7,1,3], val = 5\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 5000].\n\t1 &lt;= Node.val &lt;= 107\n\troot is a binary search tree.\n\t1 &lt;= val &lt;= 107\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n        def search(root):\n            if not root:return None\n            if root.val==val:\n                return root\n            elif root.val<val:\n                ans=search(root.right)\n                if ans:\n                    return ans\n                return None\n            else:\n                ans=search(root.left)\n                if ans:\n                    return ans\n                return None\n        return search(root)",
        "solution_js": "//====== Recursion ======\nvar searchBST = function(root, val) {\n    if (!root) return null;\n    if (root.val===val) return root;\n    return searchBST(root.left, val) || searchBST(root.right, val)\n}\n\n//====== Iteration ======\nvar searchBST = function(root, val) {\n    if (!root) return null;\n    let node = root\n\n    while (node) {\n        if (node.val === val) return node;\n        else node = node.val > val ? node.left : node.right\n    }\n\n    return node\n}",
        "solution_java": "class Solution {\n    public TreeNode searchBST(TreeNode root, int val) {\n        if (root == null) return root;\n        if (root.val == val) {\n            return root;\n        } else {\n            return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);\n        }\n    }\n}",
        "solution_c": "// Recursive\nclass Solution {\npublic:\n    TreeNode* searchBST(TreeNode* root, int& val) {\n        if(root==NULL) return NULL;\n        if(root->val==val) return root;\n        if(root->val>val) return searchBST(root->left,val);\n        return searchBST(root->right,val);\n    }\n};\n\n// Iterative\nclass Solution {\npublic:\n    TreeNode* searchBST(TreeNode* root, int val) {\n        while(root){\n            if(root->val==val) return root;\n            root=root->val>val?root->left:root->right;\n        }\n        return NULL;\n    }\n};"
    },
    {
        "title": "The Score of Students Solving Math Expression",
        "algo_input": "You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:\n\n\n\tCompute multiplication, reading from left to right; Then,\n\tCompute addition, reading from left to right.\n\n\nYou are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:\n\n\n\tIf an answer equals the correct answer of the expression, this student will be rewarded 5 points;\n\tOtherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;\n\tOtherwise, this student will be rewarded 0 points.\n\n\nReturn the sum of the points of the students.\n\n&nbsp;\nExample 1:\n\nInput: s = \"7+3*1*2\", answers = [20,13,42]\nOutput: 7\nExplanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\n\n\nExample 2:\n\nInput: s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput: 19\nExplanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\n\n\nExample 3:\n\nInput: s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput: 10\nExplanation: The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 31\n\ts represents a valid expression that contains only digits 0-9, '+', and '*' only.\n\tAll the integer operands in the expression are in the inclusive range [0, 9].\n\t1 &lt;= The count of all operators ('+' and '*') in the math expression &lt;= 15\n\tTest data are generated such that the correct answer of the expression is in the range of [0, 1000].\n\tn == answers.length\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= answers[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n        \n        @cache\n        def fn(lo, hi): \n            \"\"\"Return possible answers of s[lo:hi].\"\"\"\n            if lo+1 == hi: return {int(s[lo])}\n            ans = set()\n            for mid in range(lo+1, hi, 2): \n                for x in fn(lo, mid): \n                    for y in fn(mid+1, hi): \n                        if s[mid] == \"+\" and x + y <= 1000: ans.add(x + y)\n                        elif s[mid] == \"*\" and x * y <= 1000: ans.add(x * y)\n            return ans \n                \n        target = eval(s)\n        cand = fn(0, len(s))\n        ans = 0 \n        for x in answers: \n            if x == target: ans += 5\n            elif x in cand: ans += 2\n        return ans ",
        "solution_js": "var scoreOfStudents = function(s, answers) {\n    let correct=s.split('+').reduce((a,c)=>a+c.split('*').reduce((b,d)=>b*d,1),0),\n        n=s.length,dp=[...Array(n)].map(d=>[...Array(n)])\n    let dfs=(i=0,j=n-1)=>{\n        if(dp[i][j]!==undefined)\n            return dp[i][j]\n        if(i===j)\n            return dp[i][j]=[Number(s[i])]\n        let ans=new Set()\n        for(let k=i+1;k<=j-1;k+=2)\n            for(let a1 of dfs(i,k-1))\n                for(let a2 of dfs(k+1,j))\n                    if(s[k]==='*')\n                        ans.add(Number(a1)*Number(a2))\n                    else\n                        ans.add(Number(a1)+Number(a2))\n        return dp[i][j]=Array.from(ans).filter(d=>d<=1000)\n    }\n    dfs()\n    dp[0][n-1]=new Set(dp[0][n-1])\n    return answers.reduce( (a,c)=> a+ (c===correct?5:(dp[0][n-1].has(c)?2:0)) ,0)\n};",
        "solution_java": "class Solution {\n\n    HashMap<String , HashSet<Integer>> cache ;\n\n    public int scoreOfStudents(String s, int[] answers) {\n\n        cache = new HashMap();\n        HashSet<Integer> total_possible_ans = getPossibleAns(s);\n\n        int correct_ans = getCorrectAns(s);\n\n        int total_score = 0 ;\n        for(int i=0 ; i<answers.length ; i++){\n            if(answers[i] == correct_ans){\n                total_score += 5 ;\n            }else if(total_possible_ans.contains(answers[i])){\n                total_score += 2 ;\n            }\n        }\n\n        return total_score ;\n    }\n\n    public HashSet<Integer> getPossibleAns(String s){\n\n        if(cache.containsKey(s)){\n            return cache.get(s) ;\n        }\n\n        HashSet<Integer> possible_ans = new HashSet() ;\n\n        for(int i = 0 ; i<s.length() ; i++){\n\n            char cur = s.charAt(i) ;\n            HashSet<Integer> left = new HashSet() ;\n            HashSet<Integer> right = new HashSet() ;\n\n            if(cur == '+' || cur == '*'){\n                left = getPossibleAns(s.substring(0 , i));\n                right = getPossibleAns(s.substring(i+1));\n            }\n\n            for(Integer l : left){\n                for(Integer r : right){\n                    if(cur == '+'){\n                        if(l+r > 1000) continue ; // skiping for ans that are greater than 1000\n                        possible_ans.add(l+r);\n                    }else if(cur == '*'){\n                        if(l*r > 1000) continue ; // skiping for ans that are greater than 1000\n                        possible_ans.add(l*r);\n                    }\n                }\n            }\n        }\n\n        if(possible_ans.isEmpty() && s.length() <= 1){\n            possible_ans.add(Integer.parseInt(s));\n        }\n\n        cache.put(s , possible_ans);\n\n        return possible_ans ;\n    }\n\n    public int getCorrectAns(String s) {\n\n        Stack<Integer> stack = new Stack() ;\n\n        for(int i = 0 ; i<s.length() ; i++){\n\n            // push only integers into stack\n            if(s.charAt(i) != '+' && s.charAt(i) != '*'){\n                stack.push(Character.getNumericValue(s.charAt(i))) ;\n            }\n\n            // If operator is '*' , then take the last element from stack and multiply with next element\n            // Also push into stack , and then increment i also , to avoid pushing the same next element into stack again\n            if(s.charAt(i) == '*'){\n                int cur = stack.pop();\n                int next = Character.getNumericValue(s.charAt(i+1)) ;\n                stack.push(cur * next);\n                i++ ;\n            }\n        }\n\n        // Now sum all the element in the stack to get result for '+' operator\n        int total_sum = stack.pop() ;\n\n        while(!stack.isEmpty()){\n            total_sum += stack.pop() ;\n        }\n\n        return total_sum ;\n    }\n\n}",
        "solution_c": "class Solution {\n    int eval(int a, int b, char op) {\n        if (op == '+') {\n            return a + b;\n        } else {\n            return a * b;\n        }\n    }\n    \n    unordered_map<string_view, unordered_set<int>> mp;\n    unordered_set<int> potential;\n    \n    unordered_set<int>& solve(string_view s) {\n        if (auto it = mp.find(s); it != mp.end()) {\n            return it->second;\n        }\n        \n        bool res = true;\n        int n = 0;\n        unordered_set<int> ans;\n        for (int i = 0; i < s.size(); i++) {\n            char c = s[i];\n            if (c >= '0' && c <= '9') {\n                n = n * 10 + (c - '0');\n            } else {\n                n = 0;\n                res = false;\n                for (int l : solve(s.substr(0, i))) {\n                    for (int r : solve(s.substr(i + 1))) {\n                        int res2 = eval(l, r, c);\n                        if (res2 <= 1000) {\n                            ans.insert(res2);\n                        }\n                    }\n                }\n            }\n        }\n        if (res) {\n            ans.insert(n);\n        }\n        return mp[s] = ans;\n    }\n    \npublic:\n    int scoreOfStudents(string s, vector<int>& answers) {\n        int ans = 0, correct = 0;\n        stack<int> ns, op;\n        unordered_map<char, int> prec{\n            {'+', 1},\n            {'*', 2},\n            {'(', 0}\n        };\n        int n = 0;\n        for (int i = 0; i < s.size(); i++) {\n            char c = s[i];\n            if (c >= '0' && c <= '9') {\n                n = n * 10 + (c - '0');\n            } else if (c == '(') {\n                op.push(c);\n            } else if (c == ')') {\n                ns.push(n);\n                while (op.top() != '(') {\n                    int b = ns.top();\n                    ns.pop();\n                    int a = ns.top();\n                    ns.pop();\n                    ns.push(eval(a, b, op.top()));\n                    op.pop();\n                }\n                op.pop();\n                n = ns.top();\n                ns.pop();\n            } else {\n                ns.push(n);\n                n = 0;\n                int p = prec[c];\n                while (!op.empty() && prec[op.top()] >= p) {\n                    int b = ns.top();\n                    ns.pop();\n                    int a = ns.top();\n                    ns.pop();\n                    ns.push(eval(a, b, op.top()));\n                    op.pop();\n                }\n                op.push(c);\n            }\n        }\n        ns.push(n);\n        while (!op.empty()) {\n            int b = ns.top();\n            ns.pop();\n            int a = ns.top();\n            ns.pop();\n            ns.push(eval(a, b, op.top()));\n            op.pop();\n        }\n        correct = ns.top();\n        \n        string_view sv{s.data(), s.size()};\n        solve(sv);\n        for (int n2 : mp[sv]) {\n            potential.insert(n2);\n        }\n        \n        for (int n2 : answers) {\n            if (n2 == correct) {\n                ans += 5;\n            } else if (potential.find(n2) != potential.end()) {\n                ans += 2;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Cut Off Trees for Golf Event",
        "algo_input": "You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:\n\n\n\t0 means the cell cannot be walked through.\n\t1 represents an empty cell that can be walked through.\n\tA number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.\n\n\nIn one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\n\nYou must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).\n\nStarting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.\n\nNote: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.\n\n&nbsp;\nExample 1:\n\nInput: forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput: 6\nExplanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n\n\nExample 2:\n\nInput: forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput: -1\nExplanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n\n\nExample 3:\n\nInput: forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput: 6\nExplanation: You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == forest.length\n\tn == forest[i].length\n\t1 &lt;= m, n &lt;= 50\n\t0 &lt;= forest[i][j] &lt;= 109\n\tHeights of all trees are distinct.\n\n",
        "solution_py": "from collections import deque\n\nclass Solution:\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n        a = []\n        n = len(forest)\n        m = len(forest[0])\n        for i in range(n):\n            for j in range(m):\n                if forest[i][j] > 1:\n                    a.append(forest[i][j])\n        a.sort()\n        \n        s = 0\n        ux = 0\n        uy = 0\n        for h in a:\n            dist = [[None] * m for i in range(n)]\n            q = deque()\n            q.append((ux, uy))\n            dist[ux][uy] = 0\n            while q:\n                ux, uy = q.popleft()\n                if forest[ux][uy] == h:\n                    break\n                d = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n                for dx, dy in d:\n                    vx = ux + dx\n                    vy = uy + dy\n                    if vx < 0 or vx >= n or vy < 0 or vy >= m:\n                        continue\n                    if forest[vx][vy] == 0:\n                        continue\n                    if dist[vx][vy] is None:\n                        q.append((vx, vy))\n                        dist[vx][vy] = dist[ux][uy] + 1\n            if forest[ux][uy] == h:\n                s += dist[ux][uy]\n            else:\n                return -1\n        return s",
        "solution_js": "var cutOffTree = function(forest) {\n    const trees = forest.flat().filter(x => x && x !== 1).sort((a, b) => b - a);\n    let currPos = [0, 0], totalDist = 0;\n\n    while(trees.length) {\n        const grid = [...forest.map(row => [...row])];\n        const res = getDist(currPos, trees.pop(), grid);\n        if(res == null) return -1;\n        const [pos, dist] = res;\n        currPos = pos;\n        totalDist += dist;\n    }\n    return totalDist;    \n    \n    function getDist(start, target, grid) {\n        const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]];\n        let queue = [start], dist = 0;\n        \n        while(queue.length) {\n            const next = [];\n            \n            for(let [r, c] of queue) {\n                if(grid[r][c] === target) return [[r, c], dist];\n                if(!grid[r][c]) continue;\n                \n                for(let [x, y] of dir) {\n                    x += r; y += c;\n                    if(x >= 0 && x < grid.length && y >= 0 && \n                       y < grid[0].length && grid[x][y]) next.push([x, y])\n                }\n                grid[r][c] = 0;   \n            }\n            dist++;\n            queue = next;\n        }\n        return null;\n    }\n};",
        "solution_java": "class Solution {\n    //approach: 1st store all the positions in the min heap acc. to their height\n    //now start removing the elements from the heap and calculate their dis using bfs\n    // if at any point we cann't reach at the next position return -1;\n    // else keep on adding the distances and return;\n    public int cutOffTree(List<List<Integer>> forest) {\n       PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n       for(int i=0;i<forest.size();i++){\n           for(int j=0;j<forest.get(0).size();j++){\n               if(forest.get(i).get(j)>1)\n                   pq.add(new int[]{i,j});\n           }\n       }\n        int ans=0;\n       int curr[]={0,0};\n       while(pq.size()>0){\n           int[] temp=pq.poll();\n           int dis=calcDis(forest,curr,temp);\n           //System.out.println(dis+\" \"+temp.height);\n           if(dis==-1)\n               return -1;\n           ans+=dis;\n           curr=temp;\n       }\n        return ans;\n    }\n    int calcDis(List<List<Integer>> forest,int start[],int end[]){\n        int n=forest.size(),m=forest.get(0).size();\n        boolean vis[][]=new boolean[n][m];\n        Queue<int[]> queue=new LinkedList<>();\n        queue.add(start);\n        vis[start[0]][start[1]]=true;\n        int dis=0;\n        while(queue.size()>0){\n            int len =queue.size();\n            while(len-->0){\n                int temp[]=queue.remove();\n                int r=temp[0],c=temp[1];\n                if(r==end[0] && c==end[1])\n                    return dis;\n                if(r+1<n && !vis[r+1][c] && forest.get(r+1).get(c)!=0){\n                    queue.add(new int[]{r+1,c});\n                    vis[r+1][c]=true;\n                }if(r-1>=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n                    queue.add(new int[]{r-1,c});\n                    vis[r-1][c]=true;\n                }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n                    queue.add(new int[]{r,c-1});\n                    vis[r][c-1]=true;\n                }if(c+1<m && !vis[r][c+1] && forest.get(r).get(c+1)!=0){\n                    queue.add(new int[]{r,c+1});\n                    vis[r][c+1]=true;\n                }\n            }\n            dis++;\n        }\n        return -1;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    #define vi vector<int>\n    #define vvi vector<vi>\n    \n    vvi forests;\n    vvi moves;\n    int R;\n    int C;\n    \n    \n    bool isValid(int x,int y){\n        return x>=0&&x<R&&y>=0&&y<C;\n    }\n    \n    int getShortestDistance(int sx,int sy,int ex,int ey){\n        \n        vvi vis = vvi(R,vi(C,0));\n        queue<pair<int,int>>Q;\n        Q.push({sx,sy});\n        \n        vis[sx][sy] = 1;\n                \n        \n        int level = 0;\n        \n        while(!Q.empty()){\n            \n            queue<pair<int,int>>childQ;\n            \n            while(!Q.empty()){\n                \n                auto x = Q.front().first;\n                auto y = Q.front().second;\n                \n                Q.pop();\n                \n                if(x==ex&&y==ey)\n                    return level;\n                \n                for(auto ele:moves){\n                    \n                    int nextX = x+ele[0];\n                    int nextY = y+ele[1];\n                    \n                    if(isValid(nextX,nextY)&&!vis[nextX][nextY]&&forests[nextX][nextY]>0){\n                        childQ.push({nextX,nextY});\n                        vis[nextX][nextY]=1;\n                    }\n                    \n                }\n                \n                \n            }\n            Q=childQ;\n               \n            level++;\n        }\n        \n        return -1;\n    }\n    \n    int cutOffTree(vector<vector<int>>& forest) {\n        \n        moves={\n            {0,1},\n            {1,0},\n            {0,-1},\n            {-1,0}\n        };\n        \n        forests = forest;\n        \n        R = forest.size();\n        C = forest[0].size();\n        \n        if(forest[0][0]==0)\n            return -1;\n        \n        vector<vector<int>>trees;\n        int i=0;\n        \n        while(i<R){\n            int j=0;\n            while(j<C){\n                if(forest[i][j]>1)\n                    trees.push_back({forest[i][j],i,j});\n                \n                j++;\n            }\n            i++;\n        }\n        \n        if(trees.empty())\n            return -1;\n        \n        sort(trees.begin(),trees.end());\n        \n        int sx = 0;\n        int sy = 0;\n        \n        int ans = 0;\n        \n        for(auto it:trees){\n            \n            int dis = getShortestDistance(sx,sy,it[1],it[2]);\n            \n            if(dis==-1)\n                return -1;\n            ans+=dis;\n            sx = it[1];\n            sy = it[2];\n        }\n        \n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Paint House III",
        "algo_input": "There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.\n\nA neighborhood is a maximal group of continuous houses that are painted with the same color.\n\n\n\tFor example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].\n\n\nGiven an array houses, an m x n matrix cost and an integer target where:\n\n\n\thouses[i]: is the color of the house i, and 0 if the house is not painted yet.\n\tcost[i][j]: is the cost of paint the house i with the color j + 1.\n\n\nReturn the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.\n\n&nbsp;\nExample 1:\n\nInput: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 9\nExplanation: Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n\n\nExample 2:\n\nInput: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 11\nExplanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.\n\n\nExample 3:\n\nInput: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput: -1\nExplanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == houses.length == cost.length\n\tn == cost[i].length\n\t1 &lt;= m &lt;= 100\n\t1 &lt;= n &lt;= 20\n\t1 &lt;= target &lt;= m\n\t0 &lt;= houses[i] &lt;= n\n\t1 &lt;= cost[i][j] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n        @cache\n        def dp(i, p, h):\n            if (h > target) or (i == m and h != target):\n                return inf\n            if i == m:\n                return 0\n            if houses[i] != 0:\n                return dp(i + 1, houses[i], h + int(p != houses[i]))\n\n            best = inf\n            for j, c in enumerate(cost[i], 1):\n                best = min(best, dp(i + 1, j, h + int(p != j)) + c)\n            return best\n\n        res = dp(0, 0, 0)\n        return res if res != inf else -1",
        "solution_js": "var minCost = function(houses, cost, m, n, target) {\n    let map = new Map();\n\n    function dfs(idx = 0, prevColor = -1, neighborhoods = 0) {\n        if (idx === m) return neighborhoods === target ? 0 : Infinity;\n\n        let key = `${idx}-${prevColor}-${neighborhoods}`;\n        if (map.has(key)) return map.get(key);\n        \n        let color = houses[idx];\n        // If the current house is already painted\n        if (color > 0) {\n            return color !== prevColor ? dfs(idx + 1, color, neighborhoods + 1) : dfs(idx + 1, color, neighborhoods);\n        }\n\n        let minCost = Infinity;\n        for (let i = 1; i <= n; i++) {\n            let potentialCost;\n            // If color i is !== prevColor, increment the neighborhood count\n            if (i !== prevColor) potentialCost = dfs(idx + 1, i, neighborhoods + 1);\n            // Otherwise, the neighborhood simply expanded so the neighborhood count stays the same\n            else potentialCost = dfs(idx + 1, i, neighborhoods);\n            \n            if (potentialCost === Infinity) continue;\n            minCost = Math.min(minCost, cost[idx][i - 1] + potentialCost);\n        }\n        map.set(key, minCost);\n        return minCost;\n    }\n    \n    let minCost = dfs();\n    return minCost === Infinity ? -1 : minCost;\n};",
        "solution_java": "class Solution {\n    public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp)\n    {\n        if(idx==houses.length || neigh>target)\n        {\n            if(neigh==target)\n                return 0;\n            return Integer.MAX_VALUE;\n        }\n        if(dp[idx][prevColor][neigh]!=null)\n            return dp[idx][prevColor][neigh];\n        int minCost = Integer.MAX_VALUE;\n\n        if(houses[idx]==0)\n        {\n            for(int j = 0;j<cost[idx].length;j++)\n            {\n                int minCostHere = Integer.MAX_VALUE;\n\n                if(j+1==prevColor) // Painting the house with the same colour as that of the previous one.\n                    minCostHere = helper(idx+1,houses,cost,target,prevColor,neigh,dp);\n\n                else // Painting the house with a different color and incrementing the neighbour count.\n                    minCostHere = helper(idx+1,houses,cost,target,j+1,neigh+1,dp);\n\n                if(minCostHere!=Integer.MAX_VALUE)\n                    minCostHere+=cost[idx][j];\n\n                minCost = Math.min(minCostHere,minCost);\n            }\n        }\n        else\n        {\n            if(houses[idx]==prevColor)\n                minCost = helper(idx+1,houses,cost,target,prevColor,neigh,dp);\n            else\n                minCost = helper(idx+1,houses,cost,target,houses[idx],neigh+1,dp);\n        }\n\n        return dp[idx][prevColor][neigh] = minCost;\n\n    }\n    public int minCost(int[] houses, int[][] cost, int m, int n, int target) {\n\n        Integer[][][] dp = new Integer[m][n+1][target+1];\n        int ans = helper(0,houses,cost,target,0,0,dp);\n        return ans==Integer.MAX_VALUE?-1:ans;\n    }\n}",
        "solution_c": "class Solution {\n    int dp[101][22][101];\n    vector<int> h;//m\n    vector<vector<int>> c;//n\n    int mm; int nn; int t;\n    int dfs(int idx, int prev, int curt){\n        if(curt<1)\n            return INT_MAX;\n        if(idx==mm)\n            return (curt==1)?0:INT_MAX;\n        if(dp[idx][prev][curt]!=-1)\n            return dp[idx][prev][curt];\n        int res=INT_MAX;\n        int color=h[idx];\n        if(color==0){\n            for(int x=0;x<nn;x++){\n                color=x+1;\n                int rres=dfs(idx+1,color,curt-(prev!=21 and prev!=color));\n                if(rres!=INT_MAX)\n                    res=min(c[idx][color-1]+rres,res);\n            }\n        }else{\n            return dp[idx][prev][curt]=dfs(idx+1,color,curt-(prev!=21 and prev!=color));\n        }\n        return dp[idx][prev][curt]=res;\n    }\npublic:\n    int minCost(vector<int>& houses, vector<vector<int>>& cost, int m, int n, int target) {\n        h=houses,c=cost,mm=m,nn=n,t=target;\n        memset(dp,-1,sizeof(dp));\n        int res=dfs(0,21,t);\n        return res==INT_MAX?-1:res;\n    }\n};"
    },
    {
        "title": "Basic Calculator",
        "algo_input": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.\n\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n\n&nbsp;\nExample 1:\n\nInput: s = \"1 + 1\"\nOutput: 2\n\n\nExample 2:\n\nInput: s = \" 2-1 + 2 \"\nOutput: 3\n\n\nExample 3:\n\nInput: s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput: 23\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 3 * 105\n\ts consists of digits, '+', '-', '(', ')', and ' '.\n\ts represents a valid expression.\n\t'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).\n\t'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).\n\tThere will be no two consecutive operators in the input.\n\tEvery number and running calculation will fit in a signed 32-bit integer.\n\n",
        "solution_py": "```class Solution:\n    def calculate(self, s: str) -> int:\n        curr,output,sign,stack = 0,0,1,[]\n\n        for ch in s:\n            if ch.isdigit():\n                curr = curr * 10 + int(ch)\n\n            elif ch == '+':\n                output += sign * curr\n                sign = 1\n                curr = 0\n\n            elif ch == '-':\n                output += sign * curr\n                sign = -1\n                curr = 0\n\n            elif ch == '(':\n                #push the result and then the sign\n                stack.append(output)\n                stack.append(sign)\n                sign = 1\n                output = 0\n\n            elif ch == ')':\n                output += sign * curr\n                output *= stack.pop()\n                output += stack.pop()\n                curr = 0\n        return output + sign*curr``",
        "solution_js": "var calculate = function(s) {\n\n\tconst numStack = [[]];\n\tconst opStack = [];\n\n\tconst isNumber = char => !isNaN(char);\n\n\tfunction calculate(a, b, op){\n\t\tif(op === '+') return a + b;\n\t\tif(op === '-') return a - b;\n\t}\n\n\tlet number = '';\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst char = s[i];\n\n\t\tif (char === ' ') continue;\n\n\t\tif (isNumber(char)) {\n\t\t\tnumber += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(number) { // i.e. char is not a number so the number has ended\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(+number);\n\t\t\t} else {\n\t\t\t\tconst a = numStack[numStack.length - 1].pop();\n\t\t\t\tconst op = opStack.pop();\n\t\t\t\tnumStack[numStack.length - 1].push(calculate(a, +number, op));\n\t\t\t}\n\n\t\t\tnumber = '';\n\t\t}\n\n\t\tif (char === '(') {\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(0);\n\t\t\t\topStack.push('+');\n\t\t\t}\n\n\t\t\tnumStack.push([]); // Start a new stack for this parenthesis\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === ')') {\n\t\t\tconst b = numStack.pop().pop();\n\t\t\tconst a = numStack[numStack.length - 1].pop();\n\t\t\tconst op = opStack.pop();\n\t\t\tnumStack[numStack.length - 1].push(calculate(a, b, op));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '+' || char === '-') {\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(0);\n\t\t\t}\n\n\t\t\topStack.push(char);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\t// We should never reach here\n\t\tthrow new Error('Unexpected input: ' + char);\n\t}\n\n\tif(number){\n\t\tif (numStack[numStack.length - 1].length === 0) return +number;\n\n\t\tconst a = numStack[numStack.length - 1].pop();\n\t\tconst op = opStack.pop();\n\t\tnumStack[0].push(calculate(a, +number, op));\n\t}\n\n\treturn numStack.pop().pop();\n};",
        "solution_java": "class Solution {\n    int idx; // this index traverse the string in one pass, between different level of recursion\n    public int calculate(String s) {\n        idx = 0; // Initialization should be here\n        return helper(s);\n    }\n    \n    private int helper(String s) {\n        int res = 0, num = 0, preSign = 1, n = s.length();\n        while (idx < n) {\n            char c = s.charAt(idx++);\n            if (c == '(') num = helper(s); // Let recursion solve the sub-problem\n            else if (c >= '0' && c <= '9') num = num * 10 + c - '0';\n            if (c == '+' || c == '-' || c == ')' || idx == n) { // we need one more calculation when idx == n\n                res += preSign * num;\n                if (c == ')') return res; // end of a sub-problem\n                num = 0;\n                preSign = c == '+' ? 1 : -1;\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n   int calculate(string s) {\n       stack<pair<int,int>> st; // pair(prev_calc_value , sign before next bracket () )\n       \n       long long int sum = 0;\n       int sign = +1;\n       \n       for(int i = 0 ; i < s.size() ; ++i)\n       {\n           char ch = s[i];\n           \n           if(isdigit(ch))\n           {\n               long long int num = 0;\n               while(i < s.size() and isdigit(s[i]))\n               {\n                   num = (num * 10) + s[i] - '0';\n                   i++;\n               }\n               i--; // as for loop also increase i , so if we don't decrease i here a sign will be skipped\n               sum += (num * sign);\n               sign = +1; // reseting sign\n           }\n           else if(ch == '(')\n           {\n               // Saving current state of (sum , sign) in stack\n               st.push(make_pair(sum , sign));\n               \n               // Reseting sum and sign for inner bracket calculation\n               sum = 0; \n               sign = +1;\n           }\n           else if(ch == ')')\n           {\n               sum = st.top().first + (st.top().second * sum);\n               st.pop();\n           }\n           else if(ch == '-')\n           {\n               // toggle sign\n               sign = (-1 * sign);\n           }\n       }\n       return sum;\n   }\n};"
    },
    {
        "title": "Evaluate Division",
        "algo_input": "You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.\n\nYou are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.\n\nReturn the answers to all queries. If a single answer cannot be determined, return -1.0.\n\nNote: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.\n\n&nbsp;\nExample 1:\n\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput: [6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation: \nGiven: a / b = 2.0, b / c = 3.0\nqueries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?\nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\n\n\nExample 2:\n\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput: [3.75000,0.40000,5.00000,0.20000]\n\n\nExample 3:\n\nInput: equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput: [0.50000,2.00000,-1.00000,-1.00000]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= equations.length &lt;= 20\n\tequations[i].length == 2\n\t1 &lt;= Ai.length, Bi.length &lt;= 5\n\tvalues.length == equations.length\n\t0.0 &lt; values[i] &lt;= 20.0\n\t1 &lt;= queries.length &lt;= 20\n\tqueries[i].length == 2\n\t1 &lt;= Cj.length, Dj.length &lt;= 5\n\tAi, Bi, Cj, Dj consist of lower case English letters and digits.\n\n",
        "solution_py": "class Solution:\n    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n        graph = dict()\n        \n        for (n, d), v in zip(equations, values):\n            if n not in graph:\n                graph[n] = []\n            if d not in graph:\n                graph[d] = []\n                \n            graph[n].append((d, v))\n            graph[d].append((n, 1/v))\n        \n        def dfs(node, target, product, visited):\n            if n not in graph or d not in graph:\n                return -1\n            \n            if node == target:\n                return product\n            \n            visited.add(node)\n            \n            for neighbor, quotient in graph[node]:\n                if neighbor not in visited:\n                    soln = dfs(neighbor, target, product * quotient, visited)\n                    if soln != -1:\n                        return soln\n                    \n            return -1\n        \n        solns = []\n        for n, d in queries:\n            solns.append(dfs(n, d, 1, set()))\n            \n        return solns",
        "solution_js": "var calcEquation = function(equations, values, queries) {\n    const res = []\n    \n    for(let i = 0; i < queries.length; i++) {\n        const currQuery = queries[i]\n        \n        const [currStart, currDestination] = currQuery\n        \n        const adj = {}\n        \n        const additionalEdges = []\n        const additionalValues = []\n        \n        const visited = new Set()\n        \n        equations.forEach((el,idx) => {\n            const [to, from] = el\n            const val = values[idx]\n            \n            additionalEdges.push([from, to])\n            additionalValues.push(1/val)\n        })\n        \n        values = [...values, ...additionalValues]\n        let idx = 0\n        for(const [from, to] of [...equations, ...additionalEdges]) {\n            if(!(from in adj)) adj[from] = []\n            \n            adj[from].push([to, values[idx]])\n            \n            idx++\n        }\n        \n        if(!(currStart in adj) || !(currDestination in adj)) {\n            res.push(-1)\n            continue\n        }\n        \n        if(currStart === currDestination) {\n            res.push(1)\n            continue\n        }\n        \n        \n        let currEvaluation = 1\n        let found = false\n        const subResult = dfs(currStart)\n        if(!found) res.push(-1)\n        \n        \n        \n        function dfs(node) {\n            if(!node) return null\n            if(node === currDestination) {\n                return true\n            }\n            \n            const children = adj[node] // [ [to, val] ]\n            \n            if(!children) return false\n            \n            for(const child of children) {\n                if(visited.has(node)) continue\n                visited.add(node)\n                \n                currEvaluation =  currEvaluation*child[1]\n\n                if(dfs(child[0]) === true) {\n                    !found && res.push(currEvaluation)\n                    found = true\n                   return \n                }\n                visited.delete(node)\n                currEvaluation /= child[1]\n            }\n        }\n        \n        }\n    return res\n};",
        "solution_java": "class Solution {\n    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {\n        int len = equations.size();\n        Map<String, Integer> varMap = new HashMap<>();\n        int varCnt = 0;\n        for (int i = 0; i < len; i++) {\n            if (!varMap.containsKey(equations.get(i).get(0))) {\n                varMap.put(equations.get(i).get(0), varCnt++);\n            }\n            if (!varMap.containsKey(equations.get(i).get(1))) {\n                varMap.put(equations.get(i).get(1), varCnt++);\n            }\n        }\n\n        List<Pair>[] edges = new List[varCnt];\n        for (int i = 0; i < varCnt; i++) {\n            edges[i] = new ArrayList<>();\n        }\n\n        for (int i = 0; i < len; i++) {\n            int va = varMap.get(equations.get(i).get(0));\n            int vb = varMap.get(equations.get(i).get(1));\n            edges[va].add(new Pair(vb, values[i]));\n            edges[vb].add(new Pair(va, 1.0 / values[i]));\n        }\n\n        int queriesCnt = queries.size();\n        double[] ans = new double[queriesCnt];\n        for (int i = 0; i < queriesCnt; i++) {\n            List<String> query = queries.get(i);\n            double result = -1.0;\n            if (varMap.containsKey(query.get(0)) && varMap.containsKey(query.get(1))) {\n                int idxA = varMap.get(query.get(0));\n                int idxB = varMap.get(query.get(1));\n                if (idxA == idxB) {\n                    result = 1.0;\n                } else {\n                    Queue<Integer> points = new LinkedList<>();\n                    points.offer(idxA);\n                    double[] ratios = new double[varCnt];\n                    Arrays.fill(ratios, -1.0);\n                    ratios[idxA] = 1.0;\n                    while (!points.isEmpty() && ratios[idxB] < 0) {\n                        int cur = points.poll();\n                        for (Pair pair : edges[cur]) {\n                            int y = pair.index;\n                            double value = pair.value;\n                            if (ratios[y] < 0) {\n                                ratios[y] = ratios[cur] * value;\n                                points.offer(y);\n                            }\n                        }\n                    }\n\n                    result = ratios[idxB];\n                }\n            }\n\n            ans[i] = result;\n        }\n\n        return ans;\n    }\n\n    class Pair {\n        int index;\n        double value;\n\n        public Pair(int index, double value) {\n            this.index = index;\n            this.value = value;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {\n        map<string, vector<pair<string, double>>> graph;\n\t\tmap<string, double> dist;\n        map<string, bool> visited;\n        for(int i=0;i<equations.size();i++){\n            if(graph.count(equations[i][0])==0){\n                graph[equations[i][0]] = {};\n\t\t\t\tvisited[equations[i][0]] = false;\n                dist[equations[i][0]] = DBL_MAX;\n            }\n            if(graph.count(equations[i][1])==0){\n                graph[equations[i][1]] = {};\n\t\t\t\tdist[equations[i][0]] = DBL_MAX;\n            }\n            graph[equations[i][0]].push_back({equations[i][1], values[i]});\n            if(values[i]!=0)\n                graph[equations[i][1]].push_back({equations[i][0], 1/values[i]});\n            else\n                graph[equations[i][1]].push_back({equations[i][0], -1});\n        }\n        vector<double> result;\n        for(int i=0;i<queries.size();i++){\n            if(graph.count(queries[i][0])==0 || graph.count(queries[i][1])==0){\n                result.push_back(-1);\n                continue;\n            }\n            if(queries[i][0] == queries[i][1]){\n                result.push_back(1);\n                continue;\n            }\n            for(auto j: visited)\n                visited[j.first] = false;\n            priority_queue<pair<double, string>, vector<pair<double, string>>, greater<pair<double, string>>> pq;\n            dist[queries[i][0]] = 1;;\n            pq.push({1, queries[i][0]});\n            bool flag=false;\n            while(!pq.empty()){\n                auto k = pq.top();\n                pq.pop();\n                visited[k.second] = true;\n                if(k.second==queries[i][1]){\n                    flag=true;\n                    result.push_back(dist[k.second]);\n                    break;\n                }\n                for(int j=0;j<graph[k.second].size();j++){\n                    if(!visited[graph[k.second][j].first])\n                    {dist[graph[k.second][j].first] = dist[k.second] * graph[k.second][j].second;\n                    pq.push({dist[graph[k.second][j].first], graph[k.second][j].first});}\n                }\n            }\n            if(!flag)\n                result.push_back(-1);\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Number of Sub-arrays With Odd Sum",
        "algo_input": "Given an array of integers arr, return the number of subarrays with an odd sum.\n\nSince the answer can be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\n\n\nExample 2:\n\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\n\n\nExample 3:\n\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def numOfSubarrays(self, arr: List[int]) -> int:\n        ce, co = 0, 0\n        s = 0\n        for x in arr:\n            if x % 2 == 0:\n                ce += 1\n            else:\n                old_co = co\n                co = ce + 1\n                ce = old_co\n            \n            s += co\n            \n        return s % (10**9+7)",
        "solution_js": "var numOfSubarrays = function(arr) {\n    let mod=1e9+7,sum=0,odds=0,evens=0\n\t//Notice that I do not need to keep track of the prefixSums, I just need the total count of odd and even PrefixSums\n    for(let i=0;i<arr.length;i++){\n        sum+=arr[i]\n        odds+=Number(sum%2==1)\n        evens+=Number(sum%2==0)\n    }\n    return (odds*evens+odds)%mod\n};",
        "solution_java": "//odd-even=odd\n//even-odd=odd\nclass Solution {\n    public int numOfSubarrays(int[] arr) {\n        long ans=0;\n        int even=0;\n        int odd=0;\n        \n        long sum=0;\n        \n        for(int i=0;i<arr.length;i++){\n            sum+=arr[i];\n            \n            if(sum%2==0){\n                ans+=odd;\n                even++;\n            }else{\n                ans+=even+1;\n                odd++;\n            }\n        }\n        \n        return (int)(ans%(1000000007));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = 1e9 + 7;\n    int solve(int ind, int n, vector<int> &arr, int req, vector<vector<int>> &dp) {\n        \n        if(ind == n) return 0;\n        if(dp[ind][req] != -1) return dp[ind][req];\n        if(req == 1) {\n            if(arr[ind] % 2 == 0) {\n                return dp[ind][req] = solve(ind + 1, n, arr, req, dp);\n            }\n            else {\n                return dp[ind][req] = (1 + solve(ind + 1, n, arr, !req, dp)) %mod;\n            }\n        }\n        else {\n            if(arr[ind] % 2 == 0) {\n                return dp[ind][req] = (1 + solve(ind + 1, n, arr, req, dp)) %mod;\n            }\n            else {\n                return  dp[ind][req] = solve(ind + 1, n, arr, !req, dp);\n            }\n        }\n    }\n    int numOfSubarrays(vector<int>& arr) {\n        int n = arr.size();\n        vector<vector<int>> dp(n, vector<int> (2, -1));\n        int count = 0;\n        for(int i = 0; i < n; i++) {\n            count = (count +  solve(i, n, arr, 1, dp))% mod;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Concatenation of Consecutive Binary Numbers",
        "algo_input": "Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 1\nExplanation: \"1\" in binary corresponds to the decimal value 1. \n\n\nExample 2:\n\nInput: n = 3\nOutput: 27\nExplanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.\n\n\nExample 3:\n\nInput: n = 12\nOutput: 505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def concatenatedBinary(self, n: int) -> int:\n        modulo = 10 ** 9 + 7\n        shift = 0 # tracking power of 2\n        res = 0\n        \n        for i in range(1, n+1):\n            if i & (i - 1) == 0: # see if num reaches a greater power of 2\n                shift += 1\n            res = ((res << shift) + i) % modulo # do the simulation\n        \n        return res",
        "solution_js": "var concatenatedBinary = function(n) {\n    let num = 0;\n    \n    for(let i = 1; i <= n; i++) {\n        //OR num *= (1 << i.toString(2).length)\n        num *= (2 ** i.toString(2).length) \n        num += i;\n        num %= (10 ** 9 + 7)\n    }\n    return num;\n};",
        "solution_java": "class Solution {\n    public int concatenatedBinary(int n) {\n        long res = 0;\n        for (int i = 1; i <= n; i++) {\n            res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007;\n        }\n        return (int) res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int numberOfBits(int n) {\n\t\t  return log2(n) + 1;\n    }\n    \n    int concatenatedBinary(int n) {\n        long ans = 0, MOD = 1e9 + 7;\n        \n        for (int i = 1; i <= n; ++i) {\n            int len = numberOfBits(i);\n            ans = ((ans << len) % MOD + i) % MOD;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Valid Parentheses",
        "algo_input": "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n\nAn input string is valid if:\n\n\n\tOpen brackets must be closed by the same type of brackets.\n\tOpen brackets must be closed in the correct order.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"()\"\nOutput: true\n\n\nExample 2:\n\nInput: s = \"()[]{}\"\nOutput: true\n\n\nExample 3:\n\nInput: s = \"(]\"\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of parentheses only '()[]{}'.\n\n",
        "solution_py": "class Solution:\n    def isValid(self, string: str) -> bool:\n         while True:\n            if '()' in string:\n                string = string.replace('()', '')\n            elif '{}' in string:\n                string = string.replace('{}', '')\n            elif '[]' in string:\n                string = string.replace('[]', '')\n\n            else:\n                return not string",
        "solution_js": "var isValid = function(s) {   \n    const stack = [];\n    \n    for (let i = 0 ; i < s.length ; i++) {\n        let c = s.charAt(i);\n        switch(c) {\n            case '(': stack.push(')');\n                break;\n            case '[': stack.push(']');\n                break;\n            case '{': stack.push('}');\n                break;\n            default:\n                if (c !== stack.pop()) {\n                    return false;\n                }\n        }\n    }\n    \n    return stack.length === 0;\n};",
        "solution_java": "class Solution {\n    public boolean isValid(String s) {\n        Stack<Character> stack = new Stack<Character>(); // create an empty stack\n        for (char c : s.toCharArray()) { // loop through each character in the string\n            if (c == '(') // if the character is an opening parenthesis\n                stack.push(')'); // push the corresponding closing parenthesis onto the stack\n            else if (c == '{') // if the character is an opening brace\n                stack.push('}'); // push the corresponding closing brace onto the stack\n            else if (c == '[') // if the character is an opening bracket\n                stack.push(']'); // push the corresponding closing bracket onto the stack\n            else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket\n                // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack\n                // does not match the closing bracket, the string is not valid, so return false\n                return false;\n        }\n        // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n        // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n        return stack.isEmpty();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n// Ref:  balanced parenthesis video from LUV bhaiya YT channel \nunordered_map<char,int>symbols={{'[',-1},{'{',-2},{'(',-3},{']',1},{'}',2},{')',3}};\n    stack<char>st;\n    bool isValid(string s) {\n        for(auto &i:s){\n            if(symbols[i]<0){\n                st.push(i);\n            }\n            else{\n                if(st.empty()) return false;\n                char top=st.top();\n                st.pop();\n                if(symbols[i]+symbols[top]!=0) return false;\n            }\n        }\n    if(st.empty()) return true;\n    return false;\n        \n    }\n};"
    },
    {
        "title": "Top K Frequent Elements",
        "algo_input": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\n&nbsp;\nExample 1:\nInput: nums = [1,1,1,2,2,3], k = 2\nOutput: [1,2]\nExample 2:\nInput: nums = [1], k = 1\nOutput: [1]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\tk is in the range [1, the number of unique elements in the array].\n\tIt is guaranteed that the answer is unique.\n\n\n&nbsp;\nFollow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.\n",
        "solution_py": "class Solution:\n    def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n        return [i[0] for i in Counter(nums).most_common(k)]",
        "solution_js": "var topKFrequent = function(nums, k) {\n  let store = {};\n    for(let i=0;i<nums.length;i++){\n        store[nums[i]] = store[nums[i]]+1||1\n    }\n    //returns an array of keys in sorted order\n    let keyArr = Object.keys(store).sort((a,b)=>store[a]-store[b])\n    let arrLength = keyArr.length;\n    let slicedArr = keyArr.slice(arrLength-k,arrLength)\n    return slicedArr\n};",
        "solution_java": "class Solution {\n\tpublic int[] topKFrequent(int[] nums, int k) {\n\t\tMap<Integer, Integer> map = new HashMap<>();\n\n\t\tfor (int num : nums) {        \n\t\t\tmap.merge(num, 1, Integer::sum);\n\t\t}\n\n\t\treturn map.entrySet()\n\t\t\t.stream()\n\t\t\t.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n\t\t\t.map(Map.Entry::getKey)\n\t\t\t.mapToInt(x -> x)\n\t\t\t.limit(k)\n\t\t\t.toArray();\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> topKFrequent(vector<int>& nums, int k) {\n        unordered_map<int,int> map;\n        for(int num : nums){\n            map[num]++;\n        }\n        \n        vector<int> res;\n        // pair<first, second>: first is frequency,  second is number\n        priority_queue<pair<int,int>> pq; \n        for(auto it = map.begin(); it != map.end(); it++){\n            pq.push(make_pair(it->second, it->first));\n            if(pq.size() > (int)map.size() - k){\n                res.push_back(pq.top().second);\n                pq.pop();\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Number of Operations to Make Network Connected",
        "algo_input": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.\n\nYou are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.\n\nReturn the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput: 1\nExplanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\n\n\nExample 2:\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput: 2\n\n\nExample 3:\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput: -1\nExplanation: There are not enough cables.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= connections.length &lt;= min(n * (n - 1) / 2, 105)\n\tconnections[i].length == 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tThere are no repeated connections.\n\tNo two computers are connected by more than one cable.\n\n",
        "solution_py": "class Solution(object):\n    def __init__(self):\n        self.parents = []\n        self.count = []\n\n    def makeConnected(self, n, connections):\n        \"\"\"\n        :type n: int\n        :type connections: List[List[int]]\n        :rtype: int\n        \"\"\"\n        if len(connections) < n-1:\n            return -1\n        self.parents = [i for i in range(n)]\n        self.count = [1 for _ in range(n)]\n        for connection in connections:\n            a, b = connection[0], connection[1]\n            self.union(a, b)\n        return len({self.find(i) for i in range(n)}) - 1\n\n    def find(self, node):\n        \"\"\"\n        :type node: int\n        :rtype: int\n        \"\"\"\n        while(node != self.parents[node]):\n            node = self.parents[node];\n        return node\n\n    def union(self, a, b):\n        \"\"\"\n        :type a: int\n        :type b: int\n        :rtype: None\n        \"\"\"\n        a_parent, b_parent = self.find(a), self.find(b)\n        a_size, b_size = self.count[a_parent], self.count[b_parent]\n\n        if a_parent != b_parent:\n            if a_size < b_size:\n                self.parents[a_parent] = b_parent\n                self.count[b_parent] += a_size\n            else:\n                self.parents[b_parent] = a_parent\n                self.count[a_parent] += b_size",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} connections\n * @return {number}\n */\nclass UnionFind {\n    constructor(n) {\n        this.root = new Array(n).fill().map((_, index)=>index);\n        this.components = n;\n    }\n    find(x) {\n        if(x == this.root[x]) return x;\n        return this.root[x] = this.find(this.root[x]);\n    }\n    union(x, y) {\n        const rootX = this.find(x);\n        const rootY = this.find(y);\n        if(rootX != rootY) {\n            this.root[rootY] = rootX;\n            this.components--;\n        }\n    }\n}\nvar makeConnected = function(n, connections) {\n    // We need at least n - 1 cables to connect all nodes (like a tree).\n    if(connections.length < n-1) return -1;\n    const uf = new UnionFind(n);\n    for(const [a, b] of connections) {\n        uf.union(a, b);\n    }\n    return uf.components - 1;\n};",
        "solution_java": "class Solution {\n    public int makeConnected(int n, int[][] connections) {\n        int m = connections.length;\n        if(m < n - 1) return -1;\n        UnionFind uf = new UnionFind(n);\n        \n        for(int[] connection: connections){\n            uf.union(connection[0], connection[1]);\n        }\n        return uf.getIsolated();\n    }\n}\nclass UnionFind{\n    int[] root;\n    int[] rank;\n    int isolated;\n    public UnionFind(int n){\n        root = new int[n];\n        rank = new int[n];\n        for(int i = 0; i < n; i++){\n            root[i] = i;\n            rank[i] = 1;\n        }\n        isolated = 0;\n    }\n    public int find(int x){\n        if(root[x] != x) root[x] = find(root[x]);\n        return root[x];\n    }\n    public void union(int x, int y){\n        int rootx = find(x);\n        int rooty = find(y);\n        if(rootx == rooty) return;\n        if(rank[rootx] > rank[rooty]){\n            root[rooty] = rootx;\n        }else if(rank[rootx] < rank[rooty]){\n            root[rootx] = rooty;\n        }else{\n            root[rootx] = rooty;\n            rank[rooty] += 1;\n        }\n    }\n    public int getIsolated(){\n        for(int i = 0; i < root.length; i ++){\n            if(root[i] == i) isolated++;\n        }\n        return isolated - 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n\t// Union Find Approach\n\n\tvector<int> root;\n\n\tint find(int node){\n\t\tif(root[node] != node){\n\t\t\treturn find(root[node]);\n\t\t}\n\t\treturn node;\n\t}\n\n\tint makeConnected(int n, vector<vector<int>>& connections) {\n\n\t\tint m = connections.size();\n\n\t\tif(m < n-1){\n\t\t\treturn -1;\n\t\t}\n\n\t\tfor(int i=0 ; i<n ; i++){\n\t\t\troot.push_back(i);\n\t\t}\n\n\t\tfor(int i=0 ; i<m ; i++){\n\n\t\t\tint v1 = connections[i][0];\n\t\t\tint v2 = connections[i][1];\n\n\t\t\tint r1 = find(v1);\n\t\t\tint r2 = find(v2);\n\n\t\t\tif(r1 != r2){\n\t\t\t\troot[r1] = r2;\n\t\t\t}\n\t\t}\n\n\t\tint ans = 0;\n\t\tfor(int i=0 ; i<n ; i++){\n\t\t\tif(root[i] == i){\n\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\n\t\treturn ans - 1;\n\t}\n};"
    },
    {
        "title": "Can Convert String in K Moves",
        "algo_input": "Given two strings&nbsp;s&nbsp;and&nbsp;t, your goal is to convert&nbsp;s&nbsp;into&nbsp;t&nbsp;in&nbsp;k&nbsp;moves or less.\n\nDuring the&nbsp;ith&nbsp;(1 &lt;= i &lt;= k)&nbsp;move you can:\n\n\n\tChoose any index&nbsp;j&nbsp;(1-indexed) from&nbsp;s, such that&nbsp;1 &lt;= j &lt;= s.length&nbsp;and j&nbsp;has not been chosen in any previous move,&nbsp;and shift the character at that index&nbsp;i&nbsp;times.\n\tDo nothing.\n\n\nShifting a character means replacing it by the next letter in the alphabet&nbsp;(wrapping around so that&nbsp;'z'&nbsp;becomes&nbsp;'a'). Shifting a character by&nbsp;i&nbsp;means applying the shift operations&nbsp;i&nbsp;times.\n\nRemember that any index&nbsp;j&nbsp;can be picked at most once.\n\nReturn&nbsp;true&nbsp;if it's possible to convert&nbsp;s&nbsp;into&nbsp;t&nbsp;in no more than&nbsp;k&nbsp;moves, otherwise return&nbsp;false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"input\", t = \"ouput\", k = 9\nOutput: true\nExplanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.\n\n\nExample 2:\n\nInput: s = \"abc\", t = \"bcd\", k = 10\nOutput: false\nExplanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.\n\n\nExample 3:\n\nInput: s = \"aab\", t = \"bbb\", k = 27\nOutput: true\nExplanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, t.length &lt;= 10^5\n\t0 &lt;= k &lt;= 10^9\n\ts, t contain&nbsp;only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def canConvertString(self, s: str, t: str, k: int) -> bool:\n        if len(s) != len(t):\n            return False\n\n        cycles, extra = divmod(k, 26)\n        shifts = [cycles + (shift <= extra) for shift in range(26)]\n\n        for cs, ct in zip(s, t):\n            shift = (ord(ct) - ord(cs)) % 26\n            if shift == 0:\n                continue\n            if not shifts[shift]:\n                return False\n            shifts[shift] -= 1\n\n        return True",
        "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @param {number} k\n * @return {boolean}\n */\n var canConvertString = function(s, t, k) {\n    let res = true;\n    if(s.length === t.length){\n        let tmp = [];\n        let countMap = new Map();\n        for(let i=0; i<s.length; i++){\n            let n1 = s[i].charCodeAt();\n            let n2 = t[i].charCodeAt();\n            let r = n2 - n1;\n            if(r < 0){\n                r += 26;\n            }\n            // exclude special case 0\n            if(r > 0){\n                // Considering repeated letters, the unrepeated move should change to r + 26*n (n>=0)\n                // use hash table to count the same letter\n                if(!countMap.has(r)){\n                    // first time to move\n                    countMap.set(r, 1);\n                    tmp.push(r);\n                }else{\n                    // n time to move, n means the count of the same letter\n                    let c = countMap.get(r);\n                    tmp.push(r + c * 26);\n                    // update count\n                    countMap.set(r, c+1);\n                }\n            }\n        }\n        // check all possible move in range\n        for(let i=0; i<tmp.length; i++){\n            let t = tmp[i];\n            if(t > k){\n                res = false;\n                break;\n            }\n        }\n    }else{\n        res = false;\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public boolean canConvertString(String s, String t, int k) {\n       //if strings lengths not equal return false\n        if(s.length()!=t.length())return false;\n       //array to count number of times a difference can repeat\n        int b[]=new int[26];\n        int h=k/26;\n        int h1=k%26;\n        //count of each number from 1 to 26 from 1 to k\n        for(int i=0;i<26;i++){\n            b[i]+=h;\n            if(i<=h1)b[i]++;\n        }\n\n       int i=0;\n        while(i<s.length()){\n            //if both characters equal increment i\n            if(s.charAt(i)==t.charAt(i)){\n                i++;\n            }else{\n                //else now find difference\n                //+26 because we dont know it can be negative also and again mod with 26\n                int diff=((t.charAt(i)-s.charAt(i))+26)%26;\n                //decrement count after usage of one value of b[diff]\n                b[diff]--;\n                //if b[diff]<0 means over usage than given so return false\n                if(b[diff]<0) return false;\n                //else finally increment\n                else i++;\n            }\n\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canConvertString(string s, string t, int k) {\n        int m = s.length(), n = t.length(), count = 0;\n        if (m != n) return false;\n        unordered_map<int, int> mp;\n        for (int i = 0; i < m; i++) {\n            if (t[i] == s[i]) continue;\n            int diff = t[i] - s[i] < 0 ? 26 + t[i] - s[i] : t[i] - s[i];\n            if (mp.find(diff) == mp.end()) {\n                count = max(count, diff);\n            } else {\n                count = max(count, (mp[diff] * 26) + diff);\n            }\n            mp[diff]++;\n            if (count > k) return false;\n        }\n        return count <= k;\n    }\n    \n}; "
    },
    {
        "title": "Shifting Letters",
        "algo_input": "You are given a string s of lowercase English letters and an integer array shifts of the same length.\n\nCall the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').\n\n\n\tFor example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.\n\n\nNow for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.\n\nReturn the final string after all such shifts to s are applied.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abc\", shifts = [3,5,9]\nOutput: \"rpl\"\nExplanation: We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.\n\n\nExample 2:\n\nInput: s = \"aaa\", shifts = [1,2,3]\nOutput: \"gfd\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase English letters.\n\tshifts.length == s.length\n\t0 &lt;= shifts[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n        n = len(s)\n        nums = []\n        sums = 0\n        for i in shifts[::-1]:\n            sums = (sums+i)%26\n            nums.append(sums)\n        nums = nums[::-1]\n        \n        res = ''\n        for i, ch in enumerate(s):\n            val = ord(s[i]) + nums[i]\n            while val > 122:\n                val -= 26\n            res += chr(val)\n        \n        return res",
        "solution_js": "// 848. Shifting Letters\nvar shiftingLetters = function(s, shifts) {\n\tlet res = '', i = shifts.length;\n\tshifts.push(0);\n\twhile (--i >= 0) {\n\t\tshifts[i] += shifts[i+1];\n\t\tres = String.fromCharCode((s.charCodeAt(i) - 97 + shifts[i]) % 26 + 97) + res;\n\t}\n\treturn res;\n};",
        "solution_java": "class Solution {\n    public String shiftingLetters(String s, int[] shifts) {\n        char[] arr = s.toCharArray();\n        int[] arr1 = new int[shifts.length];\n        arr1[arr1.length-1] = (shifts[shifts.length-1])%26;\n        for(int i =shifts.length -2 ;i>=0 ;i--){\n            arr1[i] = (shifts[i] + arr1[i+1])%26;\n        }\n        for(int i =0; i<arr.length ; i++ ){\n            int c = (int)(arr[i]);\n            int n = c+arr1[i];\n            if(n>122){\n                    int m = arr1[i] -(122-c);\n                    n = m+96;\n                }\n            char ch = (char)n;\n            arr[i] = ch;\n\n        }\n        String string = new String(arr);\n        return string;\n\n    }\n}",
        "solution_c": "class Solution {\n    void shift(string& s, int times, int amt)\n    {\n        const int clampL = 97;\n        const int clampR = 123;\n        \n        for (int i = 0; i <= times; i++)\n        {\n            int op = (s[i] + amt) % clampR;\n            \n            if (op < clampL)\n                op += clampL;\n            \n            s[i] = op;\n        }\n    }\npublic:\n    string shiftingLetters(string s, vector<int>& shifts) {\n        \n        for (int i = 0; i < shifts.size(); i++)\n            shift(s,i,shifts[i]);\n        \n        return s;\n    }\n};"
    },
    {
        "title": "Range Frequency Queries",
        "algo_input": "Design a data structure to find the frequency of a given value in a given subarray.\n\nThe frequency of a value in a subarray is the number of occurrences of that value in the subarray.\n\nImplement the RangeFreqQuery class:\n\n\n\tRangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.\n\tint query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right].\n\n\nA subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).\n\n&nbsp;\nExample 1:\n\nInput\n[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]\nOutput\n[null, 1, 2]\n\nExplanation\nRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i], value &lt;= 104\n\t0 &lt;= left &lt;= right &lt; arr.length\n\tAt most 105 calls will be made to query\n\n",
        "solution_py": "class RangeFreqQuery:\n    def __init__(self, arr: List[int]):\n        self.l = [[] for _ in range(10001)]\n        for i, v in enumerate(arr):\n            self.l[v].append(i)\n    def query(self, left: int, right: int, v: int) -> int:\n        return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)",
        "solution_js": " var RangeFreqQuery = function(arr) {\n\n    this.array = arr;\n    this.subRangeSize = Math.sqrt(this.array.length) >> 0;\n    this.subRangeFreqs = [];\n\n    let freq = {};\n\n    for(let i = 0; i < arr.length; i++) {\n\n        const num = arr[i];\n    \n        if(i >= this.subRangeSize && i % this.subRangeSize === 0) {\n            this.subRangeFreqs.push({...freq});\n            freq = {};\n        }\n        \n        freq[num] = (freq[num] || 0) + 1;        \n    }\n\n    this.subRangeFreqs.push(freq);\n\n};\n\nRangeFreqQuery.prototype.query = function(left, right, value) {\n\n    let fr = 0;\n\n    const leftIdx = left / this.subRangeSize >> 0, rightIdx = right / this.subRangeSize >> 0;\n\n    for(let i = leftIdx; i <= rightIdx; i++) {\n        fr += this.subRangeFreqs[i][value] || 0;\n    }\n\n    for(let i = leftIdx * this.subRangeSize; i < left; i++) {\n        fr -= this.array[i] === value ? 1 : 0;\n    }\n\n    for(let i = right + 1; i < Math.min((rightIdx + 1) * this.subRangeSize, this.array.length); i++) {\n        fr -= this.array[i] === value ? 1 : 0;\n    }\n    return fr;\n};",
        "solution_java": "class RangeFreqQuery {\n    //Use map's key to store arr's value, map's value to keep <value's location, cummulative arr's value count>\n    HashMap<Integer, TreeMap<Integer, Integer>> map;\n    public RangeFreqQuery(int[] arr) {\n        //O(nlog(n))\n        map = new HashMap<>();\n        for(int i = 0; i < arr.length; i++){\n            map.putIfAbsent(arr[i], new TreeMap<>());\n            TreeMap<Integer, Integer> tree = map.get(arr[i]);\n            //i = value's location\n            //tree.size() = cummulative arr's value count - 1\n            tree.put(i, tree.size());\n        }\n    }\n    \n    public int query(int left, int right, int value) {\n        //O(log(n))\n        \n        //check if value exist in map\n        if(!map.containsKey(value)){\n            return 0;\n        }\n        TreeMap<Integer, Integer> tree = map.get(value);\n        \n        //check if there exist position >= left and position <= right\n        //if not, return 0\n        if(tree.ceilingKey(left) == null || tree.floorKey(right) == null){\n            return 0;\n        }\n        //get leftMost position's cummulative count\n        int leftMost = tree.get(tree.ceilingKey(left));\n        //get rightMost position's cummulative count\n        int rightMost = tree.get(tree.floorKey(right));\n        \n        return rightMost - leftMost + 1;\n    }\n}\n\n/**\n * Your RangeFreqQuery object will be instantiated and called as such:\n * RangeFreqQuery obj = new RangeFreqQuery(arr);\n * int param_1 = obj.query(left,right,value);\n */",
        "solution_c": "class RangeFreqQuery {\nprivate:\n    int size;\n    unordered_map< int, vector<int> > mp;\npublic:\n    RangeFreqQuery(vector<int>& arr) {\n        size=arr.size();\n        for (int i=0; i<size;i++){\n            mp[arr[i]].push_back(i);\n        }\n    }\n    int query(int left, int right, int value) {\n        int first = lower_bound(mp[value].begin(),mp[value].end(),left)- mp[value].begin();\n        int second = upper_bound(mp[value].begin(),mp[value].end(),right)- mp[value].begin();\n        return second-first;\n    }\n};"
    },
    {
        "title": "Unique Paths II",
        "algo_input": "You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time.\n\nAn obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.\n\nReturn the number of possible unique paths that the robot can take to reach the bottom-right corner.\n\nThe testcases are generated so that the answer will be less than or equal to 2 * 109.\n\n&nbsp;\nExample 1:\n\nInput: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\nOutput: 2\nExplanation: There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -&gt; Right -&gt; Down -&gt; Down\n2. Down -&gt; Down -&gt; Right -&gt; Right\n\n\nExample 2:\n\nInput: obstacleGrid = [[0,1],[0,0]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tm == obstacleGrid.length\n\tn == obstacleGrid[i].length\n\t1 &lt;= m, n &lt;= 100\n\tobstacleGrid[i][j] is 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n        def valid(r,c,matrix):\n            return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0])\n\n        dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))]\n        dp[0][0] = 1 ^ obstacleGrid[0][0]\n\n        for r in range(len(obstacleGrid)):\n            for c in range(len(obstacleGrid[0])):\n                if obstacleGrid[r][c] != 1:\n                    if valid(r-1, c, dp) and obstacleGrid[r-1][c] != 1:\n                        dp[r][c] += dp[r-1][c]\n                    if valid(r, c-1, dp) and obstacleGrid[r][c-1] != 1:\n                        dp[r][c] += dp[r][c-1]\n\n        return dp[-1][-1]",
        "solution_js": "var uniquePathsWithObstacles = function(grid) {\n        let m=grid.length, n=grid[0].length;\n        const dp = [...Array(m+1)].map((e) => Array(n+1).fill(0));\n        dp[0][1]=1;\n        for(let i=1;i<m+1;i++){\n            for(let j=1;j<n+1;j++){\n                dp[i][j]=grid[i-1][j-1]==1 ? 0:dp[i][j-1]+dp[i-1][j]; \n            }\n        }\n        return dp[m][n];\n};",
        "solution_java": "class Solution {\n    public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n        int m = obstacleGrid.length, n = obstacleGrid[0].length;\n        int[][] path = new int[m][n];\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n\t\t\t//if there is an obstacle at the current block then you cannot get there\n                if(obstacleGrid[i][j]!=1){\n                    if(i==0 && j==0)\n                        path[i][j] = 1;\n                    if(i>0)\n                        path[i][j] += path[i-1][j];\n                    if(j>0)\n                        path[i][j] += path[i][j-1];\n                }\n            }\n        }\n        return path[--m][--n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[101][101];\n    int paths(int i,int j,int &m, int &n,vector<vector<int>> &grid){\n        if(i>=m || j>=n) return 0;\n        \n        if(grid[i][j] == 1) return 0;\n        \n        if(i== m-1 && j== n-1) return 1;\n        \n        if(dp[i][j] != -1) return dp[i][j];\n        \n        int v = paths(i,j+1,m,n,grid);\n        int h = paths(i+1,j,m,n,grid);\n        \n        return dp[i][j] = v + h;\n    }\n    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n        int m = obstacleGrid.size();\n        int n = obstacleGrid[0].size();\n        \n        memset(dp,-1,sizeof(dp));\n        \n        return paths(0,0,m,n,obstacleGrid);\n    }\n};"
    },
    {
        "title": "Ransom Note",
        "algo_input": "Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.\n\nEach letter in magazine can only be used once in ransomNote.\n\n&nbsp;\nExample 1:\nInput: ransomNote = \"a\", magazine = \"b\"\nOutput: false\nExample 2:\nInput: ransomNote = \"aa\", magazine = \"ab\"\nOutput: false\nExample 3:\nInput: ransomNote = \"aa\", magazine = \"aab\"\nOutput: true\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= ransomNote.length, magazine.length &lt;= 105\n\transomNote and magazine consist of lowercase English letters.\n\n",
        "solution_py": "from collections import Counter\nclass Solution:\n    def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n         \n        ransomNote_count = dict(Counter(ransomNote))\n        magazine_count = dict(Counter(magazine))\n        \n        for key , value in ransomNote_count.items():\n            \n            if key in magazine_count:\n                if value <= magazine_count[key]:\n                    continue\n            else:\n                return False\n            \n            return False\n        \n        return True",
        "solution_js": "var canConstruct = function(ransomNote, magazine) {\n    map = {};\n    for(let i of magazine){\n        map[i] = (map[i] || 0) + 1;\n    }\n    for(let i of ransomNote){\n        if(!map[i]){\n            return false\n        }\n        map[i]--;\n    }\n    return true\n};",
        "solution_java": "class Solution {\n    public boolean canConstruct(String ransomNote, String magazine) {\n        char[] rs = ransomNote.toCharArray();\n        char[] ms = magazine.toCharArray();\n        \n        HashMap<Character, Integer> rm = new HashMap<>();\n        HashMap<Character, Integer> mz = new HashMap<>();\n        \n        for (char c : rs) {\n            if (rm.containsKey(c)) {\n                rm.put(c, rm.get(c) + 1);\n            } else {\n                rm.put(c, 1);\n            }\n        }\n\n        for (char c : ms) {\n            if (mz.containsKey(c)) {\n                mz.put(c, mz.get(c) + 1);\n            } else {\n                mz.put(c, 1);\n            }\n        }\n\n        for (char c : rm.keySet()) {\n            if (!mz.containsKey(c) || mz.get(c) < rm.get(c)) {\n                return false;\n            }\n        }\n        return true;  \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canConstruct(string ransomNote, string magazine) {\n        int cnt[26] = {0};\n        for(char x: magazine)\n            cnt[x-'a']++;\n        \n        for(char x: ransomNote) {\n            if(cnt[x-'a'] == 0)\n                return false;\n            cnt[x-'a']--;\n        }\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Redistribute Characters to Make All Strings Equal",
        "algo_input": "You are given an array of strings words (0-indexed).\n\nIn one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].\n\nReturn true if you can make every string in words equal using any number of operations, and false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abc\",\"aabc\",\"bc\"]\nOutput: true\nExplanation: Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so return true.\n\n\nExample 2:\n\nInput: words = [\"ab\",\"a\"]\nOutput: false\nExplanation: It is impossible to make all the strings equal using the operation.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 100\n\twords[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def makeEqual(self, words: List[str]) -> bool:\n        map_ = {}\n        for word in words:\n            for i in word:\n                if i not in map_:\n                    map_[i] = 1\n                else:\n                    map_[i] += 1\n        n = len(words)\n        for k,v in map_.items():\n            if (v%n) != 0:\n                return False\n        return True",
        "solution_js": "/**\n * @param {string[]} words\n * @return {boolean}\n */\nvar makeEqual = function(words) {\n\n    let length = words.length\n\n    let map = {}\n    for( let word of words ) {\n        for( let ch of word ) {\n            map[ch] = ( map[ch] || 0 ) + 1\n        }\n    }\n\n    for( let key of Object.keys(map)) {\n        if( map[key] % length !=0 ) return false\n    }\n\n    return true\n\n};",
        "solution_java": "class Solution {\n    public boolean makeEqual(String[] words) {\n        \n        HashMap<Character, Integer> map = new HashMap<>();\n        \n        for(String str : words){\n            \n            for(int i=0; i<str.length(); i++){\n                char ch = str.charAt(i);\n                \n                map.put(ch, map.getOrDefault(ch, 0) + 1);\n            }\n            \n        }\n        \n        for(Character key : map.keySet()){\n            \n            int freq = map.get(key);\n            if(freq % words.length!=0){\n                return false;\n            }\n        }\n        \n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool makeEqual(vector<string>& words) {\n        int mp[26] = {0};\n        for(auto &word: words){\n            for(auto &c: word){\n                mp[c - 'a']++;\n            }\n        }\n        \n        for(int i = 0;i<26;i++){\n            if(mp[i] % words.size() != 0) return false;\n        }\n        return true;      \n    }\n};"
    },
    {
        "title": "Lexicographically Smallest String After Applying Operations",
        "algo_input": "You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\n\nYou can apply either of the following two operations any number of times and in any order on s:\n\n\n\tAdd a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = \"3456\" and a = 5, s becomes \"3951\".\n\tRotate s to the right by b positions. For example, if s = \"3456\" and b = 1, s becomes \"6345\".\n\n\nReturn the lexicographically smallest string you can obtain by applying the above operations any number of times on s.\n\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9'.\n\n&nbsp;\nExample 1:\n\nInput: s = \"5525\", a = 9, b = 2\nOutput: \"2050\"\nExplanation: We can apply the following operations:\nStart:  \"5525\"\nRotate: \"2555\"\nAdd:    \"2454\"\nAdd:    \"2353\"\nRotate: \"5323\"\nAdd:    \"5222\"\nAdd:    \"5121\"\nRotate: \"2151\"\n​​​​​​​Add:    \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".\n\n\nExample 2:\n\nInput: s = \"74\", a = 5, b = 1\nOutput: \"24\"\nExplanation: We can apply the following operations:\nStart:  \"74\"\nRotate: \"47\"\n​​​​​​​Add:    \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".\n\n\nExample 3:\n\nInput: s = \"0011\", a = 4, b = 2\nOutput: \"0011\"\nExplanation: There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 100\n\ts.length is even.\n\ts consists of digits from 0 to 9 only.\n\t1 &lt;= a &lt;= 9\n\t1 &lt;= b &lt;= s.length - 1\n\n",
        "solution_py": "'''\nw: BFS\nh: for each possible number (node), we have two possible operations (add, rotate)\n    it seems to be a 2^100 possible number, however, note:\n    1) add a to number of odd index, we will get to the same number after 10 rounds of add\n    2) s has even length, if b is odd, we can get the same number after n round\n    3) for each shift, we would get different number at even index in 10 rounds\n    \n    so we would have 10 * n * 10 number at most, then we can use BFS + memo\n'''\nimport collections\n\nclass Solution:\n    def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n        seen = set()\n        deque = collections.deque([s])\n\n        while deque:\n            #print(deque)\n            curr = deque.popleft()\n            seen.add(curr)\n            \n            #1.add\n            ad = self.add_(curr, a)\n            if ad not in seen:\n                deque.append(ad)\n                seen.add(ad)\n\n            \n            #2. rotate:\n            ro = self.rotate_(curr, b)\n            if ro not in seen:\n                deque.append(ro)\n                seen.add(ro)\n\n        return min(seen)\n        \n        \n    def add_(self,s,a):\n        res = ''\n        for idx, i in enumerate(s):\n            if idx % 2 == 1:\n                num = (int(i) + a) % 10\n                res += str(num)\n            else:\n                res += i\n                \n        return res\n    \n    \n    def rotate_(self, s, b):\n        idx = len(s)-b\n        res = s[idx:] + s[0:idx]\n        return res",
        "solution_js": "var findLexSmallestString = function(s, a, b) {\n    const n = s.length;\n    const visited = new Set();\n    const queue = [];\n\n    visited.add(s);\n    queue.push(s);\n\n    let minNum = s;\n\n    while (queue.length > 0) {\n        const currNum = queue.shift();\n\n        if (currNum < minNum) minNum = currNum;\n\n        const justRotate = rotate(currNum);\n        const justAdd = add(currNum);\n\n        if (!visited.has(justRotate)) {\n            visited.add(justRotate);\n            queue.push(justRotate);\n        }\n\n        if (!visited.has(justAdd)) {\n            visited.add(justAdd);\n            queue.push(justAdd);\n        }\n    }\n\n    return minNum;\n\n    function rotate(num) {\n        let rotatedNum = \"\";\n        const start = n - b;\n\n        for (let i = 0; i < b; i++) {\n            rotatedNum += num.charAt(start + i);\n        }\n\n        const restDigs = num.substring(0, n - b);\n        rotatedNum += restDigs;\n\n        return rotatedNum;\n    }\n\n    function add(num) {\n        let nextNum = \"\";\n\n        for (let i = 0; i < n; i++) {\n            let currDig = num.charAt(i);\n\n            if (i % 2 == 0) {\n                nextNum += currDig;\n            }\n            else {\n                let newDig = (parseInt(currDig) + a) % 10;\n                nextNum += newDig;\n            }\n        }\n\n        return nextNum;\n    }\n};",
        "solution_java": "class Solution {\n    private String result;\n    public String findLexSmallestString(String s, int a, int b) {\n        result = \"z\";\n        HashSet<String> set = new HashSet<>();\n        dfs(s, a, b, set);\n        return result;\n    }\n    private void dfs(String s, int a, int b, HashSet<String> set) {\n        if(set.contains(s))\n            return;\n        set.add(s);\n        String s1, s2;\n        s1 = addA(s, a);\n        s2 = rotateB(s, b);\n        dfs(s1, a , b, set);\n        dfs(s2, a , b, set);\n    }\n    private String addA(String s, int a) {\n        char c[] = s.toCharArray();\n        int i, temp;\n        for(i=1;i<s.length();i+=2) {\n            temp = c[i] - '0';\n            temp += a;\n            temp = temp % 10;\n            c[i] = (char)(temp + '0');\n        } \n        s = new String(c);\n        if(result.compareTo(s) > 0)\n            result = s;\n        return s;\n    }\n    private String rotateB(String s, int b) {\n        if(b < 0)\n            b += s.length();\n        b = b % s.length();\n        b = s.length() - b;\n        s = s.substring(b) + s.substring(0, b);\n        if(result.compareTo(s) > 0)\n            result = s;\n        return s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void dfs(string &s, string &small, int a, int b, unordered_map<string, string> &memo) {\n        if (memo.count(s)) return;\n        string res = s, str = res;\n        memo[s] = res;\n        rotate(str.begin(), str.begin() + b, str.end()); // rotate current string\n        dfs(str, small, a, b, memo);\n        if (memo[str] < res) res = memo[str];\n        \n        for (int i = 0; i < 9; i++) { // or add it\n            for (int j = 1; j < s.length(); j+=2)\n                s[j] = '0' + ((s[j] - '0') + a) % 10;\n            if (s < res) res = s;\n            dfs(s, small, a, b, memo);\n        }\n        if (small > res) small = res;\n        memo[s] = res;\n    }\n    string findLexSmallestString(string s, int a, int b) {\n        unordered_map<string, string> memo;\n        string res = s;\n        dfs(s, res, a, b, memo);\n        return  res;\n    }\n};"
    },
    {
        "title": "Next Greater Element I",
        "algo_input": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.\n\nYou are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.\n\nFor each 0 &lt;= i &lt; nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.\n\nReturn an array ans of length nums1.length such that ans[i] is the next greater element as described above.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput: [-1,3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n\n\nExample 2:\n\nInput: nums1 = [2,4], nums2 = [1,2,3,4]\nOutput: [3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length &lt;= nums2.length &lt;= 1000\n\t0 &lt;= nums1[i], nums2[i] &lt;= 104\n\tAll integers in nums1 and nums2 are unique.\n\tAll the integers of nums1 also appear in nums2.\n\n\n&nbsp;\nFollow up: Could you find an O(nums1.length + nums2.length) solution?",
        "solution_py": "class Solution:\n    def nextGreaterElement(self, nums1, nums2):\n        dic, stack = {}, []\n        \n        for num in nums2[::-1]:\n            while stack and num > stack[-1]:\n                stack.pop()\n            if stack:\n                dic[num] = stack[-1]\n            stack.append(num)\n            \n        return [dic.get(num, -1) for num in nums1]",
        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\nvar nextGreaterElement = function(nums1, nums2) {\n    // [Value, Index] of all numbers in nums2\n    const indexMap = new Map()\n    for(let i = 0; i < nums2.length; i++){\n        indexMap.set(nums2[i], i)\n    }\n\n    // Stores the next greatest elements\n    let result = []\n\n    // Iterate through all the numbers of interest. Remember that all numbers in nums1 are present in nums2.\n    for(let num of nums1){\n\n        // Check to see those numbers were present in the nums2 indexMap\n        if(indexMap.has(num)){\n\n            // If they were, we must find the next greatest element.\n            // Set it to -1 by default in case we cannot find it.\n            let nextGreatest = -1\n\n            // Iterate through all numbers in nums2 to the right of the index of the target number. (index of the target + 1)\n            for(let i = indexMap.get(num) + 1; i < nums2.length; i++){\n                // Check to see if the current number is greater than the target.\n                if(nums2[i] > num){\n                    // If it is, this is the next greatest element.\n                    nextGreatest = nums2[i]\n                    // Break the loop.\n                    break;\n                }\n            }\n            // Add the next greatest element (if found). Otherwise, add -1 (default)\n            result.push(nextGreatest)\n        }\n    }\n\n    // Return the array of next greatest elements.\n    return result\n};",
        "solution_java": "class Solution {\n    public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n       HashMap<Integer, Integer> map = new HashMap<>();\n       Stack<Integer> stack = new Stack<>();\n        int[] ans = new int[nums1.length];\n        for(int i = 0; i < nums2.length; i++){\n            while(!stack.isEmpty() && nums2[i] > stack.peek()){\n                int temp = stack.pop();\n                map.put(temp, nums2[i]);\n            }\n            stack.push(nums2[i]);\n        }\n        for(int i = 0; i < nums1.length; i++){\n           ans[i] = map.getOrDefault(nums1[i], -1);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {\n        vector<int>vc;\n        int len1=nums1.size();\n        int len2=nums2.size();\n        unordered_map<int,int>ump;\n        int e,f;\n        for(e=0;e<len2;e++)\n        {\n            for(f=e+1;f<len2;f++)\n            {\n                if(nums2[f]>nums2[e])\n                {\n                    ump[nums2[e]]=nums2[f];\n                    break;\n                }\n\n            }\n            if(f==len2) ump[nums2[e]]=-1;\n\n        }\n        unordered_map<int,int>::iterator it;\n        for(int e=0;e<len1;e++)\n        {\n            it=ump.find(nums1[e]);\n            if(it!=ump.end())\n            {\n                vc.push_back(it->second);\n            }\n        }\n\n        return vc;\n\n    }\n};"
    },
    {
        "title": "All Elements in Two Binary Search Trees",
        "algo_input": "Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.\n\n&nbsp;\nExample 1:\n\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\n\n\nExample 2:\n\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in each tree is in the range [0, 5000].\n\t-105 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n        \n        \n        l1,l2=[],[]\n        def preorder(root,l):\n            if root is None:\n                return \n            preorder(root.left,l)\n            l.append(root.val)\n            preorder(root.right,l)\n        preorder(root1,l1)\n        preorder(root2,l2)\n        return sorted(l1+l2)",
        "solution_js": "var getAllElements = function(root1, root2) {\n    const ans = [];\n    const traverse = (r) => {\n        if(!r) return;\n        traverse(r.left);\n        ans.push(r.val);\n        traverse(r.right);\n    }\n    traverse(root1);\n    traverse(root2);\n    return ans.sort((a, b) => a - b);\n};",
        "solution_java": "class Solution {\n    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {\n        Stack<TreeNode> st1 = new Stack<>();\n        Stack<TreeNode> st2 = new Stack<>();\n        \n        List<Integer> res = new ArrayList<>();\n        \n        while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){\n            while(root1 != null){\n                st1.push(root1);\n                root1 = root1.left;\n            }\n            while(root2 != null){\n                st2.push(root2);\n                root2 = root2.left;\n            }\n            if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){\n                root1 = st1.pop();\n                res.add(root1.val);\n                root1 = root1.right;\n            }\n            else{\n                root2 = st2.pop();\n                res.add(root2.val);\n                root2 = root2.right;\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> v;\n    void Temp(TreeNode* root)\n    {\n        if(root!=NULL){\n        Temp(root->left);\n        v.push_back(root->val);\n        Temp(root->right);\n        }\n    }\n    vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {\n        Temp(root1);\n        Temp(root2);\n        sort(v.begin(), v.end());\n\n        return v;\n    }\n};"
    },
    {
        "title": "Zigzag Conversion",
        "algo_input": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n\nP   A   H   N\nA P L S I I G\nY   I   R\n\n\nAnd then read line by line: \"PAHNAPLSIIGYIR\"\n\nWrite the code that will take a string and make this conversion given a number of rows:\n\nstring convert(string s, int numRows);\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"PAYPALISHIRING\", numRows = 3\nOutput: \"PAHNAPLSIIGYIR\"\n\n\nExample 2:\n\nInput: s = \"PAYPALISHIRING\", numRows = 4\nOutput: \"PINALSIGYAHRPI\"\nExplanation:\nP     I    N\nA   L S  I G\nY A   H R\nP     I\n\n\nExample 3:\n\nInput: s = \"A\", numRows = 1\nOutput: \"A\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of English letters (lower-case and upper-case), ',' and '.'.\n\t1 &lt;= numRows &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def convert(self, s: str, numRows: int) -> str:\n\n        # safety check to not process single row\n        if numRows == 1:\n            return s\n\n        # safety check to not process strings shorter/equal than numRows\n        if len(s) <= numRows:\n            return s\n\n        # safety check to not process double rows\n        if numRows == 2:\n            # slice every other character\n            return s[0::2] + s[1::2]\n\n        # list that stores the lines\n        # add lines with initial letters\n        lines: list[str] = [letter for letter in s[:numRows]]\n\n        # positive direction goes down\n        # lines are created, so it's going up\n        direction: int = -1\n\n        # track the position at which the letter will be added\n        # position after bouncing off, after adding initial lines\n        line_index: int = numRows - 2\n\n        # edge indexes\n        # 0 can only be reached by going up\n        # numRows only by going down\n        edges: set[int] = {0, numRows}\n\n        for letter in s[numRows:]:\n            # add letter at tracked index position\n            lines[line_index] += letter\n\n            # prepare index before next loop iteration\n            line_index += direction\n\n            # reaching one of the edges\n            if line_index in edges:\n                # change direction\n                direction = -direction\n                # bounce off if bottom edge\n                if line_index == numRows:\n                    line_index += direction * 2\n\n        return \"\".join(lines)",
        "solution_js": "var convert = function(s, numRows) {\n  let result = [];\n  let row = 0;\n  let goingUp = false;\n  for (let i = 0; i < s.length; i++) {\n    result[row] = (result[row] || '') + s[i]; // append letter to active row\n    if (goingUp) {\n      row--;\n      if (row === 0) goingUp = false; // reverse direction if goingUp and reaching top\n    } else {\n      row++;\n      if (row === numRows - 1) goingUp = true; // reverse direction after reaching bottom\n    }\n\n  }\n  return result.join('');\n};",
        "solution_java": "class Solution {\n    public String convert(String s, int numRows) {\n        if (numRows==1)return s;\n        StringBuilder builder = new StringBuilder();\n        for (int i=1;i<=numRows;i++){\n            int ind = i-1;\n            boolean up = true;\n            while (ind < s.length()){\n                builder.append(s.charAt(ind));\n                if (i==1){\n                    ind += 2*(numRows-i);\n                } else if (i==numRows){\n                    ind += 2*(i-1);\n                } else {\n                    ind += up ? 2*(numRows-i) : 2*(i-1);\n                    up=!up;\n                }\n            }\n        }\n        return builder.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string convert(string s, int numRows) {\n        vector<vector<char>> v(numRows);\n        int j=0,t=1;\n        if(numRows ==1)\n            return s;\n        for(int i=0;i<s.size();i++)\n        {\n            v[j].push_back((char)s[i]);\n            if(j==numRows-1 )\n                t=0;\n            else if(j==0)\n                t=1;\n            if(t)\n                j++;\n            else\n                j--;\n            \n        }\n        string x=\"\";\n        for(int i=0;i<numRows;i++)\n        {\n            for(int j=0;j<v[i].size();j++)\n                x.push_back(v[i][j]);\n        }\n        return x;\n    }\n};"
    },
    {
        "title": "Closest Subsequence Sum",
        "algo_input": "You are given an integer array nums and an integer goal.\n\nYou want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).\n\nReturn the minimum possible value of abs(sum - goal).\n\nNote that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,-7,3,5], goal = 6\nOutput: 0\nExplanation: Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.\n\n\nExample 2:\n\nInput: nums = [7,-9,15,-2], goal = -5\nOutput: 1\nExplanation: Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n\n\nExample 3:\n\nInput: nums = [1,2,3], goal = -7\nOutput: 7\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 40\n\t-107 &lt;= nums[i] &lt;= 107\n\t-109 &lt;= goal &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def minAbsDifference(self, nums: List[int], goal: int) -> int:\n\n        # When goal 0 we can just choose no elements \n        if goal == 0: return 0\n\n        n = len(nums)\n        mid = n // 2\n        # Split the list in 2 parts and then find all possible subset sums \n        # T = O(2^n/2) to build all subset sums\n        leftList = nums[:mid]\n        leftSums = []\n        rightList = nums[mid:]\n        rightSums = []\n\n        # T = O(2^n/2) to build all subset sums (we only consider half list)\n        def buildSubsetSums(usedNums, numsToChooseFrom, ind, storeIn):\n            if ind == len(numsToChooseFrom):\n                # We also keep elements with sum 0 to deal with cases like this where we don't select nums\n                # List: [1,2,3], Target: -7 (choosing no elements will give a sum close to goal)\n                # We can also have cases where we want to take only 1 element from the list\n                # so sum 0 for left and right list needs to be an option\n                storeIn.append(sum(usedNums))\n                return \n\n            usedNums.append(numsToChooseFrom[ind])\n            buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n            usedNums.pop()\n            buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n\n\n        buildSubsetSums([], leftList, 0, leftSums)\n        buildSubsetSums([], rightList, 0, rightSums)\n        # 2^n/2 log(2^n/2) = n/2 * 2^n/2 time to sort\n        rightSums.sort()\n\n        diff = float('inf')\n\n        # Loop runs 2^n/2 times and inside binary search tale n/2 time \n        # So total time is n/2 * 2^n/2\n        for leftSum in leftSums:\n            complement = goal - leftSum\n            # Bisect left takes log(2^n/2) = n/2 search time\n            idx = bisect.bisect_left(rightSums, complement)\n\n            for i in [idx - 1, idx, idx + 1]:\n                if 0 <= i < len(rightSums):\n                    finalSum = leftSum + rightSums[i]\n                    diff = min(diff, abs(goal - finalSum))\n        \n        # Over all time complexity is - n/2 * 2^n/2\n        # 1. Making subset sums will take - 2^n/2\n        # 2. Sorting right list takes - 2^n/2 * n/2\n        # 3. Iterating one list and finding closest complement in other \n        # takes n/2 * 2^n/2\n        # Space will be O(n/2) for the list and call stack for building subset \n        return diff",
        "solution_js": "var minAbsDifference = function(nums, goal) {\n    let mid = Math.floor(nums.length / 2);\n    let part1 = nums.slice(0, mid), part2 = nums.slice(mid);\n\n    function findSubsetSums(arr, set, idx = 0, sum = 0) {\n        if (idx === arr.length) return set.add(sum);\n        findSubsetSums(arr, set, idx + 1, sum);\n        findSubsetSums(arr, set, idx + 1, sum + arr[idx]);\n    }\n\n    let sum1 = new Set(), sum2 = new Set();\n    findSubsetSums(part1, sum1);\n    findSubsetSums(part2, sum2);\n\n    sum1 = [...sum1.values()];\n    sum2 = [...sum2.values()];\n    sum2.sort((a, b) => a - b);\n\n    let min = Infinity;\n    for (let num1 of sum1) {\n        let l = 0, r = sum2.length - 1;\n        while (l <= r) {\n            let mid = l + Math.floor((r - l) / 2);\n            let num2 = sum2[mid];\n            min = Math.min(min, Math.abs(num1 + num2 - goal));\n            if (num1 + num2 < goal) l = mid + 1;\n            else r = mid - 1;\n        }\n    }\n    return min;\n};",
        "solution_java": "class Solution {\n    int[] arr;\n    public int minAbsDifference(int[] nums, int goal) {\n        arr = nums;\n        int n = nums.length;\n        \n        \n        List<Integer> first = new ArrayList<>();\n        List<Integer> second = new ArrayList<>();\n        \n        generate(0,n/2,0, first); //generate all possible subset sums from half the array\n        generate(n/2, n , 0, second);//generate all possible subset sums from the second half of the array\n        \n        \n        Collections.sort(first);\n        int ans = Integer.MAX_VALUE;\n        \n        \n        for(int secondSetSum : second ) {\n            int left = goal - secondSetSum; // How far off are we from the desired goal?\n            \n            if(first.get(0) > left) { // all subset sums from first half are too big => Choose the smallest\n                ans = (int)(Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal)));\n                continue;\n            }\n            if(first.get(first.size() - 1) < left) { // all subset sums from first half are too small => Choose the largest\n                ans = (int)(Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal)));\n                continue;\n            }\n            int pos = Collections.binarySearch(first, left);\n            if(pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal\n                return 0;\n            else        // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1)\n                pos = -1 * (pos + 1);\n            int low = pos - 1;\n            ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(low) - goal)); // Checking for the floor value (largest sum < goal)\n            ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(pos) - goal)); //Checking for the ceiling value (smallest sum > goal)\n        }\n        return ans;\n    }\n\n    /**\n    * Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick \n    */\n    void generate(int i, int end, int sum, List<Integer> listOfSubsetSums) {\n        if (i == end) {\n            listOfSubsetSums.add(sum); //add\n            return;\n        }\n        generate(i + 1, end, sum + arr[i], set);\n        generate(i + 1, end, sum, set);\n        \n    }\n    \n    \n    \n}",
        "solution_c": "class Solution {\npublic:\n    void find(vector<int>&v, int i, int e, int sum, vector<int>&sumv){\n        if(i==e){\n            sumv.push_back(sum);\n            return;\n        }\n        find(v,i+1,e,sum+v[i],sumv);\n        find(v,i+1,e,sum,sumv);\n    }\n\n    int minAbsDifference(vector<int>& nums, int goal) {\n        int n=nums.size();\n\n        //Step 1: Divide nums into 2 subarrays of size n/2 and n-n/2\n\n        vector<int>A,B;\n        for(int i=0;i<n/2;i++)\n            A.push_back(nums[i]);\n        for(int i=n/2;i<n;i++)\n            B.push_back(nums[i]);\n\n        //Step 2: Find all possible subset sums of A and B\n\n        vector<int>sumA,sumB;\n        find(A,0,A.size(),0,sumA);\n        find(B,0,B.size(),0,sumB);\n\n        sort(sumA.begin(),sumA.end());\n        sort(sumB.begin(),sumB.end());\n\n        //Step 3: Find combinations from sumA & sumB such that abs(sum-goal) is minimized\n\n        int ans=INT_MAX;\n\n        for(int i=0;i<sumA.size();i++){\n            int s=sumA[i];\n            int l=0;\n            int r=sumB.size()-1;\n            while(l<=r){\n                int mid=l+(r-l)/2;\n                int sum=s+sumB[mid];\n                if(sum==goal)\n                    return 0;\n                ans=min(ans,abs(sum-goal));\n                if(sum>goal){\n                    r=mid-1;\n                }\n                else{\n                    l=mid+1;\n                }\n            }\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Find Words That Can Be Formed by Characters",
        "algo_input": "You are given an array of strings words and a string chars.\n\nA string is good if it can be formed by characters from chars (each character can only be used once).\n\nReturn the sum of lengths of all good strings in words.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n\n\nExample 2:\n\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length, chars.length &lt;= 100\n\twords[i] and chars consist of lowercase English letters.\n\n",
        "solution_py": "class Solution(object):\n    def countCharacters(self, words, chars):\n        \"\"\"\n        :type words: List[str]\n        :type chars: str\n        :rtype: int\n        \"\"\"\n        b = set(chars)\n        anwser = 0\n        for i in words:\n            a = set(i)\n            if a.issubset(b):\n                test = [o for o in a if chars.count(o) < i.count(o)]\n                if len(test) == 0:    \n                    anwser += len(i)\n        return anwser",
        "solution_js": "var countCharacters = function(words, chars) {\n    let arr = [];\n    loop1: for(word of words){\n        let characters = chars;\n        loop2: for( char of word ){\n            if(characters.indexOf(char) === -1){\n                continue loop1;\n            }\n            characters = characters.replace(char,'');\n        }\n        arr.push(word);\n    }\n    return arr.join('').length;\n};",
        "solution_java": "class Solution {\n    public int countCharacters(String[] words, String chars) {\n        int[] freq = new int[26];\n        for (int i = 0; i < chars.length(); i++) {\n            // char - char is a kind of clever way to get the position of\n            // the character in the alphabet. 'a' - 'a' would give you 0.\n            // 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.\n            freq[chars.charAt(i) - 'a'] ++;\n        }\n\n        int result = 0;\n        for (String word : words) {\n            int[] copy = Arrays.copyOf(freq, freq.length);\n            boolean pass = true;\n            for (int j = 0; j < word.length(); j++) {\n                // decrement the frequency of this char in array for using\n                // if there are less than 1 chance for using this character, invalid,\n                // move to next word in words\n                if (-- copy[word.charAt(j) - 'a'] < 0) {\n                    pass = false;\n                    break;\n                }\n            }\n            if (pass) {\n                result += word.length();\n            }\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countCharacters(vector<string>& words, string chars) {\n        vector<int> dp(26,0);\n        vector<int> dp2(26,0);\n        for(int i=0;i<chars.size();i++){\n            dp[chars[i]-'a']++;\n        }\n        dp2 = dp;\n        bool flg = false;\n        int cnt=0;\n        for(int i=0;i<words.size();i++){\n            string a = words[i];\n            for(int j=0;j<a.size();j++){\n                if(dp[a[j]-'a']>0){\n                    dp[a[j]-'a']--;\n                }\n                else{\n                    flg = true;\n                    dp = dp2;\n                    break;\n                }\n            }\n            if(!flg){\n               cnt += a.size();\n            }\n            dp = dp2;\n            flg = false;\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Subarray Sum Equals K",
        "algo_input": "Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n&nbsp;\nExample 1:\nInput: nums = [1,1,1], k = 2\nOutput: 2\nExample 2:\nInput: nums = [1,2,3], k = 3\nOutput: 2\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t-1000 &lt;= nums[i] &lt;= 1000\n\t-107 &lt;= k &lt;= 107\n\n",
        "solution_py": "class Solution:\n\tdef subarraySum(self, nums: List[int], k: int) -> int:\n\n\t\tans=0\n\t\tprefsum=0\n\t\td={0:1}\n\n\t\tfor num in nums:\n\t\t\tprefsum = prefsum + num\n\n\t\t\tif prefsum-k in d:\n\t\t\t\tans = ans + d[prefsum-k]\n\n\t\t\tif prefsum not in d:\n\t\t\t\td[prefsum] = 1\n\t\t\telse:\n\t\t\t\td[prefsum] = d[prefsum]+1\n\n\t\treturn ans",
        "solution_js": "    var subarraySum = function(nums, k) {\n        const obj = {};\n        let res = 0;\n        let sum = 0;\n\n        for (let i = 0; i < nums.length; i++) {\n\n            sum += nums[i];\n            if (sum == k) res++;\n\n            if (obj[sum - k]) res += obj[sum - k];\n\n            obj[sum] ? obj[sum] += 1 : obj[sum] = 1;\n        }\n        return res;\n    };",
        "solution_java": "/*\n*/\nclass Solution {\n    public int subarraySum(int[] nums, int k) {\n\n        HashMap<Integer, Integer> map = new HashMap<>();\n        map.put(0,1);\n        int count = 0;\n        int sum = 0;\n\n        for(int i=0; i<nums.length; i++){\n            sum += nums[i];\n            if(map.containsKey(sum - k)){\n                count += map.get(sum-k);\n            }\n            map.put(sum, map.getOrDefault(sum,0)+1);\n        }\n        return count;\n    }\n}",
        "solution_c": "/********************************* Solution Using HashMap / Prefix ********************/\n\nclass Solution {\npublic:\n    int subarraySum(vector<int>& nums, int k) {\n       \n        unordered_map<int, int> prefixSum {{0, 1}};\n        \n        int sum = 0;\n        int numOfSubArr = 0;\n        int size = nums.size();\n        \n        \n        for (int index = 0; index < size; index++){\n            \n            sum += nums[index];\n            if (prefixSum.find(sum-k) != prefixSum.end()) \n                numOfSubArr += prefixSum[sum-k];\n            \n            prefixSum[sum]++;\n        }\n        \n        return numOfSubArr;\n    }\n};"
    },
    {
        "title": "Smallest Range Covering Elements from K Lists",
        "algo_input": "You have k lists of sorted integers in non-decreasing&nbsp;order. Find the smallest range that includes at least one number from each of the k lists.\n\nWe define the range [a, b] is smaller than range [c, d] if b - a &lt; d - c or a &lt; c if b - a == d - c.\n\n&nbsp;\nExample 1:\n\nInput: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput: [20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].\n\n\nExample 2:\n\nInput: nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput: [1,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tnums.length == k\n\t1 &lt;= k &lt;= 3500\n\t1 &lt;= nums[i].length &lt;= 50\n\t-105 &lt;= nums[i][j] &lt;= 105\n\tnums[i]&nbsp;is sorted in non-decreasing order.\n\n",
        "solution_py": "from queue import PriorityQueue\nclass Solution:\n\tdef smallestRange(self, nums: List[List[int]]) -> List[int]:\n\t\tq = PriorityQueue()\n\t\tmaxi = -10**7\n\t\tmini = 10**7\n\t\tfor i in range(len(nums)):\n\t\t\tmaxi = max(maxi,nums[i][0])            \n\t\t\tmini = min(mini,nums[i][0])\n\t\t\tq.put((nums[i][0],i,0))  \n\n\t\ts, e = mini, maxi\n\t\twhile not q.empty() :\n\t\t\tmini, i, j = q.get()\n\t\t\tif maxi - mini < e-s:\n\t\t\t\ts,e = mini, maxi\n\t\t\tif j+1 < len(nums[i]):\n\t\t\t\tmaxi = max(maxi,nums[i][j+1])\n\t\t\t\tq.put((nums[i][j+1],i,j+1))\n\t\t\telse: break\n\t\treturn [s,e]",
        "solution_js": "var smallestRange = function(nums) {\n    let minHeap = new MinPriorityQueue({\n        compare: (a,b) => a[0] - b[0]\n    });\n    let start = 0, end = Infinity;\n    let maxSoFar = -Infinity;\n\t\n    for (let num of nums) {\n        minHeap.enqueue([num[0], 0, num]);\n        maxSoFar = Math.max(maxSoFar, num[0]);\n    }\n\t\n    while (minHeap.size() == nums.length) {\n        let [num, i, list] = minHeap.dequeue();\n        \n        if (end - start > maxSoFar - num) {\n            start = num;\n            end = maxSoFar;\n        }\n        \n        if (list.length > i + 1) {\n            minHeap.enqueue([list[i + 1], i + 1, list]);\n            maxSoFar = Math.max(maxSoFar, list[i + 1]);\n        }\n    }\n    \n    return [start, end];\n};",
        "solution_java": "class Solution {\n    \n    class Pair implements Comparable<Pair> {\n        int val;\n        int li;\n        int di;\n        \n        public Pair(int val, int li, int di) {\n            this.val = val;\n            this.li = li;\n            this.di = di;\n        }\n        \n        public int compareTo(Pair other) {\n            return this.val - other.val;\n        }\n    }\n    \n    public int[] smallestRange(List<List<Integer>> nums) {\n        PriorityQueue<Pair> pq = new PriorityQueue<>();\n        int max = Integer.MIN_VALUE;\n        for(int i=0; i<nums.size(); i++) {\n            pq.add(new Pair(nums.get(i).get(0), i, 0));\n            max = Math.max(max, nums.get(i).get(0));\n        }\n        \n        int rbeg = 0;\n        int rend = 0;\n        int rsize = Integer.MAX_VALUE;\n        \n        while(pq.size() == nums.size()) {\n            Pair rem = pq.remove();\n            int crsize = max - rem.val;\n            \n            if(crsize < rsize) {\n                rsize = crsize;\n                rbeg = rem.val;\n                rend = max;\n            }\n            \n            if(rem.di < nums.get(rem.li).size() - 1) {\n                pq.add(new Pair(nums.get(rem.li).get(rem.di + 1), rem.li, rem.di + 1));\n                max = Math.max(max, nums.get(rem.li).get(rem.di + 1));\n            }\n        }\n        \n        return new int[]{rbeg, rend};\n    }\n}",
        "solution_c": "#include <vector>\n#include <queue>\n#include <limits>\n\nusing namespace std;\n\nstruct Item {\n    int val;\n    int r;\n    int c;\n    \n    Item(int val, int r, int c): val(val), r(r), c(c) {\n    }\n};\n\nstruct Comp {\n    bool operator() (const Item& it1, const Item& it2) {\n        return it2.val < it1.val;\n    }\n};\n\nclass Solution {\npublic:\n    vector<int> smallestRange(vector<vector<int>>& nums) {\n        priority_queue<Item, vector<Item>, Comp> pq;\n        \n        int high = numeric_limits<int>::min();\n        int n = nums.size();\n        for (int i = 0; i < n; ++i) {\n            pq.push(Item(nums[i][0], i, 0));\n            high = max(high , nums[i][0]);\n        }\n        int low = pq.top().val;\n        \n        vector<int> res{low, high};\n        \n        while (pq.size() == (size_t)n) {\n            auto it = pq.top();\n            pq.pop();\n            \n            if ((size_t)it.c + 1 < nums[it.r].size()) {\n                pq.push(Item(nums[it.r][it.c + 1], it.r, it.c + 1));\n                high = max(high, nums[it.r][it.c + 1]);\n                low = pq.top().val;\n                if (high - low < res[1] - res[0]) {\n                    res[0] = low;\n                    res[1] = high;\n                }\n            }\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Number of Substrings With Only 1s",
        "algo_input": "Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: s = \"0110111\"\nOutput: 9\nExplanation: There are 9 substring in total with only 1's characters.\n\"1\" -&gt; 5 times.\n\"11\" -&gt; 3 times.\n\"111\" -&gt; 1 time.\n\nExample 2:\n\nInput: s = \"101\"\nOutput: 2\nExplanation: Substring \"1\" is shown 2 times in s.\n\n\nExample 3:\n\nInput: s = \"111111\"\nOutput: 21\nExplanation: Each substring contains only 1's characters.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution(object):\n    def numSub(self, s):\n        res, currsum = 0,0\n        for digit in s:\n            if digit == '0':\n                currsum = 0\n            else:\n                currsum += 1 \n                res+=currsum \n        return res % (10**9+7)",
        "solution_js": "var numSub = function(s) {\n    const mod = Math.pow(10, 9)+7;\n    let r = 0, tot = 0;\n    \n    while (r<s.length) {\n        if (s[r]==='1') {\n            let tmp = r;\n            while (tmp < s.length && s[tmp] === '1') {\n                tot += tmp - r + 1;\n                tot%=mod;\n                tmp++;\n            }\n            r = tmp;\n        }\n        r++;\n    }\n    return tot;\n};",
        "solution_java": "class Solution {\n    public int numSub(String s) {\n        char[] ch = s.toCharArray();\n        long count =0;\n        long result =0;\n        for(int i=0; i<ch.length; i++){\n            if(ch[i] == '1'){\n                count++;\n                result += count;\n            }\n            else{\n                count = 0;\n            \n            }\n        }\n        return (int)(result%1000000007);\n        \n    }\n}",
        "solution_c": "class Solution {\n    /*\n    To calculate the substring the formula is (n*n+1)/2 so just find the range and calculate the substrings.\n    */\nint mod=1e9+7;\n    long calculateNumbeOfSubstrings(string &s,int &l,int &r){\n        long range=r-l;\n        long ans=range*(range+1)/2;\n        return ans;\n    }\npublic:\n    int numSub(string s) {\n        int ans=0;\n        int len=s.size();\n        int r=0,l=0;\n        while(r<len){\n            while(r<len && s[l]!='1'){\n                l++;\n                r++;\n            }\n            while(r<len && s[r]!='0'){\n                r++;\n            }\n               ans=(ans+calculateNumbeOfSubstrings(s,l,r))%mod;\n                l=r;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Reverse Vowels of a String",
        "algo_input": "Given a string s, reverse only all the vowels in the string and return it.\n\nThe vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.\n\n&nbsp;\nExample 1:\nInput: s = \"hello\"\nOutput: \"holle\"\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"leotcede\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 3 * 105\n\ts consist of printable ASCII characters.\n\n",
        "solution_py": "class Solution:\n    def reverseVowels(self, s: str) -> str:\n        s=list(s)\n        vow=[]\n        for i,val in enumerate(s):\n            if val in ('a','e','i','o','u','A','E','I','O','U'):\n                vow.append(val)\n                s[i]='_'\n                \n        vow=vow[::-1]\n        c=0\n        print(vow)\n        for i,val in enumerate(s):\n            if val =='_':\n                s[i]=vow[c]\n                c+=1\n        return \"\".join(s)",
        "solution_js": "var reverseVowels = function(s) {\n    const VOWELS = { 'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1 };\n    const arr = s.split('');\n    let i = 0, j = arr.length - 1;\n    while (i < j) {\n        if (VOWELS[arr[i]] && VOWELS[arr[j]]) {\n            [arr[i], arr[j]] = [arr[j], arr[i]];\n            i++;\n            j--;\n        } else if (VOWELS[arr[i]]) {\n            j--;\n        } else {\n            i++;\n        }\n    }\n    return arr.join('');\n};",
        "solution_java": "class Solution {\n    public String reverseVowels(String s) {\n        Set<Character> set = new HashSet<>();\n        set.add('a');\n        set.add('e');\n        set.add('i');\n        set.add('o');\n        set.add('u');\n        set.add('A');\n        set.add('E');\n        set.add('I');\n        set.add('O');\n        set.add('U');\n        \n        StringBuilder str = new StringBuilder(s);\n        int left = 0, right = str.length() - 1;\n        while (left < right) {\n            if (!set.contains(str.charAt(left))) {\n                left++;\n            }\n            if (!set.contains(str.charAt(right))) {\n                right--;\n            }\n            if (set.contains(str.charAt(left)) && set.contains(s.charAt(right))) {\n                char temp = str.charAt(left);\n                str.setCharAt(left++, str.charAt(right));\n                str.setCharAt(right--, temp);\n            }\n        }\n        return str.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool isVowel(char s)\n    {\n        if(s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u'\n           or s == 'A' or s == 'E' or s == 'I' or s == 'O' or s == 'U') return true;\n        return false;\n    }\n    \n    string reverseVowels(string s) {\n        if(s.size() == 0) return \"\";\n        int left = 0, right = s.size() - 1;\n        \n        while(left < right)\n        {\n            if(isVowel(s[left]) and isVowel(s[right]))\n            {\n                swap(s[left], s[right]);\n                left++;\n                right--;\n            }\n            else if(isVowel(s[left])) right--;\n            else if(isVowel(s[right])) left++;\n            else {\n                left++;\n                right--;\n            }\n        }\n        \n        \n        return s;\n    }\n};"
    },
    {
        "title": "Palindrome Partitioning II",
        "algo_input": "Given a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn the minimum cuts needed for a palindrome partitioning of s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aab\"\nOutput: 1\nExplanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n\n\nExample 2:\n\nInput: s = \"a\"\nOutput: 0\n\n\nExample 3:\n\nInput: s = \"ab\"\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 2000\n\ts consists of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def isPallindrom(self, s: str, l, r) -> bool:\n        st = s[l: r+1]\n        rev = st[::-1]\n        return st == rev\n    \n    def minCut(self, s: str) -> int:\n        N = len(s)\n        if not s: return 0\n        if self.isPallindrom(s, 0, N-1): return 0\n        dp = [sys.maxsize] * (N+1)\n        dp[-1] = 0\n        \n        for i in range(N-1, -1, -1):\n            for j in range(i, N):\n                if self.isPallindrom(s, i, j):\n                    dp[i] = min(dp[i], 1 + dp[j+1])\n                    \n        return dp[0]-1",
        "solution_js": "var minCut = function(s) {\n    function isPal(l, r) {\n        while (l < r) {\n            if (s[l] === s[r]) l++, r--;\n            else return false;\n        } return true;\n    }\n\n    let map = new Map();\n    function dfs(idx = 0) {\n        if (idx === s.length) return 0;\n        if (map.has(idx)) return map.get(idx);\n        let min = Infinity;\n        for (let i = idx; i < s.length; i++) {\n            if (isPal(idx, i)) min = Math.min(min, 1 + dfs(i + 1));\n        }\n        map.set(idx, min);\n        return min;\n    }\n\n    return dfs() - 1;\n};",
        "solution_java": "class Solution {\nint dp[];\n\n public boolean pali(int i,int j,String s){\n    \n   // int j=s.length()-1,i=0;\n    \n    while(i<=j){\n        \n        if(s.charAt(i)!=s.charAt(j))return false;\n            \n            i++;j--;\n        \n    }\n    \n    return true;\n    \n}\npublic int cut(String s,int i,int n,int dp[]){\n    \n    if(i==n)return 0;\n    if(dp[i]!=-1)return dp[i];\n    \n    int min=Integer.MAX_VALUE;\n    \n    for(int j=i;j<n;j++){\n        \n        if(pali(i,j,s)){\n            \n            int cost=1+cut(s,j+1,n,dp);\n            min=Math.min(min,cost);\n            \n      } \n    }\n   return  dp[i]=min;\n       \npublic int minCut(String s) {\n    int n=s.length();\n    dp=new int[n];\n    Arrays.fill(dp,-1);\n    return cut(s,0,n,dp)-1;       \n}",
        "solution_c": "class Solution {\npublic:\n    \n\t// function to precompute if every substring of s is a palindrome or not\n    vector<vector<bool>> isPalindrome(string& s){\n        int n = s.size();\n        vector<vector<bool>> dp(n, vector<bool>(n, false));\n        \n        for(int i=0; i<n; i++){\n            dp[i][i] = true;\n        }\n        \n        for(int i=0; i<n-1; i++){\n            if(s[i] == s[i+1]){\n                dp[i][i+1] = true;\n            }\n        }\n        \n        int k = 2;\n        \n        while(k < n){\n            int i=0;\n            int j=k;\n            \n            while(j<n){\n                if(s[i] == s[j] and dp[i+1][j-1]){\n                    dp[i][j] = true;\n                }\n                \n                i++;\n                j++;\n            }\n            \n            k++;\n        }\n        \n        return dp;\n    }\n    \n\t// function to find the minimum palindromic substrings in s\n    int solve(string& s, int n, int i, vector<vector<bool>>& palin, vector<int>& memo){\n        if(i==n){\n            return 0;\n        }\n        if(memo[i] != -1){\n            return memo[i];\n        }\n        \n        int result = INT_MAX;\n        \n        for(int j=i+1; j<=n; j++){\n            if(palin[i][j-1]){\n                result = min(result, 1+solve(s, n, j, palin, memo));\n            }\n        }\n        \n        return memo[i] = result;\n    }\n    \n    int minCut(string s) {\n        int n = s.size();\n        vector<int> memo(n, -1);\n        vector<vector<bool>> palin = isPalindrome(s);\n        return solve(s, n, 0, palin, memo)-1;\n    }\n};"
    },
    {
        "title": "Number of Different Integers in a String",
        "algo_input": "You are given a string word that consists of digits and lowercase English letters.\n\nYou will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123&nbsp; 34 8&nbsp; 34\". Notice that you are left with some integers that are separated by at least one space: \"123\", \"34\", \"8\", and \"34\".\n\nReturn the number of different integers after performing the replacement operations on word.\n\nTwo integers are considered different if their decimal representations without any leading zeros are different.\n\n&nbsp;\nExample 1:\n\nInput: word = \"a123bc34d8ef34\"\nOutput: 3\nExplanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.\n\n\nExample 2:\n\nInput: word = \"leet1234code234\"\nOutput: 2\n\n\nExample 3:\n\nInput: word = \"a1b01c001\"\nOutput: 1\nExplanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 1000\n\tword consists of digits and lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def numDifferentIntegers(self, word: str) -> int:\n\n        word = re.findall('(\\d+)', word)\n        numbers = [int(i) for i in word]\n\n        return len(set(numbers))",
        "solution_js": "const CC0 = '0'.charCodeAt(0);\n\nvar numDifferentIntegers = function(word) {\n    const numStrSet = new Set();\n    \n    // get numbers as strings\n    const numStrs = word.split(/[^0-9]+/);\n    \n    // drop leading zeros\n    for (const numStr of numStrs) {\n        if (numStr.length > 0) {\n            let i = 0;\n            while (numStr.charCodeAt(i) === CC0) i++;\n            \n            // make sure that we preserve last 0 if string is composed of zeros only\n            numStrSet.add(numStr.slice(i) || '0');\n        }\n    }\n    \n    return numStrSet.size;\n};",
        "solution_java": "class Solution {\n    public int numDifferentIntegers(String word) {\n        String[] arr = word.replaceAll(\"[a-zA-Z]\", \" \").split(\"\\\\s+\");\n        Set<String> set = new HashSet<String>();\n\n        for (String str : arr) {\n            if (!str.isEmpty())\n                set.add(String.valueOf(str.replaceAll(\"^0*\",\"\")));\n        }\n\n        return set.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numDifferentIntegers(string word) {\n        unordered_map<string, int> hmap;\n        for (int i = 0; i < word.size(); i++) {\n            if (isdigit(word[i])) {\n                string str;\n                while (word[i] == '0')\n                    i++;\n                while (isdigit(word[i]))\n                    str += word[i++];\n                hmap[str]++;\n            }\n        }\n        return hmap.size();\n    }\n};"
    },
    {
        "title": "Design HashMap",
        "algo_input": "Design a HashMap without using any built-in hash table libraries.\n\nImplement the MyHashMap class:\n\n\n\tMyHashMap() initializes the object with an empty map.\n\tvoid put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.\n\tint get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.\n\tvoid remove(key) removes the key and its corresponding value if the map contains the mapping for the key.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\nOutput\n[null, null, null, 1, -1, null, 1, null, -1]\n\nExplanation\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= key, value &lt;= 106\n\tAt most 104 calls will be made to put, get, and remove.\n\n",
        "solution_py": "class MyHashMap:\n    def __init__(self):\n        self.data = [None] * 1000001\n    def put(self, key: int, val: int) -> None:\n        self.data[key] = val\n    def get(self, key: int) -> int:\n        val = self.data[key]\n        return val if val != None else -1\n    def remove(self, key: int) -> None:\n        self.data[key] = None",
        "solution_js": "var MyHashMap = function() {\n    this.hashMap = [];\n};\n\n/**\n * @param {number} key\n * @param {number} value\n * @return {void}\n */\nMyHashMap.prototype.put = function(key, value) {\n    this.hashMap[key] = [key, value];\n};\n\n/**\n * @param {number} key\n * @return {number}\n */\nMyHashMap.prototype.get = function(key) {\n    return this.hashMap[key] ? this.hashMap[key][1] : -1;\n};\n\n/**\n * @param {number} key\n * @return {void}\n */\nMyHashMap.prototype.remove = function(key) {\n    delete this.hashMap[key];\n};\n\n/**\n * Your MyHashMap object will be instantiated and called as such:\n * var obj = new MyHashMap()\n * obj.put(key,value)\n * var param_2 = obj.get(key)\n * obj.remove(key)\n */",
        "solution_java": "class MyHashMap {\n\n\t/** Initialize your data structure here. */\n\tLinkedList<Entry>[] map;\n\tpublic static int SIZE = 769;\n\tpublic MyHashMap() {\n\t\tmap = new LinkedList[SIZE];\n\t}\n\n\t/** value will always be non-negative. */\n\tpublic void put(int key, int value) {\n\t\tint bucket = key % SIZE;\n\t\tif(map[bucket] == null) {\n\t\t\tmap[bucket] = new LinkedList<Entry>();\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key){\n\t\t\t\t\tentry.val = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tpublic int get(int key) {\n\t\tint bucket = key % SIZE;\n\t\tLinkedList<Entry> entries = map[bucket];\n\t\tif(entries == null) return -1;\n\t\tfor(Entry entry : entries) {\n\t\t\tif(entry.key == key) return entry.val;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tpublic void remove(int key) {\n\t\tint bucket = key % SIZE;\n\t\tEntry toRemove = null;\n\t\tif(map[bucket] == null) return;\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key) {\n\t\t\t\t\ttoRemove = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(toRemove == null) return;\n\t\t\tmap[bucket].remove(toRemove);\n\t\t}\n\t}\n}\n\nclass Entry {\n\tpublic int key;\n\tpublic int val;\n\n\tpublic Entry(int key, int val){\n\t\tthis.key = key;\n\t\tthis.val = val;\n\t}\n}",
        "solution_c": "class MyHashMap {\n\tvector<vector<pair<int, int>>> map;\n\tconst int size = 10000;\npublic:\n\t/** Initialize your data structure here. */\n\tMyHashMap() {\n\t\tmap.resize(size);\n\t}\n\n\t/** value will always be non-negative. */\n\tvoid put(int key, int value) {\n\t\tint index = key % size;\n        vector<pair<int, int>> &row = map[index];\n        for(auto iter = row.begin(); iter != row.end(); iter++)\n        {\n            if(iter->first == key)\n            {\n                iter->second = value;\n                return;\n            }\n        }\n\t\trow.push_back(make_pair(key, value));\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tint get(int key) {\n\t\tint index = key % size;\n        vector<pair<int, int>> &row = map[index];\n\t\tfor (auto iter = row.begin(); iter != row.end(); iter++)\n\t\t{\n\t\t\tif (iter->first == key)\n\t\t\t{\n\t\t\t\treturn iter->second;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tvoid remove(int key) {\n\t\tint index = key % size;\n        vector<pair<int, int>> &row = map[index];\n\t\tfor (auto iter = row.begin(); iter != row.end(); iter++)\n\t\t{\n\t\t\tif (iter->first == key)\n\t\t\t{\n\t\t\t\trow.erase(iter);\n                return;\n\t\t\t}\n\t\t}\n\t}\n};\n\n/**\n * Your MyHashMap object will be instantiated and called as such:\n * MyHashMap* obj = new MyHashMap();\n * obj->put(key,value);\n * int param_2 = obj->get(key);\n * obj->remove(key);\n */"
    },
    {
        "title": "Sum of All Odd Length Subarrays",
        "algo_input": "Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\n\nA subarray is a contiguous subsequence of the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\n\nExample 2:\n\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\n\nExample 3:\n\nInput: arr = [10,11,12]\nOutput: 66\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 100\n\t1 &lt;= arr[i] &lt;= 1000\n\n\n&nbsp;\nFollow up:\n\nCould you solve this problem in O(n) time complexity?\n",
        "solution_py": "class Solution:\n    def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n        n = len(arr)\n        ans = 0\n        for i in range(n):\n            total = (i+1) * (n-1-i+1)\n            ans = ans + (total//2 + total%2) * arr[i]\n        return ans",
        "solution_js": "/*\nSuppose N is the length of given array.\nNumber of subarrays including element arr[i] is\ni * (N-i) + (N-i) because there are N-i subarrays with arr[i] as first element\nand i * (N-i) subarrays with arr[i] as a not-first element. arr[i] appears in \n(N-i) subarrays for each preceding element and therefore we have i*(N-i).\n\nSuppose i * (N-i) + (N-i) is `total`. Ceil(total / 2) is the number of odd-length subarrays and Floor(total / 2) is the number of even-length subarrays. \nWhen total is odd, there is one more odd-length subarray because of a single-element subarray.\n    \nFor each number, we multiply its value with the total number of subarrays it appears and\nadd it to a sum.\n*/\nvar sumOddLengthSubarrays = function(arr) {\n    let sum = 0, N = arr.length;\n    for (let i = 0; i < arr.length; i++) {\n        let total = i * (N-i) + (N-i);\n        sum += Math.ceil(total / 2) * arr[i];\n    }\n    return sum;\n    // T.C: O(N)\n    // S.C: O(1)\n};",
        "solution_java": "class Solution {\n    public int sumOddLengthSubarrays(int[] arr) {\n        \n        // Using two loops in this question...\n        int sum = 0;\n        for(int i=0 ; i<arr.length ; i++){\n            int prevSum = 0;\n            for(int j=i ; j<arr.length ; j++){\n                prevSum+=arr[j];\n                if((j-i+1)%2==1){\n                    sum+=prevSum;\n                }\n            }\n        }\n        // Time Complexity : O(n-square)\n        // Space Complexity : O(1)\n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumOddLengthSubarrays(vector<int>& arr) {\n        int sum=0;\n        int sum1=0;\n        for(int i=0;i<arr.size();i++)\n        {\n            int count=0;\n            sum+=arr[i];\n            for(int j=i;j<arr.size();j++)\n            {\n                sum1+=arr[j];\n                count++;\n                if(count%2!=0 and count!=1)\n                    sum+=sum1;\n            }\n            sum1=0;\n        }\n        return sum;\n    }\n};"
    },
    {
        "title": "Evaluate the Bracket Pairs of a String",
        "algo_input": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.\n\n\n\tFor example, in the string \"(name)is(age)yearsold\", there are two bracket pairs that contain the keys \"name\" and \"age\".\n\n\nYou know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.\n\nYou are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:\n\n\n\tReplace keyi and the bracket pair with the key's corresponding valuei.\n\tIf you do not know the value of the key, you will replace keyi and the bracket pair with a question mark \"?\" (without the quotation marks).\n\n\nEach key will appear at most once in your knowledge. There will not be any nested brackets in s.\n\nReturn the resulting string after evaluating all of the bracket pairs.\n\n&nbsp;\nExample 1:\n\nInput: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput: \"bobistwoyearsold\"\nExplanation:\nThe key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\n\n\nExample 2:\n\nInput: s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\nOutput: \"hi?\"\nExplanation: As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".\n\n\nExample 3:\n\nInput: s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\nOutput: \"yesyesyesaaa\"\nExplanation: The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\t0 &lt;= knowledge.length &lt;= 105\n\tknowledge[i].length == 2\n\t1 &lt;= keyi.length, valuei.length &lt;= 10\n\ts consists of lowercase English letters and round brackets '(' and ')'.\n\tEvery open bracket '(' in s will have a corresponding close bracket ')'.\n\tThe key in each bracket pair of s will be non-empty.\n\tThere will not be any nested bracket pairs in s.\n\tkeyi and valuei consist of lowercase English letters.\n\tEach keyi in knowledge is unique.\n\n",
        "solution_py": "class Solution:\n    def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n        knowledge = dict(knowledge)\n        answer, start = [], None\n        for i, char in enumerate(s):\n            if char == '(': \n                start = i + 1\n            elif char == ')':\n                answer.append(knowledge.get(s[start:i], '?'))\n                start = None\n            elif start is None: \n                answer.append(char)\n        return ''.join(answer)",
        "solution_js": "var evaluate = function(s, knowledge) {\n    // key => value hash map can be directly constructed using the Map constructor\n    const map = new Map(knowledge);\n    \n\t// since bracket pairs can't be nested we can use a RegExp to capture keys and replace using a map constructed in the line above\n\treturn s.replace(/\\(([a-z]+)\\)/g, (_, p1) => map.get(p1) ?? \"?\");\n};",
        "solution_java": "class Solution {\n    public String evaluate(String s, List<List<String>> knowledge) {\n        Map<String, String> map = new HashMap<>();\n        for(List<String> ele : knowledge) {\n            map.put(ele.get(0), ele.get(1));\n        }\n        StringBuilder sb = new StringBuilder();\n        int b_start = -1;\n        for(int i = 0; i < s.length(); i++) {\n            if(s.charAt(i) == '(') {\n                b_start = i;\n            } else if(s.charAt(i) == ')') {\n                String key = s.substring(b_start + 1, i);\n                sb.append(map.getOrDefault(key, \"?\"));\n                b_start = -1;\n            } else {\n                if(b_start == -1) {\n                    sb.append(s.charAt(i));\n                }\n            }\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string evaluate(string s, vector<vector<string>>& knowledge) {\n        string ans; // resultant string\n        int n = s.size();\n        if(n < 2) return s; // because () will come in pair so, size should be more than 2\n        int sz = knowledge.size();\n        for(int i=0; i<sz; ++i){\n            mp.insert({knowledge[i][0], knowledge[i][1]}); // Inserting {key, value} pair\n        }\n        for(int i=0; i<n; i++){\n            \n            if(s[i] == '('){  \n                string key;\n                i++;\n                while(s[i] != ')'){ // getting key till we get ')'\n                    key += s[i++];\n                }\n                string value;\n                if(mp.find(key) != mp.end()){ // If {key, value} pair is present then replace (key) by it's value\n                    value = mp[key];\n                    ans += value;\n                }\n                else {// otherwise replace (key) by ?\n                    ans += \"?\";\n                }\n            }\n            else ans += s[i];\n        }\n        return ans;\n    }\n};\n\n**Please do upvote**"
    },
    {
        "title": "Maximum Running Time of N Computers",
        "algo_input": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.\n\nInitially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.\n\nNote that the batteries cannot be recharged.\n\nReturn the maximum number of minutes you can run all the n computers simultaneously.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, batteries = [3,3,3]\nOutput: 4\nExplanation: \nInitially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.\n\n\n\nExample 2:\n\nInput: n = 2, batteries = [1,1,1,1]\nOutput: 2\nExplanation: \nInitially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= batteries.length &lt;= 105\n\t1 &lt;= batteries[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maxRunTime(self, n: int, batteries: List[int]) -> int:\n        batteries.sort()\n        total=sum(batteries)\n        while batteries[-1]>total//n:\n            n-=1\n            total-=batteries.pop()\n        return total//n",
        "solution_js": "var maxRunTime = function(n, batteries) {\n    let total = batteries.reduce((acc,x)=>acc+x,0)\n    let batts = batteries.sort((a,b)=>b-a)\n    let i = 0\n    while(1){\n        let average_truncated = parseInt(total / n)\n        let cur = batts[i]\n        if(cur > average_truncated){\n            total -= cur // remove all of that batteries charge from the equation\n            n --         // remove the computer from the equation\n            i++\n        } else {\n            return average_truncated\n        }\n    }\n};",
        "solution_java": "class Solution {\n\n    private boolean canFit(int n, long k, int[] batteries) {\n        long currBatSum = 0;\n        long target = n * k;\n\n        for (int bat : batteries) {\n            if (bat < k) {\n                currBatSum += bat;\n            } else {\n                currBatSum += k;\n            }\n\n            if (currBatSum >= target) {\n                return true;\n            }\n        }\n\n        return currBatSum >= target;\n\n    }\n\n    public long maxRunTime(int n, int[] batteries) {\n        long batSum = 0;\n        for (int bat : batteries) {\n            batSum += bat;\n        }\n        \n        long lower = 0;\n        long upper = batSum / n;\n        long res = -1;\n\n\t\t// binary search\n        while (lower <= upper) {\n            long mid = lower + (upper - lower) / 2;\n\n            if (canFit(n, mid, batteries)) {\n                res = mid;\n                lower = mid + 1;\n            } else {\n                upper = mid - 1;\n            }\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\nbool canFit(int n,long timeSpan,vector<int>batteries)\n{\n    long currBatSum=0;\n\tlong targetBatSum=n*timeSpan; \n    for(auto it:batteries)\n    {\n        if(it<timeSpan)\n            currBatSum+=it;\n        else\n            currBatSum+=timeSpan;\n        \n        if(currBatSum>=targetBatSum)\n            return true;  \n    }\n    \n    return false;\n }\n\nlong long maxRunTime(int n, vector<int>& batteries) {\n  long totalSum=0;\n  long low=*min_element(batteries.begin(),batteries.end());\n  \n    for(auto it:batteries)\n    {\n        totalSum+=it;  \n    }\n    \n    long high = totalSum/n;\n    long ans=-1;\n    \n    while(low<=high)\n    {\n     \n      long mid = low+(high-low)/2;    \n     if(canFit(n,mid,batteries))\n     {\n         ans=mid;\n         low=mid+1;\n     }\n     else\n     {\n         high=mid-1;\n     }\n           \n    }  \n   return ans;       \n}"
    },
    {
        "title": "Beautiful Arrangement",
        "algo_input": "Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 &lt;= i &lt;= n), either of the following is true:\n\n\n\tperm[i] is divisible by i.\n\ti is divisible by perm[i].\n\n\nGiven an integer n, return the number of the beautiful arrangements that you can construct.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 2\nExplanation: \nThe first beautiful arrangement is [1,2]:\n    - perm[1] = 1 is divisible by i = 1\n    - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n    - perm[1] = 2 is divisible by i = 1\n    - i = 2 is divisible by perm[2] = 1\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 15\n\n",
        "solution_py": "class Solution:\n    def countArrangement(self, n: int) -> int:\n        self.count = 0\n        self.backtrack(n, 1, [])\n        return self.count\n        \n    def backtrack(self, N, idx, temp):\n        if len(temp) == N:\n            self.count += 1\n            return\n        \n        for i in range(1, N+1):\n            if i not in temp and (i % idx == 0 or idx % i == 0):\n                temp.append(i)\n                self.backtrack(N, idx+1, temp)\n                temp.pop()",
        "solution_js": "var countArrangement = function(n) {\n    let result = 0;\n    const visited = Array(n + 1).fill(false);\n    const dfs = (next = n) => {\n        if (next === 0) {\n            result += 1;\n            return;\n        }\n\n        for (let index = 1; index <= n; index++) {\n            if (visited[index] || index % next && next % index) continue;\n            visited[index] = true;\n            dfs(next - 1);\n            visited[index] = false;\n        }\n    };\n\n    dfs();\n    return result;\n};",
        "solution_java": "class Solution {\n    int N;\n    Integer[][] memo;\n    public int countArrangement(int n) {\n        this.N = n;\n        memo = new Integer[n+1][1<<N];\n        return permute(1, 0);\n    }\n\n    private int permute(int index, int mask)\n    {\n        if (mask == (1<<N)-1)\n            return 1;\n        if (memo[index][mask] != null)\n            return memo[index][mask];\n        int res = 0;\n        for (int i = 1; i <= N; i++)\n        {\n            if ((mask & (1<<(i-1))) == 0 && (index % i == 0 || i % index == 0))\n            {\n                mask |= (1<<(i-1));\n                res += permute(index+1, mask);\n                mask ^= (1<<(i-1));\n            }\n        }\n        return memo[index][mask]=res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = 0;\n    bool isBeautiful(vector<int> &v) {\n        int i = v.size() - 1;\n        if (v[i] % (i + 1) == 0 || (i + 1) % v[i] == 0) return true;\n        return false;\n    }\n\n    void solve(int n, vector<int> &p, vector<bool> &seen) {\n        if (p.size() == n) {\n            ans++;\n            return;\n        }\n        for (int i = 1; i <= n; i++) {\n\n            if (seen[i]) continue;\n            p.push_back(i);\n\n            if (isBeautiful(p)) {\n                seen[i] = true;\n                solve(n, p, seen);\n                seen[i] = false;\n            }\n            p.pop_back();\n        }\n    }\n    int countArrangement(int n) {\n\n        vector<int> p;\n        vector<bool> seen(n + 1, false);\n        solve(n, p, seen);\n\n        return ans;\n    }\n};"
    },
    {
        "title": "24 Game",
        "algo_input": "You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.\n\nYou are restricted with the following rules:\n\n\n\tThe division operator '/' represents real division, not integer division.\n\n\t\n\t\tFor example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.\n\t\n\t\n\tEvery operation done is between two numbers. In particular, we cannot use '-' as a unary operator.\n\t\n\t\tFor example, if cards = [1, 1, 1, 1], the expression \"-1 - 1 - 1 - 1\" is not allowed.\n\t\n\t\n\tYou cannot concatenate numbers together\n\t\n\t\tFor example, if cards = [1, 2, 1, 2], the expression \"12 + 12\" is not valid.\n\t\n\t\n\n\nReturn true if you can get such expression that evaluates to 24, and false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: cards = [4,1,8,7]\nOutput: true\nExplanation: (8-4) * (7-1) = 24\n\n\nExample 2:\n\nInput: cards = [1,2,1,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tcards.length == 4\n\t1 &lt;= cards[i] &lt;= 9\n\n",
        "solution_py": "class Solution:\n    def judgePoint24(self, cards: List[int]) -> bool:\n        return self.allComputeWays(cards, 4, 24)\n        \n    def allComputeWays(self, nums, l, target):\n        if l == 1:\n            if abs(nums[0] - target) <= 1e-6:\n                return True\n            return False\n        for first in range(l):\n            for second in range(first + 1, l):\n                tmp1, tmp2 = nums[first], nums[second]\n                nums[second] = nums[l - 1]\n                \n                nums[first] = tmp1 + tmp2\n                if self.allComputeWays(nums, l - 1, target):\n                    return True\n                nums[first] = tmp1 - tmp2\n                if self.allComputeWays(nums, l - 1, target):\n                    return True\n                nums[first] = tmp2 - tmp1\n                if self.allComputeWays(nums, l - 1, target):\n                    return True\n                nums[first] = tmp1 * tmp2\n                if self.allComputeWays(nums, l - 1, target):\n                    return True\n                if tmp2:\n                    nums[first] = tmp1 / tmp2\n                    if self.allComputeWays(nums, l - 1, target):\n                        return True\n                if tmp1:\n                    nums[first] = tmp2 / tmp1\n                    if self.allComputeWays(nums, l - 1, target):\n                        return True\n                nums[first], nums[second] = tmp1, tmp2\n        return False",
        "solution_js": "/**\n * @param {number[]} cards\n * @return {boolean}\n1487\n7-1 8-4\n */\nvar judgePoint24 = function(cards) {\n    let minV = 0.00000001;\n    let numL = [];\n    cards.forEach(card=>numL.push(card));\n    function judge(nums){\n        if(nums.length === 1) return Math.abs(nums[0]-24)<=minV;\n        else{\n            for(let i = 0 ;i<nums.length;i++){\n                for(let j = 0 ;j<i;j++){\n                    let a = nums[i] ,b = nums[j];\n                    let val =[a + b, a - b, b - a, a * b, a / b, b / a];\n                    let copy =[...nums];\n                    copy.splice(i,1);\n                    copy.splice(j,1);\n                    for(let v of val){\n                        copy.push(v);\n                        if (judge(copy)) {\n                            return true;\n                        }\n                        copy.pop();\n                    }\n                }\n            }\n            return false;\n        }\n    }\n    return judge(numL);\n};",
        "solution_java": "// 0 ms. 100%\nclass Solution {\n    private static final double EPS = 1e-6;\n    private boolean backtrack(double[] A, int n) {\n        if(n == 1) return Math.abs(A[0] - 24) < EPS;\n        for(int i = 0; i < n; i++) {\n            for(int j = i + 1; j < n; j++) {\n                double a = A[i], b = A[j];\n                A[j] = A[n-1];\n                A[i] = a + b;\n                if(backtrack(A, n - 1)) return true;\n                A[i] = a - b;\n                if(backtrack(A, n - 1)) return true;\n                A[i] = b - a;\n                if(backtrack(A, n - 1)) return true;\n                A[i] = a * b;\n                if(backtrack(A, n - 1)) return true;\n                if(Math.abs(b) > EPS) {\n                    A[i] = a / b;\n                    if(backtrack(A, n - 1)) return true;\n                }\n                if(Math.abs(a) > EPS) {\n                    A[i] = b / a;\n                    if(backtrack(A, n - 1)) return true;\n                }\n                A[i] = a; A[j] = b;\n            }\n        }\n        return false;\n    }\n    public boolean judgePoint24(int[] nums) {\n        double[] A = new double[nums.length];\n        for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n        return backtrack(A, A.length);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double cor=0.001;\n    void dfs(vector<double> &cards,bool &res){\n        if(res==true) return;\n        if(cards.size()==1){\n            if(abs(cards[0]-24)<cor) res=true;\n            return;\n        }\n        for(int i=0;i<cards.size();i++){\n            for(int j=0;j<i;j++){\n                double p=cards[i],q=cards[j];\n                vector<double> t{p+q,q-p,p-q,p*q};\n                if(p>cor) t.push_back(q/p);\n                if(q>cor) t.push_back(p/q);\n                cards.erase(cards.begin()+i);\n                cards.erase(cards.begin()+j);\n                for(double d:t){\n                    cards.push_back(d);\n                    dfs(cards,res);\n                    cards.pop_back();\n                }\n                cards.insert(cards.begin()+j,q);\n                cards.insert(cards.begin()+i,p);\n            }\n        }\n    }\n    bool judgePoint24(vector<int>& cards) {\n        bool res=false;\n        vector<double> card (cards.begin(),cards.end());\n        dfs(card,res);\n        return res;\n    }\n};"
    },
    {
        "title": "Largest Magic Square",
        "algo_input": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.\n\nGiven an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput: 3\nExplanation: The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12\n\n\nExample 2:\n\nInput: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 50\n\t1 &lt;= grid[i][j] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def largestMagicSquare(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0]) # dimensions \n        rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n        cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n        \n        for i in range(m):\n            for j in range(n): \n                rows[i][j+1] = grid[i][j] + rows[i][j]\n                cols[i+1][j] = grid[i][j] + cols[i][j]\n        \n        ans = 1\n        for i in range(m): \n            for j in range(n): \n                diag = grid[i][j]\n                for k in range(min(i, j)): \n                    ii, jj = i-k-1, j-k-1\n                    diag += grid[ii][jj]\n                    ss = {diag}\n                    for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])\n                    for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])\n                    ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal\n                    if len(ss) == 1: ans = max(ans, k+2)\n        return ans ",
        "solution_js": "var largestMagicSquare = function(grid) {\n   const row = grid.length;\n   const col = grid[0].length;\n   const startSize = row <= col ? row : col;\n   for(let s = startSize; s > 1; s--){\n       for(let r = 0; r < grid.length - s + 1; r++){\n           for(let c = 0; c < grid[0].length - s + 1; c++){\n               if(isMagic(grid, r, c, s)){\n                   return s;\n               }\n           }\n       }\n   }\n   return 1;\n};\n\nconst isMagic = (grid, i, j, size) => {\n   let targetSum = 0;\n   for(let c = j; c < j + size; c++){\n       targetSum += grid[i][c];\n   }\n   //check rows\n   for(let r = i; r < i + size; r++){\n       let sum = 0;\n       for(let c = j; c < j + size; c++){\n           sum += grid[r][c];\n       }\n       if(targetSum !== sum){\n           return false;\n       }\n   }\n   //check cols\n   for(let c = j; c < j + size; c++){\n       let sum = 0;\n       for(let r = i; r < i + size; r++){\n           sum += grid[r][c];\n       }\n       if(targetSum !== sum){\n           return false;\n       }\n   }\n   //check diagonals\n   let diagSum = 0, antiDiagSum = 0;\n   for(let c = 0; c < size; c++){\n       diagSum += grid[i + c][j+c];\n       antiDiagSum += grid[i + c][j + size - 1 - c];\n   }\n   if(diagSum !== antiDiagSum || diagSum !== targetSum){\n       return false\n   }\n   return true;\n}",
        "solution_java": "class Solution {\n  public int largestMagicSquare(int[][] grid) {\n    int m = grid.length;\n    int n = grid[0].length;\n    // every row prefix sum\n    int[][] rowPrefix = new int[m][n];\n    for (int i = 0; i < m; i++) {\n      rowPrefix[i][0] = grid[i][0];\n      for (int j = 1; j < n; j++) {\n        rowPrefix[i][j] = rowPrefix[i][j - 1] + grid[i][j];\n      }\n    }\n\n    // every column prefix sum\n    int[][] columnPrefix = new int[m][n];\n    for (int i = 0; i < n; i++) {\n      columnPrefix[0][i] = grid[0][i];\n      for (int j = 1; j < m; j++) {\n        columnPrefix[j][i] = columnPrefix[j - 1][i] + grid[j][i];\n      }\n    }\n\n    int result = 1;\n    for (int i = 0; i < m; i++) {\n      for (int j = 0; j < n; j++) {\n        // length of square\n        int l = Math.min(m - i, n - j);\n        // only check square's length is better than previous result\n        for (int k = l; k > result; k--) {\n          if (magic(i, j, k, grid, rowPrefix, columnPrefix)) {\n            result = k;\n            break;\n          }\n        }\n      }\n    }\n    return result;\n  }\n\n  private boolean magic(\n      int i, int j, int l, int[][] grid, int[][] rowPrefix, int[][] columnPrefix) {\n    // check every row\n    int target = rowPrefix[i][j + l - 1] - rowPrefix[i][j] + grid[i][j];\n    for (int k = 0; k < l; k++) {\n      if (rowPrefix[i + k][j + l - 1] - rowPrefix[i + k][j] + grid[i + k][j] != target) {\n        return false;\n      }\n    }\n\n    // check every column\n    for (int k = 0; k < l; k++) {\n      if (columnPrefix[i + l - 1][j + k] - columnPrefix[i][j + k] + grid[i][j + k] != target) {\n        return false;\n      }\n    }\n\n    // check both diagonal\n    int diagonal = 0;\n    // \\\n    // \\\n    for (int k = 0; k < l; k++) {\n      diagonal += grid[i + k][j + k];\n    }\n\n    if (diagonal != target) {\n      return false;\n    }\n\n    // /\n    // /\n    for (int k = 0; k < l; k++) {\n      diagonal -= grid[i + l - 1 - k][j + k];\n    }\n\n    return diagonal == 0;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isValid(int r1, int r2, int c1, int c2, vector<vector<int>>& grid, vector<vector<int>>& rg, vector<vector<int>>& cg,int checkSum){\n        //Checking all row sums between top and bottom row\n        for(int i = r1 + 1; i<r2; i++){\n            int sum = rg[i][c2];\n            if(c1>0)sum-=rg[i][c1-1];\n            if(sum!=checkSum)return false;\n        }\n        //Checking all columns between left and right column \n        for(int j = c1 + 1; j<c2; j++){\n            int sum = cg[r2][j];\n            if(r1>0)sum-=cg[r1-1][j];\n            if(sum!=checkSum)return false;\n        }\n        int sum = 0;\n        //right diagonal\n        for(int i = r1, j = c1; i<=r2&&j<=c2; i++, j++){\n            sum+=grid[i][j];\n        }\n        if(sum!=checkSum)return false;\n        sum = 0;\n        //left diagonal\n        for(int i = r1, j = c2; i<=r2&&j>=c1; i++, j--){\n            sum+=grid[i][j];\n        }\n        if(sum!=checkSum)return false;\n        return true;\n    }\n    int largestMagicSquare(vector<vector<int>>& grid) {\n        int m = grid.size(), n = grid[0].size();\n        vector<vector<int>>rg, cg;\n        rg = grid;\n        cg = grid;\n        //Generating row prefix sum matrix\n        for(int i = 0; i<m; i++){\n            for(int j = 1; j<n; j++){\n                rg[i][j] += rg[i][j-1];\n            }\n        }\n        //Generating column prefix sum matrix\n        for(int j = 0; j<n; j++){\n            for(int i = 1; i<m; i++){\n                cg[i][j] += cg[i-1][j];\n            }\n        }\n        int ans = 1;\n        //For each cell in the loop, we find the larget magic square with cell {i,j} at the top left corner.\n        for(int i = 0; i<m; i++){\n            for(int j = 0; j<n; j++){\n                if(m-i<=ans)return ans;//The largest square with it's top row as i will have at max a dimension = m-i, and in case are answer is already >= this dimension, we can simply return our answer\n                //Pruning step -->\n                //We only need to consider squares whose sizes our greater than our current answer, so we prune our search by starting from squares having side-lengths greater than ans.\n                int r = i + ans;\n                int c = j + ans;\n                while(r<m&&c<n){\n                    //For a square having it's 4 corners defined by {i,j,r,c}, we calculate the sum of all these 4 sides, and call our isValid function in case these sums are equal\n                    int rsum1 = j>0 ? rg[i][c] - rg[i][j-1] : rg[i][c];//top row sum\n                    int csum1 = i>0 ? cg[r][j] - cg[i-1][j] : cg[r][j];//left column sum\n                    int rsum2 = j>0 ? rg[r][c] - rg[r][j-1] : rg[r][c];//bottom row sum\n                    int csum2 = i>0 ? cg[r][c] - cg[i-1][c] : cg[r][c];//right column sum\n                    if(rsum1==csum2&&rsum2==csum2&&isValid(i,r,j,c,grid, rg, cg, rsum1)){\n                        ans = max(ans, r-i+1);\n                    }\n                    r++;\n                    c++;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Substring Without Repeating Characters",
        "algo_input": "Given a string s, find the length of the longest substring without repeating characters.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\n\nExample 2:\n\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\n\n\nExample 3:\n\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 5 * 104\n\ts consists of English letters, digits, symbols and spaces.\n\n",
        "solution_py": "class Solution:\n    def lengthOfLongestSubstring(self, s: str) -> int:\n        \n        longest_s = ''\n        curr_s = ''\n        for i in s:\n            if i not in curr_s:\n                curr_s += i\n                if len(curr_s) >= len(longest_s):\n                    longest_s = curr_s\n            else:\n                curr_s = curr_s[curr_s.index(i)+1:]+i\n        \n        return len(longest_s)",
        "solution_js": "var lengthOfLongestSubstring = function(s) {\n    // keeps track of the most recent index of each letter.\n    const seen = new Map();\n    // keeps track of the starting index of the current substring.\n    let start = 0;\n    // keeps track of the maximum substring length.\n    let maxLen = 0;\n\n    for(let i = 0; i < s.length; i++) {\n        // if the current char was seen, move the start to (1 + the last index of this char)\n        // max prevents moving backward, 'start' can only move forward\n        if(seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start)\n        seen.set(s[i], i);\n        // maximum of the current substring length and maxLen\n        maxLen = Math.max(i - start + 1, maxLen);\n    }\n\n    return maxLen;\n};",
        "solution_java": "class Solution {\n    public int lengthOfLongestSubstring(String s) {\n        Map<Character, Integer> hash = new HashMap<>();\n        int count = 0;\n        int ans = 0;\n        for(int i=0; i < s.length(); i++){\n            if(hash.containsKey(s.charAt(i))){\n                i = hash.get(s.charAt(i)) + 1;\n                hash.clear();\n                count = 0;\n            }\n            if(!hash.containsKey(s.charAt(i))){\n                hash.put(s.charAt(i), i);\n                count++;\n                ans = Math.max(ans, count);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lengthOfLongestSubstring(string s) {\n        map<char, int> mp;\n        int ans = 1;\n        for(auto ch : s) {\n            if(mp.find(ch) != mp.end()) {\n                while(mp.find(ch) != mp.end()) mp.erase(mp.begin());\n            }\n            mp.insert({ch, 1});\n            if(mp.size() > ans) ans = mp.size();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Patching Array",
        "algo_input": "Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.\n\nReturn the minimum number of patches required.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3], n = 6\nOutput: 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\n\n\nExample 2:\n\nInput: nums = [1,5,10], n = 20\nOutput: 2\nExplanation: The two patches can be [2, 4].\n\n\nExample 3:\n\nInput: nums = [1,2,2], n = 5\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 104\n\tnums is sorted in ascending order.\n\t1 &lt;= n &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def minPatches(self, nums: List[int], n: int) -> int:\n\t#pre-process for convenience\n        nums.append(n+1)\n        t=1\n        sum=1\n        rs=0\n        if nums[0]!=1:\n            nums=[1]+nums\n            rs+=1\n# the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go form left to right to cover upto n\n        while sum<n:\n            if sum<nums[t]-1:\n                sum+=(sum+1)\n                rs+=1\n            else:\n                sum+=nums[t]\n                t+=1\n        return rs",
        "solution_js": "// time complexity:\n// while loop is - o(n) beacuse we can potentially get to n with nums array full of ones and we will pass on each of them\n// in some cases it will hit o(logn) if the nums array is pretty empty\nvar minPatches = function(nums, n) {\n    // nums is sorted so we don't have to sort it\n    let index = 0;\n    let sumCanCreate = 0;\n    let patchCount = 0;\n    while(sumCanCreate < n) {\n        // if we can't create nums[index] or we at the end of nums and can't create n.\n        // we can create nums[index] only if it is lower or equal to sumCanCreate+1.\n        if(sumCanCreate+1 < nums[index] || (index >= nums.length && sumCanCreate+1 < n)) {\n            patchCount++;\n            // because we \"patch\" the next number in the sequence.\n            sumCanCreate += (sumCanCreate+1);\n        // if we can create nums[index].\n        } else {\n            // we can create anything from current sumCanCreate to (sumCanCreate + nums[index]).\n            sumCanCreate += nums[index];\n            index++;\n        }\n    }\n    return patchCount;\n};",
        "solution_java": "class Solution {\n     public int minPatches(int[] nums, int n) {\n        long sum = 0;\n        int count = 0;\n        for (int x : nums) {\n            if (sum >= n) break;\n            while (sum+1 < x && sum < n) { \n                ++count;\n                sum += sum+1;\n            }\n            sum += x;\n        }\n        while (sum < n) {\n            sum += sum+1;\n            ++count;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minPatches(vector<int>& nums, int n) {\n        nums.push_back(0);\n        sort(nums.begin(), nums.end());\n        long sum = 0;\n        int ans = 0;\n        for(int i = 1; i < nums.size(); i++){\n            while((long)nums[i] > (long)(sum + 1)){\n                ans++;\n                sum += (long)(sum + 1);\n                if(sum >= (long)n)\n                    return ans;\n            }\n            sum += nums[i];\n            if(sum >= (long)n)\n                return ans;\n        }\n        while(sum < (long)n){\n            ans++;\n            sum += (long)(sum + 1);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Simple Bank System",
        "algo_input": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i].\n\nExecute all the valid transactions. A transaction is valid if:\n\n\n\tThe given account number(s) are between 1 and n, and\n\tThe amount of money withdrawn or transferred from is less than or equal to the balance of the account.\n\n\nImplement the Bank class:\n\n\n\tBank(long[] balance) Initializes the object with the 0-indexed integer array balance.\n\tboolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise.\n\tboolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise.\n\tboolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]\nOutput\n[null, true, true, true, false, false]\n\nExplanation\nBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10);    // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n                         // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n                         // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20);     // return true, it is valid to deposit $20 to account 5.\n                         // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n                         // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50);   // return false, it is invalid because account 10 does not exist.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == balance.length\n\t1 &lt;= n, account, account1, account2 &lt;= 105\n\t0 &lt;= balance[i], money &lt;= 1012\n\tAt most 104 calls will be made to each function transfer, deposit, withdraw.\n\n",
        "solution_py": "class Bank:\n\n    def __init__(self, bal: List[int]):\n        self.store = bal # storage list\n\n    def transfer(self, a1: int, a2: int, money: int) -> bool:\n        try:\n            # checking if both accounts exist. and if the transaction would be valid\n            if self.store[a1 - 1] >= money and self.store[a2 - 1] >= 0:\n                # performing the transaction\n                self.store[a1 - 1] -= money\n                self.store[a2 - 1] += money\n                return True\n            else:\n                # retrning false on invalid transaction\n                return False\n        except:\n            # returning false when accounts don't exist\n            return False\n\n    def deposit(self, ac: int, mn: int) -> bool:\n        try:\n            # if account exists performing transaction\n            self.store[ac - 1] += mn\n            return True\n        except:\n            # returning false when account doesn't exist\n            return False\n\n    def withdraw(self, ac: int, mn: int) -> bool:\n        try:\n            # checking if transaction is valid\n            if self.store[ac - 1] >= mn:\n                # performing the transaction\n                self.store[ac - 1] -= mn\n                return True\n            else:\n                # returning false in case on invalid transaction\n                return False\n        except:\n            # returning false when account doesn't exist\n            return False",
        "solution_js": "/**\n * @param {number[]} balance\n */\nvar Bank = function(balance) {\n   this.arr = balance; \n};\n\n/** \n * @param {number} account1 \n * @param {number} account2 \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.transfer = function(account1, account2, money) {\n    if (this.arr[account1-1] >= money && this.arr.length >= account1 && this.arr.length >= account2) {\n        this.arr[account1-1] -= money;\n        this.arr[account2-1] += money;\n        return true;\n    }\n    return false;\n};\n\n/** \n * @param {number} account \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.deposit = function(account, money) {\n    if (this.arr.length >= account) {\n        this.arr[account-1] += money;\n        return true;\n    }\n    return false;\n};\n\n/** \n * @param {number} account \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.withdraw = function(account, money) {\n    if (this.arr.length >= account && this.arr[account-1] >= money) {\n        this.arr[account-1] -= money\n        return true;\n    }\n    return false;\n};\n\n/** \n * Your Bank object will be instantiated and called as such:\n * var obj = new Bank(balance)\n * var param_1 = obj.transfer(account1,account2,money)\n * var param_2 = obj.deposit(account,money)\n * var param_3 = obj.withdraw(account,money)\n */",
        "solution_java": "class Bank {\n\n    int N;\n    long[] balance;\n    public Bank(long[] balance) {\n        this.N = balance.length;\n        this.balance = balance;\n    }\n\n    public boolean transfer(int account1, int account2, long money) {\n        if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < money)\n            return false;\n        balance[account1 - 1] -= money;\n        balance[account2 - 1] += money;\n        return true;\n    }\n\n    public boolean deposit(int account, long money) {\n        if(account < 1 || account > N)\n            return false;\n        balance[account - 1] += money;\n        return true;\n    }\n\n    public boolean withdraw(int account, long money) {\n        if(account < 1 || account > N || balance[account - 1] < money)\n            return false;\n        balance[account - 1] -= money;\n        return true;\n    }\n}",
        "solution_c": "class Bank {\npublic:\n\tvector<long long> temp;\n\tint n;\n\tBank(vector<long long>& balance) {\n\t\ttemp=balance;\n\t\tn=balance.size();\n\t}\n\n\tbool transfer(int account1, int account2, long long money) {\n\t\tif(account1<=n && account2<=n && account1>0 && account2>0 && temp[account1-1]>=money){\n\t\t\ttemp[account1-1]-=money;\n\t\t\ttemp[account2-1]+=money;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool deposit(int account, long long money) {\n\t\tif(account>n || account<0)return false;\n\t\ttemp[account-1]+=money;\n\t\treturn true;\n\t}\n\n\tbool withdraw(int account, long long money) {\n\t\tif(account<=n && account>0 && temp[account-1]>=money){\n\t\t\ttemp[account-1]-=money;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n};"
    },
    {
        "title": "Subarray With Elements Greater Than Varying Threshold",
        "algo_input": "You are given an integer array nums and an integer threshold.\n\nFind any subarray of nums of length k such that every element in the subarray is greater than threshold / k.\n\nReturn the size of any such subarray. If there is no such subarray, return -1.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,4,3,1], threshold = 6\nOutput: 3\nExplanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.\nNote that this is the only valid subarray.\n\n\nExample 2:\n\nInput: nums = [6,5,6,5,8], threshold = 7\nOutput: 1\nExplanation: The subarray [8] has a size of 1, and 8 &gt; 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i], threshold &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n        nums = [0] + nums + [0]\n        stack = [0]\n        for i in range(1,len(nums)):\n            while nums[i] < nums[stack[-1]]:\n                tmp = nums[stack.pop()]\n                if tmp > threshold / (i - stack[-1] - 1):\n                    return i - stack[-1] - 1\n            stack.append(i)\n        return -1",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} threshold\n * @return {number}\n */\nvar validSubarraySize = function(nums, threshold) {\n    /*\n    Approach: Use monotonous increasing array\n    */\n    let stack=[];\n    for(let i=0;i<nums.length;i++){\n        let start = i;\n        while(stack.length>0 && stack[stack.length-1][0]>nums[i]){\n            let popped = stack.pop();\n            let min = popped[0];\n            let len = i-popped[1];\n            if(min>threshold/len){\n                return len;\n            }\n            start = popped[1];\n        }\n        stack.push([nums[i],start]);\n    }\n    let end = nums.length-1;\n    for(let i=0;i<stack.length;i++){\n        let len = end - stack[i][1] +1;\n        let min = stack[i][0];\n        if(min>threshold/len){\n            return len;\n        }\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int validSubarraySize(int[] nums, int threshold) {\n        int n = nums.length;\n        int[] next_small = new int[n];\n        int[] prev_small = new int[n];\n        Stack<Integer> stack = new Stack<>();\n        stack.push(0);\n        Arrays.fill(next_small, n);\n        Arrays.fill(prev_small, -1);\n        for(int i=1;i<n;i++){\n            while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){\n                stack.pop();\n            }    \n            if(stack.size()!=0){\n                prev_small[i] = stack.peek();\n            }\n            stack.push(i);\n        }\n        stack = new Stack<>();\n        stack.push(n-1);\n        for(int i=n-2;i>=0;i--){\n            while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){\n                stack.pop();\n            }    \n            if(stack.size()!=0){\n                next_small[i] = stack.peek();\n            }\n            stack.push(i);\n        }\n        for(int i=0;i<n;i++){\n            int len = next_small[i] - prev_small[i] - 1;\n            if(threshold/(double)len < nums[i]){\n                return len;\n            }\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int validSubarraySize(vector<int>& nums, int threshold) {\n        int n = nums.size();\n        vector<long long> lr(n, n), rl(n, -1);\n        \n        vector<int> s;\n        for(int i = 0; i < n; ++i) {\n            while(!s.empty() and nums[i] < nums[s.back()]) {\n                lr[s.back()] = i;\n                s.pop_back();\n            }\n            s.push_back(i);\n        }\n        s.clear();\n        for(int i = n - 1; ~i; --i) {\n            while(!s.empty() and nums[i] < nums[s.back()]) {\n                rl[s.back()] = i;\n                s.pop_back();\n            }\n            s.push_back(i);\n        }\n        \n        for(int i = 0; i < n; ++i) {\n            long long length = lr[i] - rl[i] - 1;\n            if(1LL * nums[i] * length > threshold) return length;\n        }\n        \n        return -1;\n    }\n};\n// please upvote if you like"
    },
    {
        "title": "Increasing Subsequences",
        "algo_input": "Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.\n\nThe given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,6,7,7]\nOutput: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n\n\nExample 2:\n\nInput: nums = [4,4,3,2,1]\nOutput: [[4,4]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 15\n\t-100 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n        def backtracking(nums,path):\n           # to ensure that the base array has at least 2 elements\n            if len(path)>=2:\n                res.add(tuple(path))\n            for i in range(len(nums)):\n                # to ensure that every element to be added is equal or larger than the former\n                if not path or path[-1] <= nums[i]:\n                    backtracking(nums[i+1:],path+[nums[i]])\n\n        res=set()\n        backtracking(nums,[])\n        return res",
        "solution_js": "var findSubsequences = function(nums) {\n    \n    const result = [];\n    const set = new Set();\n    \n    function bt(index=0,ar=[]){\n        if(!set.has(ar.join(\"_\")) && ar.length >=2){\n            set.add(ar.join(\"_\"));\n            result.push(ar);\n        }\n        for(let i =index; i<nums.length; i++){\n            if(nums[i] >= ar[ar.length-1] || ar.length===0){\n                bt(i+1, [...ar, nums[i]]);\n            }\n        }\n    }\n    \n    bt();\n    return result;\n};",
        "solution_java": "class Solution {\n    HashSet<List<Integer>> set;\n    public List<List<Integer>> findSubsequences(int[] nums) {\n        set=new HashSet<>();\n\n        dfs(nums,0,new ArrayList<>());\n\n        List<List<Integer>> ans=new ArrayList<>();\n        if(set.size()>0){\n            ans.addAll(set);\n        }\n        return ans;\n    }\n\n    private void dfs(int nums[], int start, List<Integer> temp){\n        if(start==nums.length) return;\n\n        for(int i=start;i<nums.length;i++){\n            if(temp.size()==0 || temp.get(temp.size()-1)<=nums[i]){\n                temp.add(nums[i]);\n\n                if(temp.size()>=2) set.add(new ArrayList<>(temp));\n\n                dfs(nums,i+1,temp);\n                temp.remove(temp.size()-1);\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    set<vector<int>>ans;\n    void solve(int start, int n, vector<int>&nums, vector<int>&result){\n        if(result.size()>1)ans.insert(result);\n        if(start==n){\n            return;\n        }\n        for(int i=start; i<n; i++){\n            if(result.empty() || result.back()<=nums[i]){\n                result.push_back(nums[i]);\n                solve(i+1, n, nums, result);\n                result.pop_back();\n            }\n        }\n        \n    }\n    vector<vector<int>> findSubsequences(vector<int>& nums) {\n        int n = nums.size();\n        vector<int>result;\n        solve(0, n, nums, result);\n        return vector<vector<int>>(ans.begin(), ans.end());\n    }\n};"
    },
    {
        "title": "Decrypt String from Alphabet to Integer Mapping",
        "algo_input": "You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:\n\n\n\tCharacters ('a' to 'i') are represented by ('1' to '9') respectively.\n\tCharacters ('j' to 'z') are represented by ('10#' to '26#') respectively.\n\n\nReturn the string formed after mapping.\n\nThe test cases are generated so that a unique mapping will always exist.\n\n&nbsp;\nExample 1:\n\nInput: s = \"10#11#12\"\nOutput: \"jkab\"\nExplanation: \"j\" -&gt; \"10#\" , \"k\" -&gt; \"11#\" , \"a\" -&gt; \"1\" , \"b\" -&gt; \"2\".\n\n\nExample 2:\n\nInput: s = \"1326#\"\nOutput: \"acz\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of digits and the '#' letter.\n\ts will be a valid string such that mapping is always possible.\n\n",
        "solution_py": "class Solution:\n    def freqAlphabets(self, s: str) -> str:\n        for i in range(26,0,-1): s = s.replace(str(i)+\"#\"*(i>9),chr(96+i))\n        return s",
        "solution_js": "var freqAlphabets = function(s) {\n  const ans = []\n  for (let i = 0, len = s.length; i < len; ++i) {\n    const c = s.charAt(i)\n    if (c === '#') {\n      ans.length = ans.length - 2\n      ans.push(String.fromCharCode(parseInt(`${s.charAt(i - 2)}${s.charAt(i - 1)}`, 10) + 96))\n      continue\n    }\n    ans.push(String.fromCharCode(+c + 96))\n  }\n  return ans.join('')\n};",
        "solution_java": "class Solution {\n    public String freqAlphabets(String str) {\n        HashMap<String, Character> map = new HashMap<>();\n        int k = 1;\n        for (char ch = 'a'; ch <= 'z'; ch++) {\n            if (ch < 'j')\n                map.put(String.valueOf(k++), ch);\n            else\n                map.put(String.valueOf(k++)+\"#\", ch);\n        }\n        \n        StringBuilder sb = new StringBuilder();\n        int i = str.length() - 1;\n        while (i >= 0) {\n            if (str.charAt(i) == '#') {\n                sb.append(map.get(str.substring(i - 2, i+1)));\n                i -= 3;\n            } else {\n                sb.append(map.get(str.substring(i, i + 1)));\n                i--;\n            }\n        }\n        \n        return sb.reverse().toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tstring freqAlphabets(string s) {\n\t\tint n=s.size(); \n\t\tstring ans=\"\";\n\t\tfor(int i=0;i<n;){\n\t\t\tif(i+2<n && s[i+2]=='#'){\n\t\t\t\tans+= (s[i]-'0')*10 + (s[i+1]-'0') +96;\n\t\t\t\ti+=3;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tans+=(s[i]-'0') + 96;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Equal Rational Numbers",
        "algo_input": "Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\n\nA rational number can be represented using up to three parts: &lt;IntegerPart&gt;, &lt;NonRepeatingPart&gt;, and a &lt;RepeatingPart&gt;. The number will be represented in one of the following three ways:\n\n\n\t&lt;IntegerPart&gt;\n\n\t\n\t\tFor example, 12, 0, and 123.\n\t\n\t\n\t&lt;IntegerPart&gt;&lt;.&gt;&lt;NonRepeatingPart&gt;\n\t\n\t\tFor example, 0.5, 1., 2.12, and 123.0001.\n\t\n\t\n\t&lt;IntegerPart&gt;&lt;.&gt;&lt;NonRepeatingPart&gt;&lt;(&gt;&lt;RepeatingPart&gt;&lt;)&gt;\n\t\n\t\tFor example, 0.1(6), 1.(9), 123.00(1212).\n\t\n\t\n\n\nThe repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n\n\n\t1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"0.(52)\", t = \"0.5(25)\"\nOutput: true\nExplanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\n\n\nExample 2:\n\nInput: s = \"0.1666(6)\", t = \"0.166(66)\"\nOutput: true\n\n\nExample 3:\n\nInput: s = \"0.9(9)\", t = \"1.\"\nOutput: true\nExplanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1.  [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n\n\n&nbsp;\nConstraints:\n\n\n\tEach part consists only of digits.\n\tThe &lt;IntegerPart&gt; does not have leading zeros (except for the zero itself).\n\t1 &lt;= &lt;IntegerPart&gt;.length &lt;= 4\n\t0 &lt;= &lt;NonRepeatingPart&gt;.length &lt;= 4\n\t1 &lt;= &lt;RepeatingPart&gt;.length &lt;= 4\n\n",
        "solution_py": "class Solution:\n    # inspired from:\n    # https://coolconversion.com/math/recurring-decimals-as-a-fraction/\n    # to which we wouldn't have access during interview.\n\n    import typing\n    def isRationalEqual(self, s: str, t: str) -> bool:\n\n        # intuition:\n        # write each numbes as fraction: num / den\n        # then compare the two fractions.\n\n        num1, den1 = self.toFraction(s)\n        num2, den2 = self.toFraction(t)\n\n        return den1 * num2 == den2 * num1\n\n    def toFraction(self, s: str) -> typing.Tuple[int, int]:\n        if \".\" not in s:\n            return int(s), 1\n\n        intp, frac = s.split(\".\")\n        # decimal dot, but no repeating part:\n        # xyz.abc = xyzabc / 1000\n        if \"(\" not in frac:\n            ifrac = int(frac) if len(frac) > 0 else 0\n            num = int(intp) * (10 ** len(frac)) + ifrac\n            den = 10 ** len(frac)\n            return num, den\n\n        # this is for cases like a.b(c)\n        # let n = a.b(c)\n        # then, 10^(len(b+c)) * n = abc.(c)\n        # and 10^(len(b)) * n = ab.(c)\n        # subtract the two, and solve for n:\n        # n = (abc - ab) / (10^len(b + c) - 10^len(b))\n        frac, repfrac = frac.split(\"(\")\n        repfrac = repfrac[:-1]\n\n        iintp = int(intp)\n        ifrac = int(frac) if len(frac) > 0 else 0\n        irep = int(repfrac)\n\n        return (\n            (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac),\n            (10** len(frac+repfrac) - 10 **len(frac))\n        )\n    ```",
        "solution_js": "var isRationalEqual = function(s, t) {\n    return calculate(s) === calculate(t);\n\n    function calculate(v) {\n        let start = v.split('(')[0] || v;\n        let newer = v.split('(')[1] && v.split('(')[1].split(')')[0] || '0';\n\n        start = start.includes('.') ? start : start + '.';\n        newer = newer.padEnd(100, newer);\n\n        return parseFloat(start + newer);\n    }\n};",
        "solution_java": "class Solution {\n\n    private List<Double> ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999);\n\n    public boolean isRationalEqual(String S, String T) {\n        return Math.abs(computeValue(S) - computeValue(T)) < 1e-9;\n    }\n\n    private double computeValue(String s) {\n        if (!s.contains(\"(\")) {\n            return Double.valueOf(s);\n        } else {\n            double intNonRepeatingValue = Double.valueOf(s.substring(0, s.indexOf('(')));\n            int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1;\n            int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1;\n            int repeatingValue = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')')));\n            return intNonRepeatingValue + repeatingValue * Math.pow(0.1, nonRepeatingLength) * ratios.get(repeatingLength);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double toDouble(string s){\n\n       // Strings for each integral, fractional, and repeating part\n       string in=\"\", fn=\"\", rn=\"\";\n\n        int i=0;\n\n        // Integral\n        while(i<s.size() && s[i]!='.'){ in+=s[i]; i++; }\n        // Fractional\n        i++;\n        while(i<s.size() && s[i]!='('){ fn+=s[i]; i++; }\n        // Repeating\n        i++;\n        while(i<s.size() && s[i]!=')'){ rn+=s[i]; i++; }\n\n         // Number\n        double a = 0;\n\n        // Adding integral part\n        if(!in.empty()) a=stoi(in);\n\n        i=0;\n\n        // Adding fractional part\n        while(i<fn.size()){\n            a = a*10 + fn[i] - '0';\n            i++;\n        }\n\n        // Adding repeating part\n        if(i < 8){\n            // If repeatig part isn't there then just add 0s\n            if(rn.size() == 0){\n                while(i <= 8){ a*=10;i++; }\n            }\n\n            else {\n                int j=0;\n                while(i <= 8){\n                    a = a*10 + rn[j%rn.size()] - '0';\n                    j++;\n                    i++;\n                }\n            }\n        }\n        // Return number/10^8\n        return a/10e8;\n    }\n\n    bool isRationalEqual(string s, string t) {\n        // Find absolute differance till 8 digits after decimal and compar if its lesser\n        double ans = abs(toDouble(s) - toDouble(t));\n        return ans < 0.000000002;\n    }\n};"
    },
    {
        "title": "Occurrences After Bigram",
        "algo_input": "Given two strings first and second, consider occurrences in some text of the form \"first second third\", where second comes immediately after first, and third comes immediately after second.\n\nReturn an array of all the words third for each occurrence of \"first second third\".\n\n&nbsp;\nExample 1:\nInput: text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\nOutput: [\"girl\",\"student\"]\nExample 2:\nInput: text = \"we will we will rock you\", first = \"we\", second = \"will\"\nOutput: [\"we\",\"rock\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 1000\n\ttext consists of lowercase English letters and spaces.\n\tAll the words in text a separated by a single space.\n\t1 &lt;= first.length, second.length &lt;= 10\n\tfirst and second consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n        pattern = r\"(?<=\\b\" + first +\" \" + second + r\" )[a-z]*\"\n        txt = re.findall(pattern,text)\n        return txt",
        "solution_js": "var findOcurrences = function(text, first, second) {\n    let result = [];\n    let txt = text.split(' ');\n    for(let i = 0; i<txt.length - 2; i++) {\n        if(txt[i] === first && txt[i+1] === second) result.push(txt[i+2]);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public String[] findOcurrences(String text, String first, String second) {\n        List<String> list = new ArrayList<>();\n        \n        String[] arr = text.split(\" \");\n        \n        for(int i = 0; i < arr.length - 2; i++) {\n            if(arr[i].equals(first) && arr[i + 1].equals(second)) {\n                list.add(arr[i + 2]);\n            }\n        }\n        \n        String[] result = list.toArray(new String[0]);\n        \n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tvector<string> findOcurrences(string text, string first, string second) {\n\t\tvector<string>ans;\n\t\tint i=0;\n\t\twhile(i<text.length())\n\t\t{\n\t\t\tstring word = \"\";\n\t\t\tstring secondWord=\"\";\n\t\t\twhile(i<text.length() && text[i]!=' ')\n\t\t\t{\n\t\t\t\tword = word+text[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif(word == first)\n\t\t\t{\n\t\t\t\tint k = i+1;\n\t\t\t\twhile(k<text.length() && text[k]!=' ')\n\t\t\t\t{\n\t\t\t\t\tsecondWord = secondWord+text[k];\n\t\t\t\t\tk++;\n\t\t\t\t}  \n\t\t\t\tk++;\n\t\t\t\tif(k<text.length() && secondWord==second)\n\t\t\t\t{\n\t\t\t\t\tstring tmp=\"\";\n\t\t\t\t\tint j=k;\n\t\t\t\t\twhile(j<text.length() && text[j]!=' ')\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp = tmp+text[j];\n\t\t\t\t\t\tj++;\n\t\t\t\t\t} \n\n\t\t\t\t\tans.push_back(tmp);\n\t\t\t\t}\n\t\t\t}\n\t\t   i++;\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Find the Minimum Number of Fibonacci Numbers Whose Sum Is K",
        "algo_input": "Given an integer&nbsp;k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.\n\nThe Fibonacci numbers are defined as:\n\n\n\tF1 = 1\n\tF2 = 1\n\tFn = Fn-1 + Fn-2 for n &gt; 2.\n\nIt is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.\n&nbsp;\nExample 1:\n\nInput: k = 7\nOutput: 2 \nExplanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.\n\nExample 2:\n\nInput: k = 10\nOutput: 2 \nExplanation: For k = 10 we can use 2 + 8 = 10.\n\n\nExample 3:\n\nInput: k = 19\nOutput: 3 \nExplanation: For k = 19 we can use 1 + 5 + 13 = 19.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def findMinFibonacciNumbers(self, k: int) -> int:\n        fib_sq = [1, 1]\n        while fib_sq[-1] + fib_sq[-2] <= k:\n            fib_sq.append(fib_sq[-1]+fib_sq[-2])\n        counter = 0\n        for i in range(len(fib_sq)-1, -1, -1):\n            if fib_sq[i] <= k:\n                counter += 1\n                k -= fib_sq[i]\n        return counter",
        "solution_js": "var findMinFibonacciNumbers = function(k) {\n    let sequence = [1, 1], sum = sequence[0] + sequence[1];\n    let i = 2;\n    while (sum <= k) {\n        sequence.push(sum);\n        i++;\n        sum = sequence[i-1]+sequence[i-2];\n    }\n    let j = sequence.length-1, res = 0;\n    while (k) {\n        if (k >= sequence[j]) k -= sequence[j], res++;\n        j--;\n    }\n    return res;\n    // Time Complexity: O(n)\n    // Space Complexity: O(n)\n};",
        "solution_java": "class Solution {\n    public int findMinFibonacciNumbers(int k) {\n        int ans = 0;\n\n        while (k > 0) {\n\t\t\t// Run until solution is reached\n            int fib2prev = 1;\n            int fib1prev = 1;\n            while (fib1prev <= k) {\n\t\t\t\t// Generate Fib values, stop when fib1prev is > k, we have the fib number we want stored in fib2prev\n                int temp = fib2prev + fib1prev;\n                fib2prev = fib1prev;\n                fib1prev = temp;\n            }\n            k -= fib2prev;\n            ans += 1;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    int findMinFibonacciNumbers(int k)\n    {\n        vector<int> fibb;\n        int a = 1;\n        int b = 1;\n        fibb.push_back(a);\n        fibb.push_back(b);\n        int next = a + b;\n\n        while (next <= k)\n        {\n            fibb.push_back(next);\n            a = b;\n            b = next;\n            next = a + b;\n        }\n\n        int res = 0;\n        int j = fibb.size() - 1;\n        while (j >= 0 and k > 0)\n        {\n            if (fibb[j] <= k)\n            {\n                k -= fibb[j];\n                res++;\n            }\n            j--;\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Rotate List",
        "algo_input": "Given the head of a linked&nbsp;list, rotate the list to the right by k places.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [4,5,1,2,3]\n\n\nExample 2:\n\nInput: head = [0,1,2], k = 4\nOutput: [2,0,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 500].\n\t-100 &lt;= Node.val &lt;= 100\n\t0 &lt;= k &lt;= 2 * 109\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n        if k==0 or head is None or head.next is None:\n            return head\n        cur=head\n        n=0\n        while cur is not None:\n            cur=cur.next\n            n+=1\n        k=n-k%n\n        if k==n:\n            return head\n        cur=head\n        prev=None\n        while k>0 and cur is not None:\n            prev=cur\n            cur=cur.next\n            k-=1\n        prev.next=None\n        prev=cur\n        while cur.next is not None:\n            cur=cur.next\n        cur.next=head\n        return prev\n        ",
        "solution_js": "var rotateRight = function(head, k) {\n    if(k === 0 || !head) return head;\n\n    let n = 0;\n    let end = null;\n\n    let iterator = head;\n    while(iterator) {\n        n += 1;\n        end = iterator;\n        iterator = iterator.next;\n    }\n\n    const nodesToRotate = k % n;\n    if(nodesToRotate === 0) return head;\n\n    let breakAt = n - nodesToRotate;\n    iterator = head;\n    while(breakAt - 1 > 0) {\n        iterator = iterator.next;\n        breakAt -= 1;\n    }\n\n    const newHead = iterator.next;\n    iterator.next = null;\n    end.next = head;\n\n    return newHead;\n};",
        "solution_java": "class Solution {\n    public ListNode rotateRight(ListNode head, int k) {\n        if(k<=0 || head==null || head.next==null){\n            return head;\n        }\n        \n        int length=1;\n        ListNode first=head;\n        ListNode curr=head;\n        ListNode node=head;   \n        while(node.next!=null){\n            length++;\n            node=node.next;\n        }\n        \n        if(k==length){\n            return head;\n        }\n        \n        int n=length-(k%length);\n        for(int i=0; i<n-1;i++){\n            curr=curr.next;\n        }\n        \n        node.next=head;  //5-->1\n        head=curr.next;\n        curr.next=null;\n        \n        return head;\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n// like if it is useful to you\n    ListNode* rotateRight(ListNode* head, int k) {\n       if(head == NULL){\n           return head;\n       }\n       vector<int> nums;\n       ListNode *temp = head;\n       while(temp != NULL){\n           nums.push_back(temp->val);\n           temp = temp->next;\n       }\n// if k greater than size;\n        k = k%nums.size();\n// rotating vector\n     reverse(nums.begin(),nums.end());\n     reverse(nums.begin(),nums.begin()+k);\n     reverse(nums.begin()+k,nums.end());\n// replace value of list    \n temp = head;\n     for(int i = 0; i<nums.size();i++){\n         temp->val = nums[i];\n         temp = temp->next;\n     }\n     return head;\n    }\n};"
    },
    {
        "title": "Binary Search Tree Iterator",
        "algo_input": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):\n\n\n\tBSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.\n\tboolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.\n\tint next() Moves the pointer to the right, then returns the number at the pointer.\n\n\nNotice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.\n\nYou may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.\n\n&nbsp;\nExample 1:\n\nInput\n[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\nOutput\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\nExplanation\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next();    // return 3\nbSTIterator.next();    // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 20\nbSTIterator.hasNext(); // return False\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 105].\n\t0 &lt;= Node.val &lt;= 106\n\tAt most 105 calls will be made to hasNext, and next.\n\n\n&nbsp;\nFollow up:\n\n\n\tCould you implement next() and hasNext() to run in average O(1) time and use&nbsp;O(h) memory, where h is the height of the tree?\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass BSTIterator:\n\n    def __init__(self, root: Optional[TreeNode]):\n        self.root=root\n        self.tree=[]#list to store the inorder traversal\n        def inorder(node):\n            if not node:\n                return\n            inorder(node.left)\n            self.tree.append(node.val)\n            inorder(node.right)\n            return\n        inorder(self.root)\n        self.i=0\n        \n\n    def next(self) -> int:\n        self.i+=1\n        return self.tree[self.i-1]\n\n    def hasNext(self) -> bool:\n        return self.i-1<len(self.tree)-1\n\n\n# Your BSTIterator object will be instantiated and called as such:\n# obj = BSTIterator(root)\n# param_1 = obj.next()\n# param_2 = obj.hasNext()",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n */\nvar BSTIterator = function(root) {\n    this.stack = [];\n    this.node = root;\n};\n\n/**\n * @return {number}\n */\nBSTIterator.prototype.next = function() {\n    while (this.node) {\n        this.stack.push(this.node);\n        this.node = this.node.left;\n    }\n    const node = this.stack.pop();\n    this.node = node.right;\n    return node.val;\n};\n\n/**\n * @return {boolean}\n */\nBSTIterator.prototype.hasNext = function() {\n    return this.node || this.stack.length > 0;\n};\n\n/** \n * Your BSTIterator object will be instantiated and called as such:\n * var obj = new BSTIterator(root)\n * var param_1 = obj.next()\n * var param_2 = obj.hasNext()\n */",
        "solution_java": "class BSTIterator {\n\n    TreeNode root;\n    TreeNode current;\n    Stack<TreeNode> st = new Stack<>();\n    public BSTIterator(TreeNode root) {\n        this.root = root;\n        //init(root);\n        current = findLeft(root);\n        //System.out.println(\"Init: stack is: \"+st);\n    }\n\n    public int next() {\n        \n        int val = -1;\n        if(current != null)\n            val = current.val;\n        else\n            return -1;\n        \n        if(current.right != null)\n            current = findLeft(current.right);\n        else if(!st.isEmpty())\n            current = st.pop();\n         else   \n            current = null;\n       // System.out.println(\"next: stack is: \"+st);\n        return val;\n    }\n    \n    public TreeNode findLeft(TreeNode node) {\n        \n        if(node == null)\n            return null;\n        \n        if(node.left != null){\n            TreeNode next = node.left;\n            st.push(node);\n            return findLeft(next);\n        }\n        else\n            return node;\n        \n    }\n    \n    public boolean hasNext() {\n        return current != null;\n    }\n}",
        "solution_c": "//TC O(1) and O(H) Space\n\n//MIMIC inorder\nclass BSTIterator {\npublic:\n    stack<TreeNode*> stk;\n    BSTIterator(TreeNode* root) {\n        pushAll(root);\n         // left is done\n    }\n    \n    int next() {\n        //root handled\n        TreeNode* node = stk.top();\n        int ans = node->val;\n        stk.pop();\n        \n        //right handled\n        pushAll(node->right);\n        \n        return ans;\n        \n    }\n    \n    bool hasNext() {\n        return stk.size() != 0; // stk is empty then no next to show simple\n    }\n    \n    void pushAll(TreeNode* root){\n        //left part - as inorder is like Left left left, once a root is done then check right\n        while(root!= NULL){\n            stk.push(root);\n            root = root->left;\n        }\n        \n    }\n};"
    },
    {
        "title": "Minimum Adjacent Swaps to Reach the Kth Smallest Number",
        "algo_input": "You are given a string num, representing a large integer, and an integer k.\n\nWe call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.\n\n\n\tFor example, when num = \"5489355142\":\n\n\t\n\t\tThe 1st smallest wonderful integer is \"5489355214\".\n\t\tThe 2nd smallest wonderful integer is \"5489355241\".\n\t\tThe 3rd smallest wonderful integer is \"5489355412\".\n\t\tThe 4th smallest wonderful integer is \"5489355421\".\n\t\n\t\n\n\nReturn the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.\n\nThe tests are generated in such a way that kth&nbsp;smallest wonderful integer exists.\n\n&nbsp;\nExample 1:\n\nInput: num = \"5489355142\", k = 4\nOutput: 2\nExplanation: The 4th smallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -&gt; \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -&gt; \"5489355421\"\n\n\nExample 2:\n\nInput: num = \"11112\", k = 4\nOutput: 4\nExplanation: The 4th smallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -&gt; \"11121\"\n- Swap index 2 with index 3: \"11121\" -&gt; \"11211\"\n- Swap index 1 with index 2: \"11211\" -&gt; \"12111\"\n- Swap index 0 with index 1: \"12111\" -&gt; \"21111\"\n\n\nExample 3:\n\nInput: num = \"00123\", k = 1\nOutput: 1\nExplanation: The 1st smallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -&gt; \"00132\"\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= num.length &lt;= 1000\n\t1 &lt;= k &lt;= 1000\n\tnum only consists of digits.\n\n",
        "solution_py": "class Solution:\n    def getMinSwaps(self, num: str, k: int) -> int:\n        num = list(num)\n        orig = num.copy()\n        \n        for _ in range(k): \n            for i in reversed(range(len(num)-1)): \n                if num[i] < num[i+1]: \n                    ii = i+1 \n                    while ii < len(num) and num[i] < num[ii]: ii += 1\n                    num[i], num[ii-1] = num[ii-1], num[i]\n                    lo, hi = i+1, len(num)-1\n                    while lo < hi: \n                        num[lo], num[hi] = num[hi], num[lo]\n                        lo += 1\n                        hi -= 1\n                    break \n        \n        ans = 0\n        for i in range(len(num)): \n            ii = i\n            while orig[i] != num[i]: \n                ans += 1\n                ii += 1\n                num[i], num[ii] = num[ii], num[i]\n        return ans ",
        "solution_js": "var getMinSwaps = function(num, k) {\n    \n    const digits = [...num]\n    const len = digits.length;\n    \n    // helper function to swap elements in digits in place\n    const swap = (i, j) => [digits[i], digits[j]] = [digits[j], digits[i]]\n    \n    // helper function to reverse elements in digits from i to the end of digits\n    const reverse = (i) => {\n        for (let j = len - 1; i < j; ++i && --j) {\n            swap(i, j);\n        }\n    }\n    \n    // helper to get the next smallest permutation for digits\n    const nextPermutation = () => {\n        // from right to left, find the first decreasing index\n        // in digits and store it as i\n        let i = len - 2;\n        while (digits[i] >= digits[i + 1]) {\n            i--;\n        }\n        \n        // from right to left, find the first index in digits\n        // that is greater than element at i\n        let j = len - 1;\n        while (digits[j] <= digits[i]) {\n            j--;\n        }\n        \n        // swap the 2 elements at i and j\n        swap(i, j);\n        // reverse all elements after i because we know that\n        // all elements after i are in ascending order\n        // from right to left\n        reverse(i + 1);\n    }\n    \n    // find the next permutation k times\n    for (let i = 0; i < k; i++) {\n        nextPermutation();\n    }\n\n    // find out how many swaps it will take to get to the\n    // kth permutation by finding out how many swaps\n    // it takes to put digits back to its original state\n    let numSwaps = 0;\n    for (let i = 0; i < len; i++) {\n        let j = i;\n        // find the first element in digits to matches\n        // num[i] and hold its place at j\n        while (num[i] !== digits[j]) {\n            j++;\n        }\n        \n        // move the element at j to i while counting the\n        // number of swaps\n        while (i < j) {\n            swap(j, j - 1);\n            numSwaps++;\n            j--;\n        }\n    }\n    return numSwaps;\n};",
        "solution_java": "class Solution {\n    public int getMinSwaps(String num, int k) {\n        int[] nums=new int[num.length()];\n        int[] org=new int[num.length()];\n\n        for(int i=0;i<num.length();i++){\n            int e=Character.getNumericValue(num.charAt(i));\n            nums[i]=e;\n            org[i]=e;\n        }\n\n        while(k!=0){\n        nextPermutation(nums);\n         k--;\n        }\n\n        int ans=0;\n\n        for(int i=0;i<nums.length;i++){\n\n            if(nums[i]!=org[i]){\n                int j=0;\n                for(j=i+1;j<nums.length;j++)\n                    if(org[j]==nums[i])\n                        break;\n\n                while(j>0 && j!=i){\n                    swap(org,j,j-1);\n                    ans++;\n                    j--;\n                }\n\n            }\n\n    }\n\n      return ans;\n\n    }\n\npublic void nextPermutation(int[] nums) {\n\n        if(nums.length<=1)\n            return;\n\n        int j=nums.length-2;\n       while(j>=0 && nums[j]>=nums[j+1])\n           j--;\n\n        if(j>=0){\n        int k=nums.length-1;\n        while(nums[j]>=nums[k])\n            k--;\n\n        swap(nums,j,k);\n\n        }\n\n        reverse(nums,j+1,nums.length-1);\n\n    }\n\n    public void swap(int[] nums,int j,int k){\n        int temp=nums[j];\n            nums[j]=nums[k];\n            nums[k]=temp;\n    }\n\n    public void reverse(int[] nums,int i,int j){\n        while(i<=j){\n            swap(nums,i,j);\n                i++;\n                j--;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // GREEDY APPROACH\n    // min steps to make strings equal\n\n    int minSteps(string s1, string s2) {\n        int size = s1.length();\n        int i = 0, j = 0;\n        int result = 0;\n\n        while (i < size) {\n            j = i;\n            while (s1[j] != s2[i]) j++;\n\n            while (i < j) {\n                swap(s1[j], s1[j-1]);\n                j--;\n                result++;\n            }\n            i++;\n        }\n        return result;\n    }\n\n    int getMinSwaps(string num, int k) {\n        string original = num;\n\n        while(k--) {\n            next_permutation(num.begin(), num.end());\n        }\n\n        return minSteps(original, num);\n    }\n};"
    },
    {
        "title": "Height Checker",
        "algo_input": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.\n\nYou are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).\n\nReturn the number of indices where heights[i] != expected[i].\n\n&nbsp;\nExample 1:\n\nInput: heights = [1,1,4,2,1,3]\nOutput: 3\nExplanation: \nheights:  [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.\n\n\nExample 2:\n\nInput: heights = [5,1,2,3,4]\nOutput: 5\nExplanation:\nheights:  [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.\n\n\nExample 3:\n\nInput: heights = [1,2,3,4,5]\nOutput: 0\nExplanation:\nheights:  [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= heights.length &lt;= 100\n\t1 &lt;= heights[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def heightChecker(self, heights: List[int]) -> int:\n        heightssort = sorted(heights)\n        import numpy as np\n        diff = list(np.array(heightssort) - np.array(heights))\n        return (len(diff) - diff.count(0))",
        "solution_js": "var heightChecker = function(heights) {\n  let count = 0;\n  const orderedHeights = [...heights].sort((a, b) => a-b)\n\n  for (let i = 0; i < heights.length; i++) {\n    heights[i] !== orderedHeights[i] ? count++ : null\n  }\n\n  return count\n};",
        "solution_java": "class Solution {\n    public int heightChecker(int[] heights) {\n\n      int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length);\n\n      Arrays.sort(dupheights);\n      int count = 0;\n\n      for(int i=0 ; i< heights.length ; i++){\n\n        if(heights[i] != dupheights[i]){\n          count++;\n        }\n\n      }\n\n      return count;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int heightChecker(vector<int>& heights) {\n        vector<int> expected=heights;\n        int count=0;\n        sort(expected.begin(),expected.end());\n        for(int i=0;i<heights.size();i++){\n            if(heights[i]!=expected[i])\n            count++;\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Additive Number",
        "algo_input": "An additive number is a string whose digits can form an additive sequence.\n\nA valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.\n\nGiven a string containing only digits, return true if it is an additive number or false otherwise.\n\nNote: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.\n\n&nbsp;\nExample 1:\n\nInput: \"112358\"\nOutput: true\nExplanation: \nThe digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n\n\nExample 2:\n\nInput: \"199100199\"\nOutput: true\nExplanation: \nThe additive sequence is: 1, 99, 100, 199.&nbsp;\n1 + 99 = 100, 99 + 100 = 199\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 35\n\tnum consists only of digits.\n\n\n&nbsp;\nFollow up: How would you handle overflow for very large input integers?\n",
        "solution_py": "class Solution:\ndef isAdditiveNumber(self, num: str) -> bool:\n    \n    def isadditive(num1,num2,st):\n        if len(st) == 0:\n            return True\n        num3 = str(num1+num2)\n        l = len(num3)\n        return num3 == st[:l] and isadditive(num2,int(num3),st[l:])\n    \n    for i in range(1,len(num)-1):\n        for j in range(i+1,len(num)):\n            if num [0] == \"0\" and i != 1:\n                break\n            if num[i] == \"0\" and i+1 != j:\n                break\n           \n            if isadditive(int(num[:i]),int(num[i:j]),num[j:]):\n                \n                return True\n    return False",
        "solution_js": "const getNum = (str, i, j) => {\n    str = str.slice(i, j);\n    if(str[0] == '0' && str.length > 1) return -1000\n    return Number(str);\n}\n\nvar isAdditiveNumber = function(num) {\n    // i = 3 say and make theory and proof that\n    const len = num.length;\n    for(let b = 2; b < len; b++) {\n        for(let i = 0; i < b - 1; i++) {\n            for(let j = i + 1; j < b; j++) {\n                let v1 = getNum(num,0, i + 1);\n                let v2 = getNum(num,i + 1, j + 1);\n                let v3 = getNum(num,j + 1, b + 1);\n                if(v1 + v2 == v3) {\n                    // test hypothesis;\n                    // from b start checking if string persist behaviour\n                    let p = num.slice(0, b + 1);\n                    while(p.length <= len) {\n                        let sum = v2 + v3;\n                        p += sum;\n                        v2 = v3;\n                        v3 = sum;\n                    }\n                    if(p.slice(0, len) == num) {\n                        return true;\n                    }\n                }\n            }\n        }\n    }\n    return false;\n};",
        "solution_java": "class Solution {\n\n    public boolean isAdditiveNumber(String num) {\n        return backtrack(num, 0, 0, 0, 0);\n    }\n    \n    public boolean backtrack(String num, int idx, long sum, long prev, int length){\n        if(idx == num.length()){\n            return length >= 3;\n        }\n        \n        long currLong = 0;\n        \n        for(int i = idx; i < num.length(); i++){\n            //make sure it won't start with 0\n            if(i > idx && num.charAt(idx) == '0') break;\n            currLong = currLong * 10 + num.charAt(i) - '0';\n            \n            if(length >= 2){\n                if(sum < currLong){\n                    //currLong is greater than sum of previous 2 numbers\n                    break;\n                }else if(sum > currLong){\n                    //currLong is smaller than sum of previous 2 numbers\n                    continue;\n                }\n            }\n            //currLong == sum of previous 2 numbers\n            if(backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true){\n                return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    bool isAdditiveNumber(string num)\n    {\n        vector<string> adds;\n        return backtrack(num, 0, adds);\n    }\n\nprivate:\n    bool backtrack(string num, int start, vector<string> &adds)\n    {\n        if (start >= num.size() && adds.size() >= 3)\n            return true;\n\n        int maxSize = num[start] == '0' ? 1 : num.size() - start;\n        for (int i = 1; i <= maxSize; i++)\n        {\n            string current = num.substr(start, i);\n\n            if (adds.size() >= 2)\n            {\n                string num1 = adds[adds.size() - 1], num2 = adds[adds.size() - 2];\n                string sum = add(num1, num2);\n                if (sum != current)\n                    continue;\n            }\n\n            adds.push_back(current);\n            if (backtrack(num, start + i, adds))\n                return true;\n            adds.pop_back();\n        }\n        return false;\n    }\n\n    string add(string num1, string num2)\n    {\n        string sum;\n        int i1 = num1.size() - 1, i2 = num2.size() - 1, carry = 0;\n        while (i1 >= 0 || i2 >= 0)\n        {\n            int current = carry + (i1 >= 0 ? (num1[i1--] - '0') : 0) + (i2 >= 0 ? (num2[i2--] - '0') : 0);\n            carry = current / 10;\n            sum.push_back(current % 10 + '0');\n        }\n        if (carry)\n            sum.push_back(carry + '0');\n        reverse(begin(sum), end(sum));\n        return sum;\n    }\n};"
    },
    {
        "title": "Generate a String With Characters That Have Odd Counts",
        "algo_input": "Given an&nbsp;integer n, return a string with n&nbsp;characters such that each character in such string occurs an odd number of times.\n\nThe returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. &nbsp;\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: \"pppz\"\nExplanation: \"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".\n\n\nExample 2:\n\nInput: n = 2\nOutput: \"xy\"\nExplanation: \"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".\n\n\nExample 3:\n\nInput: n = 7\nOutput: \"holasss\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 500\n\n",
        "solution_py": "class Solution:\n    def generateTheString(self, n: int) -> str:\n        alpha = \"abcdefghijklmnopqrstuvwxyz\"\n        res=\"\"\n        while n>0:\n            curr, alpha = alpha[0], alpha[1:]\n            if n%2:\n                res += curr*n\n                n-=n\n            else: \n                res += curr*(n-1)\n                n-=n-1\n        return res",
        "solution_js": "// C++ Code\nclass Solution {\npublic:\n    string generateTheString(int n) {\n        string res = \"\";\n        if (n%2 == 0)\n        {\n            res += 'a';\n            n -= 1;\n        }\n        for (int i=0;i < n;i++)\n            res += 'k';\n        return res;\n    }\n};\n\n\n// JavaScript Code\nvar generateTheString = function(n) {\n    let ans = [];\n    let state = n % 2 === 0 ? true : false;\n    \n    if(!state){\n        for(let i=0;i<n;i++){\n            ans.push('a');\n        }\n    }else{\n        for(let i=0;i<n-1;i++){\n            ans.push('a');\n        }\n        ans.push('k');\n    }\n   \n    return ans.join('');\n};",
        "solution_java": "class Solution {\n    public String generateTheString(int n) {\n        String s = \"\";\n        String string =\"a\";\n        for (int i = 0; i < n-1; i++)\n            s += string;\n        if(n%2==0)\n        return s+\"b\";\n        return s+\"a\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string generateTheString(int n) {\n        string s=\"\";\n        if(n%2!=0){\n            for(int i=0;i<n;i++)\n                s+=\"a\";\n        }\n        else{\n            for(int i=0;i<n-1;i++)\n                s+=\"a\";\n            s+=\"b\";\n        }\n        return s;\n    }\n};"
    },
    {
        "title": "Find the Minimum and Maximum Number of Nodes Between Critical Points",
        "algo_input": "A critical point in a linked list is defined as either a local maxima or a local minima.\n\nA node is a local maxima if the current node has a value strictly greater than the previous node and the next node.\n\nA node is a local minima if the current node has a value strictly smaller than the previous node and the next node.\n\nNote that a node can only be a local maxima/minima if there exists both a previous node and a next node.\n\nGiven a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any&nbsp;two distinct critical points and maxDistance is the maximum distance between any&nbsp;two distinct critical points. If there are fewer than two critical points, return [-1, -1].\n\n&nbsp;\nExample 1:\n\nInput: head = [3,1]\nOutput: [-1,-1]\nExplanation: There are no critical points in [3,1].\n\n\nExample 2:\n\nInput: head = [5,3,1,2,5,1,2]\nOutput: [1,3]\nExplanation: There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.\n\n\nExample 3:\n\nInput: head = [1,3,2,2,3,2,2,2,7]\nOutput: [3,3]\nExplanation: There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [2, 105].\n\t1 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n        idx, i = [], 1\n        prev, cur = head, head.next\n        while cur and cur.next:\n            if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n                idx.append(i)\n            prev = cur\n            cur = cur.next\n            i += 1\n\n        if len(idx) < 2:\n            return [-1, -1]\n        \n        minDist = min(j - i for i, j in pairwise(idx))\n        maxDist = idx[-1] - idx[0]\n\n        return [minDist, maxDist]",
        "solution_js": "var nodesBetweenCriticalPoints = function(head) {\n    const MAX = Number.MAX_SAFE_INTEGER;\n    const MIN = Number.MIN_SAFE_INTEGER;\n    \n    let currNode = head.next;\n    let prevVal = head.val;\n    \n    let minIdx = MAX;\n    let maxIdx = MIN;\n    \n    let minDist = MAX;\n    let maxDist = MIN;\n    \n    for (let i = 1; currNode.next != null; ++i) {\n        const currVal = currNode.val;\n        const nextNode = currNode.next;\n        const nextVal = nextNode.val;\n        \n        // Triggers when we have either a maxima or a minima\n        if ((prevVal < currVal && currVal > nextVal) || (prevVal > currVal && currVal < nextVal)) {\n            if (maxIdx != MIN) minDist = Math.min(minDist, i - maxIdx);\n            if (minIdx != MAX) maxDist = Math.max(maxDist, i - minIdx);\n            \n            if (minIdx == MAX) minIdx = i;\n            maxIdx = i;\n        }\n        \n        prevVal = currVal;\n        currNode = nextNode;\n    }\n\n    const minRes = minDist === MAX ? -1 : minDist;\n    const maxRes = maxDist === MIN ? -1 : maxDist;\n    \n    return [minRes, maxRes];\n};",
        "solution_java": "class Solution {\n    public int[] nodesBetweenCriticalPoints(ListNode head) {\n        int res[]=new int[]{-1,-1};\n        if(head==null||head.next==null||head.next.next==null) return res;\n        int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1;\n        ListNode prev=head,ptr=head.next;\n        int idx=1,minD=Integer.MAX_VALUE;\n        while(ptr!=null&&ptr.next!=null){\n            if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val<prev.val&&ptr.val<ptr.next.val)){\n                if(idx<minidx) minidx=idx;\n                lastidx=curridx;\n                curridx=idx;\n                if(lastidx!=-1&&curridx-lastidx<minD) minD=curridx-lastidx;\n            }\n            prev=ptr;\n            ptr=ptr.next;\n            idx++;\n        }\n        if(lastidx==-1) return res;\n        else{\n            res[0]=minD;\n            res[1]=curridx-minidx;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n        if(!head or !head->next or !head->next->next) return {-1,-1};\n        int mini = 1e9;\n        int prevInd = -1e9;\n        int currInd = 0;\n        int start = -1e9;\n        int prev = head->val;\n        head = head->next;\n\n        while(head->next){\n            if(prev<head->val and head->next->val<head->val){\n                mini = min(mini,currInd-prevInd);\n                prevInd = currInd;\n                if(start==-1e9) start = currInd;\n            }\n            if(prev>head->val and head->next->val>head->val){\n                mini = min(mini,currInd-prevInd);\n                prevInd = currInd;\n                if(start==-1e9) start = currInd;\n            }\n            prev = head->val;\n            head = head->next;\n            currInd++;\n        }\n\n        if(start!=prevInd) return {mini,prevInd-start};\n        return {-1,-1};\n    }\n};"
    },
    {
        "title": "Longest Palindromic Substring",
        "algo_input": "Given a string s, return the longest palindromic substring in s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"babad\"\nOutput: \"bab\"\nExplanation: \"aba\" is also a valid answer.\n\n\nExample 2:\n\nInput: s = \"cbbd\"\nOutput: \"bb\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consist of only digits and English letters.\n\n",
        "solution_py": "class Solution:\n    def longestPalindrome(self, s: str) -> str:\n        res = \"\"\n        for i in range(len(s)):\n            left, right = i - 1, i + 1\n\n            while (right < len(s) and s[right] == s[i]):\n                right += 1\n\n            while (0 <= left < right < len(s) and s[left] == s[right]):\n                left, right = left - 1, right + 1\n\n            res = s[left+1:right] if right - left-1 > len(res) else res\n        return res",
        "solution_js": "I solve the problem distinguishing two different cases.\nFirst I consider the case when the length of the palindrome to be found is odd (there is a center). \n\tI then expand the search to left and right from the possible found center.\nThen I consider the case when the length of the palindrome to be found is pair (there is no center/middle).\n\tI then expand the search to left and right from the possible palindrome having the form \"xx\".\n```/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n    let longestP = s[0];\n    let palindrome = \"\";\n    if(s.length === 1 ) return s;\n    \n    //the length of the palindrome is odd\n    for(let index = 1; index < s.length-1; index++){\n        if(s[index - 1] === s[index + 1]){\n            palindrome = s[index - 1] + s[index] + s[index + 1];\n            for(let k = 1; index - 1 - k > -1 && index + 1 + k < s.length; k++){\n                if(s[index - 1 - k] === s[index + 1 + k]){\n                    palindrome = s[index - 1 - k] + palindrome + s[index + 1 + k];\n                }\n                else{\n                    break;\n                }\n            }\n        }\n        if (palindrome.length > longestP.length){\n            longestP = palindrome;\n        }\n        palindrome = \"\";\n    }\n    \n    //the length of the palindrome is pair\n    for(let index = 0; index < s.length-1; index++){\n        if(s[index] === s[index + 1]){\n            palindrome = s[index] + s[index + 1];\n            for(let k = 1; (index - k > -1) && (index + 1 + k < s.length); k++){\n                if(s[index - k] === s[index + 1 + k]){\n                    palindrome = s[index - k] + palindrome + s[index + 1 + k];\n                }\n                else{\n                    break;\n                }\n            }\n        }\n        if (palindrome.length > longestP.length){\n            longestP = palindrome;\n        }\n        palindrome = \"\";\n    }\n    return longestP;\n};`",
        "solution_java": "class Solution {\n    String max = \"\";\n    \n    private void checkPalindrome(String s, int l, int r) {\n        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {\n            if (r - l >= max.length()) {\n                max = s.substring(l, r + 1);\n            }   \n\n            l--;\n            r++;\n        }\n    }\n    \n    public String longestPalindrome(String s) {\n        for (int i = 0; i < s.length(); i++) {\n            checkPalindrome(s, i, i);\n            checkPalindrome(s, i, i + 1);   \n        }\n        \n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string longestPalindrome(string s) {\n        if(s.size() <= 1) return s;\n\n        string longest = \"\";\n\n        for (int i = 0; i < s.size(); i++) {\n            string sub1 = expand(s, i, i+1);\n            string sub2 = expand(s, i, i);\n\n            string sub3 = sub1.size() > sub2.size() ? sub1 : sub2;\n\n            if(sub3.size() > longest.size()) {\n                longest = sub3;\n            }\n        }\n        return longest;\n    }\n\n    string expand(string s, int i, int j) {\n        while(j < s.size() && i >= 0 && s[i] == s[j]) {\n            i--;\n            j++;\n        }\n        // Add 1 to i and subtract 1 from j because the range is expanded by 1 on each side before it ends\n        return s.substr(i+1, j-i-1);\n    }\n};"
    },
    {
        "title": "String Matching in an Array",
        "algo_input": "Given an array of string words. Return all strings in words which is substring of another word in any order.&nbsp;\n\nString words[i] is substring of words[j],&nbsp;if&nbsp;can be obtained removing some characters to left and/or right side of words[j].\n\n&nbsp;\nExample 1:\n\nInput: words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput: [\"as\",\"hero\"]\nExplanation: \"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.\n\n\nExample 2:\n\nInput: words = [\"leetcode\",\"et\",\"code\"]\nOutput: [\"et\",\"code\"]\nExplanation: \"et\", \"code\" are substring of \"leetcode\".\n\n\nExample 3:\n\nInput: words = [\"blue\",\"green\",\"bu\"]\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 30\n\twords[i] contains only lowercase English letters.\n\tIt's guaranteed&nbsp;that words[i]&nbsp;will be unique.\n\n",
        "solution_py": "class Solution:\n    def stringMatching(self, words: List[str]) -> List[str]:\n        ans=set()\n        l=len(words)\n        for i in range(l):\n            for j in range(l):\n                if (words[i] in words[j]) & (i!=j):\n                    ans.add(words[i])\n        return ans",
        "solution_js": "var stringMatching = function(words) {\n    let res = [];\n\n    for (let i = 0; i < words.length; i++) {\n\n        for (let j = 0; j < words.length; j++) {\n            if (j === i) continue;\n\n            if (words[j].includes(words[i])) {\n                res.push(words[i]);\n                break;\n            }\n\n        }\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<String> stringMatching(String[] words) {\n        List<String>ans = new ArrayList<>();\n        for(int i=0; i<words.length; i++){\n            String s = words[i];\n            for(int j=0; j<words.length; j++){\n                if(i == j){\n                    continue;\n                }\n                if(words[j].indexOf(s) >= 0){\n                    ans.add(s);\n                    break;\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> stringMatching(vector<string>& words) {\n        vector<string> res; //output\n\n        for(int i = 0 ; i < words.size(); i++)\n        {\n            for(int j = 0; j < words.size(); j++)\n            {\n                if(i != j && words[j].find(words[i]) != -1)\n                {\n                    if(!count(res.begin(),res.end(), words[i])) //if vector result does not include this string, push it to vector\n                        res.push_back(words[i]);\n                    else\n                        continue; //if vector result includes this string, ignore\n                }\n            }\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Uncrossed Lines",
        "algo_input": "You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.\n\nWe may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:\n\n\n\tnums1[i] == nums2[j], and\n\tthe line we draw does not intersect any other connecting (non-horizontal) line.\n\n\nNote that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).\n\nReturn the maximum number of connecting lines we can draw in this way.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,4,2], nums2 = [1,2,4]\nOutput: 2\nExplanation: We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\n\n\nExample 2:\n\nInput: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput: 3\n\n\nExample 3:\n\nInput: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 500\n\t1 &lt;= nums1[i], nums2[j] &lt;= 2000\n\n",
        "solution_py": "class Solution:\n    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n        \n        @lru_cache(None)\n        def dp(a,b):\n            if a>=len(nums1) or b>=len(nums2): return 0\n            if nums1[a]==nums2[b]: return 1+dp(a+1,b+1)\n            else: return max(dp(a+1,b),dp(a,b+1))\n        \n        return dp(0,0)",
        "solution_js": "/** https://leetcode.com/problems/uncrossed-lines/\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxUncrossedLines = function(nums1, nums2) {\n  // Array to hold the combination of connected numbers\n  let dp = [];\n  \n  // We look up the connected numbers with matrix\n  for (let i=0;i< nums1.length;i++){\n    for (let j=0;j< nums2.length;j++){\n      if (nums1[i]===nums2[j]){\n        dp.push([i,j]);\n      }\n    }\n  }\n  \n  // Only 0 or 1 connected numbers found, return\n  if(dp.length <=1){\n    return dp.length;\n  }\n  \n  // Array to count how many connected numbers in the matrix without crossing\n  let count=Array(dp.length).fill(1);\n  let out = count[0];\n  \n  // Count from the last connected numbers, for each connected number, count how many other connected numbers in front of it that will not crossed with current\n  for (let i=dp.length-2;i>=0;i--){\n    for (let j=i+1;j<dp.length;j++){\n      if (dp[i][0] < dp[j][0]&&\n          dp[i][1] < dp[j][1]){\n            count[i] = Math.max(count[i],count[j]+1);\n            out = Math.max(out, count[i]);\n      }\n    }\n  }\n  \n  return out;\n};",
        "solution_java": "class Solution {\n    public int maxUncrossedLines(int[] nums1, int[] nums2) {\n        int m = nums1.length;\n        int n = nums2.length;\n        int[][] dp = new int[m + 1][n + 1];\n        for(int i = 1; i <= m; i ++){\n            for(int j = 1; j <= n; j ++){\n                if(nums1[i - 1] == nums2[j - 1])\n                    dp[i][j] = dp[i - 1][j - 1] + 1;\n                else\n                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n            }\n        }\n        return dp[m][n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(int n1,int n2,vector<int>& nums1, vector<int>& nums2,vector<vector<int>> &dp)\n    {\n        if(n1<0 || n2<0)\n            return 0;\n        \n        if(dp[n1][n2]!=-1)\n            return dp[n1][n2];\n        \n        if(nums1[n1]==nums2[n2])\n            return dp[n1][n2]=1+solve(n1-1,n2-1,nums1,nums2,dp);\n        \n        return dp[n1][n2]=max(solve(n1-1,n2,nums1,nums2,dp),solve(n1,n2-1,nums1,nums2,dp));\n    }\n    \n    int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {\n        int n1=nums1.size(),n2=nums2.size();\n        vector<vector<int>> dp(n1+1,vector<int>(n2+1,-1));\n        \n        return solve(n1-1,n2-1,nums1,nums2,dp);\n    }\n};"
    },
    {
        "title": "Minimum Increment to Make Array Unique",
        "algo_input": "You are given an integer array nums. In one move, you can pick an index i where 0 &lt;= i &lt; nums.length and increment nums[i] by 1.\n\nReturn the minimum number of moves to make every value in nums unique.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,2]\nOutput: 1\nExplanation: After 1 move, the array could be [1, 2, 3].\n\n\nExample 2:\n\nInput: nums = [3,2,1,2,1,7]\nOutput: 6\nExplanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minIncrementForUnique(self, nums: List[int]) -> int:\n        nums.sort()\n        c=0\n        i=1\n        num=[]\n        \n        while i<len(nums):\n            if nums[i]<=nums[i-1]:\n                a=nums[i-1]+1\n                c+=(a-nums[i])\n                nums[i]=a\n            i+=1\n        return c\n    ",
        "solution_js": "var minIncrementForUnique = function(nums) {\n  let ans = 0, arr = nums.sort((a, b) => a - b);\n\n  for (let i = 0; i < arr.length; i++) {\n    if (arr[i] === arr[i + 1]) {\n      arr[i + 1]++;\n      ans++;\n    }\n    else if (arr[i] > arr[i + 1]) {\n      if(arr[i] - arr[i - 1] === 1){\n        ans += arr[i] - arr[i + 1] + 1\n        arr[i + 1] += arr[i] - arr[i + 1] + 1;\n      }\n    }\n  }\n\n  return ans;\n};",
        "solution_java": "class Solution {\n    public int minIncrementForUnique(int[] nums) {\n        \n        //Approach - 1 : Using a Count array\n        \n        // TC : O(N)\n        // SC : O(N)\n        \n        int max = 0;\n        for(int i : nums)\n            max = Math.max(max, i);\n        \n        int count[] = new int[nums.length + max];\n\t\t\n        for(int c : nums)\n            count[c]++;\n\t\t\t\n        int answer = 0, choosen = 0;\n\t\tint len = count.length;\n\t\t\n        for(int i = 0; i< len; i++)\n        {\n            if(count[i] >= 2)\n            {\n                choosen += count[i] - 1;\n                answer -= i * (count[i] - 1);\n            }\n            else if(choosen > 0 && count[i] == 0)\n            {\n                answer += i;\n                choosen--;\n            }\n        }\n\t\t\n        return answer;\n        \n        \n        //Approach - 2:\n        \n        // TC : O(nlogn)\n        // SC : O(1)\n        \n        Arrays.sort(nums);\n        int answer = 0;\n        for(int i=1; i<nums.length; i++)\n        {\n            if(nums[i-1] >= nums[i]){\n                answer += nums[i-1]- nums[i] +1;\n                nums[i] = nums[i-1] + 1; \n            }\n        }\n        return answer;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minIncrementForUnique(vector<int>& nums) {\n        int minElePossible=0,ans=0;\n        sort(nums.begin(),nums.end());\n        for(int i=0;i<nums.size();i++){\n            if(nums[i]<minElePossible){\n                ans+=minElePossible-nums[i];\n                nums[i]+=minElePossible-nums[i];\n            }\n            minElePossible=nums[i]+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Peak Index in a Mountain Array",
        "algo_input": "An array arr a mountain if the following properties hold:\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\nGiven a mountain array arr, return the index i such that arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1].\n\nYou must solve it in O(log(arr.length)) time complexity.\n\n&nbsp;\nExample 1:\n\nInput: arr = [0,1,0]\nOutput: 1\n\n\nExample 2:\n\nInput: arr = [0,2,1,0]\nOutput: 1\n\n\nExample 3:\n\nInput: arr = [0,10,5,2]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 105\n\t0 &lt;= arr[i] &lt;= 106\n\tarr is guaranteed to be a mountain array.\n\n",
        "solution_py": "class Solution:\n    def peakIndexInMountainArray(self, arr: List[int]) -> int:\n        beg = 0\n        end = len(arr)-1\n        \n        while beg <= end:\n            mid = (beg+end)//2\n            if arr[mid] < arr[mid+1]:\n                beg = mid +1\n            elif arr[mid] > arr[mid+1]:\n                end = mid -1\n        return beg",
        "solution_js": "var peakIndexInMountainArray = function(arr) {\n\n    //lets assume we have peak it divides array in two parts\n    // first part is increasing order , second part is decreasing\n    // when we find the middle we'll compare arr[middle] > arr[middle+1], it means\n    //we can only find max in first part of arr (increasing part) else second part.\n    //there will be point where start === end that is our peak\n    let start = 0;\n    let end = arr.length -1;\n    while(start < end){\n        let mid = parseInt(start + (end - start)/2)\n        if( arr[mid] > arr[mid + 1]){\n            end = mid;\n        }else {\n            start = mid +1;\n        }\n    }\n\n    return start;\n\n};",
        "solution_java": "class Solution {\npublic int peakIndexInMountainArray(int[] arr) {\n\n    int start = 0;\n    int end = arr.length - 1;\n\n    while( start < end){\n        int mid = start + (end - start)/2;\n        // if mid < mid next\n        if(arr[mid] < arr[mid + 1]){\n            start = mid + 1;\n        }\n        // otherwise it can either peak element or greater element\n        else{\n            end = mid;\n        }\n    }\n    return start; // or we can return end also, bcz both will be on same value at the time, that's why loop breaks here.\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int peakIndexInMountainArray(vector<int>& arr) {\n        return max_element(arr.begin(), arr.end()) - arr.begin();\n    }\n};"
    },
    {
        "title": "Count Unhappy Friends",
        "algo_input": "You are given a list of&nbsp;preferences&nbsp;for&nbsp;n&nbsp;friends, where n is always even.\n\nFor each person i,&nbsp;preferences[i]&nbsp;contains&nbsp;a list of friends&nbsp;sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list.&nbsp;Friends in&nbsp;each list are&nbsp;denoted by integers from 0 to n-1.\n\nAll the friends are divided into pairs.&nbsp;The pairings are&nbsp;given in a list&nbsp;pairs,&nbsp;where pairs[i] = [xi, yi] denotes xi&nbsp;is paired with yi and yi is paired with xi.\n\nHowever, this pairing may cause some of the friends to be unhappy.&nbsp;A friend x&nbsp;is unhappy if x&nbsp;is paired with y&nbsp;and there exists a friend u&nbsp;who&nbsp;is paired with v&nbsp;but:\n\n\n\tx&nbsp;prefers u&nbsp;over y,&nbsp;and\n\tu&nbsp;prefers x&nbsp;over v.\n\n\nReturn the number of unhappy friends.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput: 2\nExplanation:\nFriend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.\n\n\nExample 2:\n\nInput: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput: 0\nExplanation: Both friends 0 and 1 are happy.\n\n\nExample 3:\n\nInput: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 500\n\tn&nbsp;is even.\n\tpreferences.length&nbsp;== n\n\tpreferences[i].length&nbsp;== n - 1\n\t0 &lt;= preferences[i][j] &lt;= n - 1\n\tpreferences[i]&nbsp;does not contain i.\n\tAll values in&nbsp;preferences[i]&nbsp;are unique.\n\tpairs.length&nbsp;== n/2\n\tpairs[i].length&nbsp;== 2\n\txi != yi\n\t0 &lt;= xi, yi&nbsp;&lt;= n - 1\n\tEach person is contained in exactly one pair.\n\n",
        "solution_py": "class Solution:\n    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n        dd = {}\n        \n        for i,x in pairs:\n            dd[i] = preferences[i][:preferences[i].index(x)]\n            dd[x] = preferences[x][:preferences[x].index(i)]\n        \n        ans = 0\n            \n        for i in dd:\n            for x in dd[i]:\n                if i in dd[x]:\n                    ans += 1\n                    break\n        \n        return ans",
        "solution_js": "var unhappyFriends = function(n, preferences, pairs) {\n    let happyMap = new Array(n);\n    for (let [i, j] of pairs) {\n        happyMap[i] = preferences[i].indexOf(j);\n        happyMap[j] = preferences[j].indexOf(i);\n    }\n    \n    let unhappy = 0;\n    for (let i = 0; i < n; i++) {\n        for (let j = 0; j < happyMap[i]; j++) {\n            let partner = preferences[i][j];\n            if (preferences[partner].indexOf(i) < happyMap[partner]) {\n                unhappy++;\n                break;\n            }\n        }\n    }\n    \n    return unhappy;\n};",
        "solution_java": "class Solution {\n  public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {\n    int[][] rankings = new int[n][n]; // smaller the value, higher the preference\n    int[] pairedWith = new int[n];\n    for (int i = 0; i < n; i++) {\n      for (int rank = 0; rank < n - 1; rank++) {\n        int j = preferences[i][rank];\n        rankings[i][j] = rank; // person \"i\" views person \"j\" with rank\n      }\n    }\n    int unhappy = 0;\n    for (int[] pair : pairs) {\n      int a = pair[0], b = pair[1];\n      pairedWith[a] = b;\n      pairedWith[b] = a;\n    }\n    for (int a = 0; a < n; a++) {\n      // \"a\" prefers someone else\n      if (rankings[a][pairedWith[a]] != 0) {\n        for (int b = 0; b < n; b++) {\n          // \"b\" prefers to be with \"a\" over their current partner\n          // \"a\" prefers to be with \"b\" over their current partner\n          if (b != a\n              && rankings[b][a] < rankings[b][pairedWith[b]]\n              && rankings[a][b] < rankings[a][pairedWith[a]]) {\n            unhappy++;\n            break;\n          }\n        }\n      }\n    }\n    return unhappy;\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    bool check(int x , int y , int u , int v ,int n , vector<vector<int>>& pref){\n        int id_x = 0 , id_y = 0 , id_u = 0  , id_v = 0 ;\n        //check indices of (y and u) in pref[x] ;\n        for(int i = 0 ; i < n - 1; ++i ){\n            if(pref[x][i] == y) id_y = i ;\n            if(pref[x][i] == u) id_u = i ;\n        }\n        \n        //check indices of (v and x) in pref[u] ;\n        for(int i = 0 ; i < n - 1 ; ++i ){\n            if(pref[u][i] == v) id_v = i ;\n            if(pref[u][i] == x) id_x = i ;\n        }\n        \n        return (id_x < id_v and id_u < id_y) ;\n    }\n    int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {\n        unordered_set<int> unhappy ;\n        for(int i = 0 ; i < pairs.size() ; ++i ){\n            for(int j = i + 1; j < pairs.size() ; ++j){\n                int x = pairs[i][0] , y = pairs[i][1] , u = pairs[j][0] , v = pairs[j][1] ;\n                // x prefers u over y and u preferes x over v \n                if(check(x,y,u,v,n,preferences)) unhappy.insert(x), unhappy.insert(u) ;\n                // x prefers v over y and v prefers x over u \n                if(check(x,y,v,u,n,preferences)) unhappy.insert(x) , unhappy.insert(v) ;\n                // y prefers u over x and u prefers y over v\n                if(check(y,x,u,v,n,preferences)) unhappy.insert(y) , unhappy.insert(u) ;\n                // y prefers v over x and v prefers y over u \n                if(check(y,x,v,u,n,preferences)) unhappy.insert(y) , unhappy.insert(v) ;\n            }\n        }\n        return unhappy.size() ;\n    }\n};"
    },
    {
        "title": "Escape The Ghosts",
        "algo_input": "You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.\n\nEach turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.\n\nYou escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.\n\nReturn true if it is possible to escape regardless of how the ghosts move, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: ghosts = [[1,0],[0,3]], target = [0,1]\nOutput: true\nExplanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\n\n\nExample 2:\n\nInput: ghosts = [[1,0]], target = [2,0]\nOutput: false\nExplanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\n\n\nExample 3:\n\nInput: ghosts = [[2,0]], target = [1,0]\nOutput: false\nExplanation: The ghost can reach the target at the same time as you.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= ghosts.length &lt;= 100\n\tghosts[i].length == 2\n\t-104 &lt;= xi, yi &lt;= 104\n\tThere can be multiple ghosts in the same location.\n\ttarget.length == 2\n\t-104 &lt;= xtarget, ytarget &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:\n        t = float('inf')\n        tx, ty = target\n        for i, j in ghosts:\n            t = min(t, abs(tx - i) + abs(ty - j))\n        return t > abs(tx) + abs(ty)",
        "solution_js": "var escapeGhosts = function(ghosts, target) {\n    const getDistance = (target, source = [0, 0]) => {\n        return (\n            Math.abs(target[0] - source[0])\n            +\n            Math.abs(target[1] - source[1])\n        );\n    }\n    const timeTakenByMe = getDistance(target);\n    let timeTakenByGhosts = Infinity;\n    for(let ghost of ghosts) {\n        timeTakenByGhosts = Math.min(timeTakenByGhosts, getDistance(target, ghost));\n    }\n    return timeTakenByGhosts > timeTakenByMe;\n};",
        "solution_java": "// Escape The Ghosts\n// Leetcode: https://leetcode.com/problems/escape-the-ghosts/\n\nclass Solution {\n    public boolean escapeGhosts(int[][] ghosts, int[] target) {\n        int dist = Math.abs(target[0]) + Math.abs(target[1]);\n        for (int[] ghost : ghosts) {\n            if (Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]) <= dist) {\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {\n        int minimumstepsreqbyplayer = abs(target[0]) + abs(target[1]);\n        int minimumstepsreqbyanyghost = INT_MAX;\n        \n        for(auto x: ghosts){\n            minimumstepsreqbyanyghost = min(minimumstepsreqbyanyghost, abs(x[0]-target[0]) + abs(x[1]-target[1]));\n        }\n        \n        return minimumstepsreqbyplayer<minimumstepsreqbyanyghost;\n    }\n};"
    },
    {
        "title": "Find Numbers with Even Number of Digits",
        "algo_input": "Given an array nums of integers, return how many of them contain an even number of digits.\n\n&nbsp;\nExample 1:\n\nInput: nums = [12,345,2,6,7896]\nOutput: 2\nExplanation: \n12 contains 2 digits (even number of digits).&nbsp;\n345 contains 3 digits (odd number of digits).&nbsp;\n2 contains 1 digit (odd number of digits).&nbsp;\n6 contains 1 digit (odd number of digits).&nbsp;\n7896 contains 4 digits (even number of digits).&nbsp;\nTherefore only 12 and 7896 contain an even number of digits.\n\n\nExample 2:\n\nInput: nums = [555,901,482,1771]\nOutput: 1 \nExplanation: \nOnly 1771 contains an even number of digits.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 500\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findNumbers(self, nums: List[int]) -> int:\n        even_count = 0\n        for elem in nums:\n            if(len(str(elem))%2 == 0):\n                even_count += 1\n        return even_count\n        ",
        "solution_js": "var findNumbers = function(nums) {\n\tlet count = 0;\n\tfor(let num of nums){\n\t\tif(String(num).length % 2 === 0) count++\n\t}\n\treturn count;\n};",
        "solution_java": "class Solution \n{\n    public int findNumbers(int[] nums) \n    {\n        int count = 0;\n        for(int val : nums)\n        {\n            if((val>9 && val<100)  ||  (val>999 && val<10000)  || val==100000  )\n                count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findNumbers(vector<int>& nums) {\n        int count = 0;\n\n        for(auto it:nums)\n        {\n            int amount = 0;\n            while(it>0)\n            {\n                amount++;\n                it /= 10;\n            }\n            if (amount % 2 == 0)\n            {\n                count++;\n            }\n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Minimize Maximum Pair Sum in Array",
        "algo_input": "The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.\n\n\n\tFor example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.\n\n\nGiven an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:\n\n\n\tEach element of nums is in exactly one pair, and\n\tThe maximum pair sum is minimized.\n\n\nReturn the minimized maximum pair sum after optimally pairing up the elements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,5,2,3]\nOutput: 7\nExplanation: The elements can be paired up into pairs (3,3) and (5,2).\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\n\n\nExample 2:\n\nInput: nums = [3,5,4,2,4,6]\nOutput: 8\nExplanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t2 &lt;= n &lt;= 105\n\tn is even.\n\t1 &lt;= nums[i] &lt;= 105\n",
        "solution_py": "class Solution:\n    def minPairSum(self, nums: List[int]) -> int:\n        pair_sum = []\n        nums.sort()\n        for i in range(len(nums)//2):\n            pair_sum.append(nums[i]+nums[len(nums)-i-1])\n        return max(pair_sum)",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minPairSum = function(nums) {\n    nums.sort((a,b) => a-b);\n    let max = 0;\n    for(let i=0; i<nums.length/2; i++){\n        max = Math.max(max , nums[i] + nums[nums.length-1-i]);\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int minPairSum(int[] nums) {\n        Arrays.sort(nums);\n\n        int output = Integer.MIN_VALUE;\n\n        //This is greedy, so n/2 pairs must be from start and end and move inwards\n        for(int i=0, j=nums.length - 1; i<nums.length/2; i++, j--)\n        {\n            output = Math.max(output, nums[i] + nums[j]);\n        }\n\n        return output;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minPairSum(vector<int>& nums){\n\t    //sort the array\n        sort(nums.begin(),nums.end());\n        int start=0,end=nums.size()-1,min_max_pair_sum=0;\n\t\t//Observe the pattern of taking the first and last element, second and second last element... and soo onn.. \n\t\t//would help you to minimize the maximum sum.\n        while(start<end){\n            min_max_pair_sum=max(min_max_pair_sum,nums[start++]+nums[end--]);\n        }\n        return min_max_pair_sum;\n    }\n};"
    },
    {
        "title": "The Number of Full Rounds You Have Played",
        "algo_input": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts.\n\n\n\tFor example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30.\n\n\nYou are given two strings loginTime and logoutTime where:\n\n\n\tloginTime is the time you will login to the game, and\n\tlogoutTime is the time you will logout from the game.\n\n\nIf logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.\n\nReturn the number of full chess rounds you have played in the tournament.\n\nNote:&nbsp;All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.\n\n&nbsp;\nExample 1:\n\nInput: loginTime = \"09:31\", logoutTime = \"10:14\"\nOutput: 1\nExplanation: You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.\n\n\nExample 2:\n\nInput: loginTime = \"21:30\", logoutTime = \"03:00\"\nOutput: 22\nExplanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.\n\n\n&nbsp;\nConstraints:\n\n\n\tloginTime and logoutTime are in the format hh:mm.\n\t00 &lt;= hh &lt;= 23\n\t00 &lt;= mm &lt;= 59\n\tloginTime and logoutTime are not equal.\n\n",
        "solution_py": "class Solution:\n    def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n        hs, ms = (int(x) for x in startTime.split(\":\"))\n        ts = 60 * hs + ms\n        hf, mf = (int(x) for x in finishTime.split(\":\"))\n        tf = 60 * hf + mf\n        if 0 <= tf - ts < 15: return 0 # edge case \n        return tf//15 - (ts+14)//15 + (ts>tf)*96",
        "solution_js": "var numberOfRounds = function(loginTime, logoutTime) {\n    const start = toMins(loginTime);\n    const end = toMins(logoutTime);\n\n    let roundStart = Math.ceil(start / 15);\n    let roundEnd = Math.floor(end / 15);\n\n    if (start < end) {\n        return Math.max(0, roundEnd - roundStart);\n    }\n    else {\n        roundEnd += 96;\n        return roundEnd - roundStart;\n    }\n\n    function toMins(timeStr) {\n        const [hh, mm] = timeStr.split(\":\");\n\n        let totMins = 0;\n\n        totMins += parseInt(hh) * 60;\n        totMins += parseInt(mm);\n\n        return totMins;\n    }\n};",
        "solution_java": "class Solution {\n    public int numberOfRounds(String loginTime, String logoutTime) {\n        String[] arr1 = loginTime.split(\":\");\n        String[] arr2 = logoutTime.split(\":\");\n\n        int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]);\n        int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]);\n\n        if(time1 > time2) time2 = time2 + 24*60;\n        if(time1%15 != 0) time1 = time1 + 15-time1%15;\n\n        return (time2 - time1)/15;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(string s)\n    {\n        int hour=stoi(s.substr(0,2));\n        int min=stoi(s.substr(3,5));\n        return hour*60+min;\n    }\n    int numberOfRounds(string loginTime, string logoutTime) {\n        int st=solve(loginTime);\n        int et=solve(logoutTime);\n        int ans=0;\n        if(st>et) et=et+1440;\n        if(st%15!=0) st=st+(15-st%15);\n        ans=(et-st)/15;\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Closed Islands",
        "algo_input": "Given a 2D&nbsp;grid consists of 0s (land)&nbsp;and 1s (water).&nbsp; An island is a maximal 4-directionally connected group of 0s and a closed island&nbsp;is an island totally&nbsp;(all left, top, right, bottom) surrounded by 1s.\n\nReturn the number of closed islands.\n\n&nbsp;\nExample 1:\n\n\n\nInput: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput: 2\nExplanation: \nIslands in gray are closed because they are completely surrounded by water (group of 1s).\n\nExample 2:\n\n\n\nInput: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput: 1\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1,1,1],\n&nbsp;              [1,0,0,0,0,0,1],\n&nbsp;              [1,0,1,1,1,0,1],\n&nbsp;              [1,0,1,0,1,0,1],\n&nbsp;              [1,0,1,1,1,0,1],\n&nbsp;              [1,0,0,0,0,0,1],\n               [1,1,1,1,1,1,1]]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= grid.length, grid[0].length &lt;= 100\n\t0 &lt;= grid[i][j] &lt;=1\n\n",
        "solution_py": "class Solution:\n    '''主函数:计算封闭岛屿的数量'''\n    def closedIsland(self, grid: List[List[int]]) -> int:\n        result = 0\n        m, n = len(grid), len(grid[0])\n        self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n        \n        # 遍历 grid,处理边缘陆地\n        for j in range(n):\n            self.dfs(grid, 0, j)\n            self.dfs(grid, m - 1, j)\n        for i in range(m):\n            self.dfs(grid, i, 0)\n            self.dfs(grid, i, n - 1)\n        \n        # 剩下都是封闭岛屿,遍历找结果\n        for i in range(m):\n            for j in range(n):\n                if grid[i][j] == 0:\n                    result += 1\n                    self.dfs(grid, i, j)\n        return result\n    \n    '''从 (i, j) 开始,将与之相邻的陆地都变成海水'''\n    def dfs(self, grid, i, j):\n        m, n = len(grid), len(grid[0])\n        # 超出索引边界\n        if i < 0 or j < 0 or i >= m or j >= n:\n            return\n        # 已经是海水了\n        if grid[i][j] == 1:\n            return\n        # 变成海水\n        grid[i][j] = 1\n        for d in self.direction:\n            x = i + d[0]\n            y = j + d[1]\n            self.dfs(grid, x, y)",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar closedIsland = function(grid) {\n    let rows = grid.length;\n    let cols = grid[0].length;\n    let islandCount = 0; // Initial island count\n\n    // For Quick Response\n    if (rows <= 2 || cols <= 2) return islandCount;\n\n    for (let i = 0; i <= rows - 1; i++) {\n        for (let j = 0; j <= cols - 1; j++) {\n            /*\n                If land was found on the border, it can never be enclosed by water.\n                So, mark the all the adjacent land across grid as visited.\n            */\n            if (grid[i][j] === 0 && (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)) {\n                dfs(i, j);\n            }\n        }\n    }\n\n    // If land is found, increase the count and walk around land(adjacent indexes) to mark them as visited.\n    for (let i = 1; i <= rows - 1; i++) {\n        for (let j = 1; j <= cols - 1; j++) {\n            if (grid[i][j] === 0) {\n                islandCount++;\n                dfs(i, j);\n            }\n        }\n    }\n\n    // To walk around land and mark it as visited\n    function dfs(x, y) {\n        if (x < 0 || y < 0 || x >= rows || y >= cols) return;\n        if (grid[x][y] !== 0) return;\n\n        grid[x][y] = 2;\n\n        dfs(x + 1, y);\n        dfs(x, y + 1);\n        dfs(x - 1, y);\n        dfs(x, y - 1);\n    }\n\n    return islandCount;\n};",
        "solution_java": "class Solution {\n    boolean isClosed = true;\n    public int closedIsland(int[][] grid) {\n        int m = grid.length;\n        int n = grid[0].length;\n        int count = 0;\n\n        for(int i=1; i<m-1; i++){\n            for(int j=1; j<n-1; j++){\n                isClosed = true;\n                if(grid[i][j] == 0){\n                    dfs(grid, i, j);\n\n                    if(isClosed){\n                        count++;\n                    }\n                }\n            }\n        }\n\n        return count;\n    }\n\n    public void dfs(int[][] grid, int i, int j){\n        if(i<0 || j<0 || i> grid.length-1 || j> grid[0].length-1 || grid[i][j] != 0) return;\n\n         grid[i][j] = 1; // to mark as visited\n\n        if(i == 0 || j == 0 || i == grid.length -1 || j == grid[0].length - 1) isClosed = false;\n\n        dfs(grid, i, j+1);\n        dfs(grid, i, j-1);\n        dfs(grid, i+1, j);\n        dfs(grid, i-1, j);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isValid(int i,int j,vector<vector<int>>&grid) {\n        if(i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 0) {\n            return true;\n        }\n        return false;\n    }\n    void DFS(int i,int j,vector<vector<int>>&grid) {\n        grid[i][j] = 1;\n        if(isValid(i + 1,j,grid)) {\n            DFS(i + 1,j,grid);\n        }\n        if(isValid(i - 1,j,grid)) {\n            DFS(i - 1,j,grid);\n        }\n        if(isValid(i,j + 1,grid)) {\n            DFS(i,j + 1,grid);\n        }\n        if(isValid(i,j - 1,grid)) {\n            DFS(i,j - 1,grid);\n        }\n    }\n    int closedIsland(vector<vector<int>>& grid) {\n        int m = grid.size();\n        int n = grid[0].size();\n        for(int i = 0; i < m; i++) {\n            int j = 0;\n            if(grid[i][j] == 0) {\n                DFS(i,j,grid);\n            }\n            j = n - 1;\n            if(grid[i][j] == 0) {\n                DFS(i,j,grid);\n            }\n        }\n        for(int j = 0; j < n; j++) {\n            int i = 0;\n            if(grid[i][j] == 0) {\n                DFS(i,j,grid);\n            }\n            i = m - 1;\n            if(grid[i][j] == 0) {\n                DFS(i,j,grid);\n            }\n        }\n        int cnt = 0;\n        for(int i = 0; i < m; i++) {\n            for(int j = 0; j < n; j++) {\n                if(grid[i][j] == 0) {\n                    cnt++;\n                    DFS(i,j,grid);\n                }\n            }\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Super Palindromes",
        "algo_input": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\n\nGiven two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].\n\n&nbsp;\nExample 1:\n\nInput: left = \"4\", right = \"1000\"\nOutput: 4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n\n\nExample 2:\n\nInput: left = \"1\", right = \"2\"\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= left.length, right.length &lt;= 18\n\tleft and right consist of only digits.\n\tleft and right cannot have leading zeros.\n\tleft and right represent integers in the range [1, 1018 - 1].\n\tleft is less than or equal to right.\n\n",
        "solution_py": "class Solution:\n    def superpalindromesInRange(self, left: str, right: str) -> int:\n        min_num, max_num = int(left), int(right)\n        count, limit = 0, 20001\n        \n        # odd pals\n        for num in range(limit + 1):\n            num_str = str(num)\n            if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n                pal = num_str + num_str[:-1][::-1]\n                num_sqr = int(pal) ** 2\n\n                if num_sqr > max_num:\n                    break\n\n                if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n                    count += 1\n        \n        # even pals\n        for num in range(limit + 1):\n            num_str = str(num)\n            if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n                pal = num_str + num_str[::-1]\n                num_sqr = int(pal) ** 2\n\n                if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n                len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n                    if num_sqr > max_num:\n                        break\n\n                    if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n                        count += 1\n                \n        return count ",
        "solution_js": "var superpalindromesInRange = function(left, right) {\n    let ans = 9 >= left && 9 <= right ? 1 : 0\n\n    const isPal = str => {\n        for (let i = 0, j = str.length - 1; i < j; i++, j--)\n            if (str.charAt(i) !== str.charAt(j)) return false\n        return true\n    }\n\n    for (let dig = 1; dig < 10; dig++) {\n        let isOdd = dig % 2 && dig !== 1,\n            innerLen = (dig >> 1) - 1, innerLim = Math.max(1, 2 ** innerLen),\n            midPos = dig >> 1, midLim = isOdd ? 3 : 1\n        for (let edge = 1; edge < 3; edge++) {\n            let pal = new Uint8Array(dig)\n            pal[0] = edge, pal[dig-1] = edge\n            if (edge === 2) innerLim = 1, midLim = Math.min(midLim, 2)\n            for (let inner = 0; inner < innerLim; inner++) {\n                if (inner > 0) {\n                    let innerStr = inner.toString(2).padStart(innerLen, '0')\n                    for (let i = 0; i < innerLen; i++)\n                        pal[1+i] = innerStr[i], pal[dig-2-i] = innerStr[i]\n                }\n                for (let mid = 0; mid < midLim; mid++) {\n                    if (isOdd) pal[midPos] = mid\n                    let palin = ~~pal.join(\"\"),\n                        square = BigInt(palin) * BigInt(palin)\n                    if (square > right) return ans\n                    if (square >= left && isPal(square.toString())) ans++\n                }\n            }\n        }\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public int superpalindromesInRange(String left, String right) {\n        int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n\n        for (int dig = 1; dig < 10; dig++) {\n            boolean isOdd = dig % 2 > 0 && dig != 1;\n            int innerLen = (dig >> 1) - 1,\n                innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n                midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n            for (int edge = 1; edge < 3; edge++) {\n                char[] pal = new char[dig];\n                Arrays.fill(pal, '0');\n                pal[0] = (char)(edge + 48);\n                pal[dig-1] = (char)(edge + 48);\n                if (edge == 2) {\n                    innerLim = 1;\n                    midLim = Math.min(midLim, 2);\n                }\n                for (int inner = 0; inner < innerLim; inner++) {\n                    if (inner > 0) {\n                        String innerStr = Integer.toString(inner, 2);\n                        while (innerStr.length() < innerLen)\n                            innerStr = \"0\" + innerStr;\n                        for (int i = 0; i < innerLen; i++) {\n                            pal[1+i] = innerStr.charAt(i);\n                            pal[dig-2-i] = innerStr.charAt(i);\n                        }\n                    }\n                    for (int mid = 0; mid < midLim; mid++) {\n                        if (isOdd) pal[midPos] = (char)(mid + 48);\n                        String palin = new String(pal);\n                        long square = Long.parseLong(palin) * Long.parseLong(palin);\n                        if (square > Long.parseLong(right)) return ans;\n                        if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n\n    private boolean isPal(String str) {\n        for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n            if (str.charAt(i) != str.charAt(j)) return false;\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int superpalindromesInRange(string lef, string rig) {\n   long L = stol(lef) , R = stol(rig);        \n           int magic = 100000 , ans = 0;\n                   string s = \"\";\n\n                            for(int k = 1 ; k  < magic ; k++){\n                                     s = to_string(k);\n                                       for(int i = s.length() - 2 ; i >= 0; i--){\n                                                       s += s.at(i);\n                                                                   }\n                                                                               long v = stol(s);\n                                                                                           v *= v;\n                                                                                                       if(v > R) break;\n                                                                                                          if(v >= L && isPalindrome(v)) ans++;\n                                                                                                                  }\n\n                                                                                                                          for(int k = 1 ; k < magic ; k++){\n                                                                                                                                      s = to_string(k);\n                                                                                                                                       for(int i = s.length() - 1 ; i >= 0 ; i--){\n                                                                                                                                                       s += s.at(i);\n                                                                                                                                                                   }\n                                                                                                                                                                               long v = stol(s);\n                                                                                                                                                                                           v *= v;\n                                                                                                                                                                                                       if(v > R) break;\n                                                                                                                                                                                                         if(v >= L && isPalindrome(v)) ans++;\n                                                                                                                                                                                                                 }\n                                                                                                                                                                                                                         return ans;\n                                                                                                                                                                                                                             }\n\n                                                                                                                                                                                                                                     bool isPalindrome(long x){\n                                                                                                                                                                                                                                             return x == reverse(x);\n                                                                                                                                                                                                                                                 }\n\n                                                                                                                                                                                                                                                         long reverse(long x ){\n                                                                                                                                                                                                                                                                 long ans = 0;\n                                                                                                                                                                                                                                                                         while(x > 0){\n                                                                                                                                                                                                                                                                                     ans = 10 * ans + x % 10;\n                                                                                                                                                                                                                                                                                                 x /= 10;\n                                                                                                                                                                                                                                                                                                         }\n                                                                                                                                                                                                                                                                                                                 return ans;\n                                                                                                                                                                                                                                                                                                                     }     \n    \n};"
    },
    {
        "title": "String Compression II",
        "algo_input": "Run-length encoding is a string compression method that works by&nbsp;replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string&nbsp;\"aabccc\"&nbsp;we replace \"aa\"&nbsp;by&nbsp;\"a2\"&nbsp;and replace \"ccc\"&nbsp;by&nbsp;\"c3\". Thus the compressed string becomes \"a2bc3\".\n\nNotice that in this problem, we are not adding&nbsp;'1'&nbsp;after single characters.\n\nGiven a&nbsp;string s&nbsp;and an integer k. You need to delete at most&nbsp;k characters from&nbsp;s&nbsp;such that the run-length encoded version of s&nbsp;has minimum length.\n\nFind the minimum length of the run-length encoded&nbsp;version of s after deleting at most k characters.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aaabcccd\", k = 2\nOutput: 4\nExplanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n\nExample 2:\n\nInput: s = \"aabbaa\", k = 2\nOutput: 2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n\n\nExample 3:\n\nInput: s = \"aaaaaaaaaaa\", k = 0\nOutput: 3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\t0 &lt;= k &lt;= s.length\n\ts contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n        # Find min lenth of the code starting from group ind, if there are res_k characters to delete and\n        # group ind needs to be increased by carry_over additional characters\n        def FindMinLen(ind, res_k, carry_over=0):\n\n            # If we already found the min length - just retrieve it (-1 means we did not calculate it)\n            if carry_over == 0 and dynamic[ind][res_k] != -1:\n                return dynamic[ind][res_k]\n\n            # Number of character occurences that we need to code. Includes carry-over.\n            cur_count = carry_over + frequency[ind]\n\n            # Min code length if the group ind stays intact. The code accounts for single-character \"s0\" vs. \"s\" situation.\n            min_len = 1 + min(len(str(cur_count)), cur_count - 1) + FindMinLen(ind+1,res_k)\n\n            # Min length if we keep only 0, 1, 9, or 99 characters in the group - delete the rest, if feasible\n            for leave_count, code_count in [(0,0), (1, 1), (9, 2), (99, 3)]:\n                if cur_count > leave_count and res_k >= cur_count - leave_count:\n                    min_len = min(min_len, code_count + FindMinLen(ind + 1,res_k - (cur_count - leave_count)))\n\n            # If we drop characters between this character group and next group, like drop \"a\" in \"bbbabb\"\n            next_ind = chars.find(chars[ind], ind + 1)\n            delete_count = sum(frequency[ind+1:next_ind])\n            if next_ind > 0 and res_k >= delete_count:\n                min_len = min(min_len, FindMinLen(next_ind, res_k - delete_count, carry_over = cur_count))\n\n            # If there was no carry-over, store the result\n            if carry_over == 0: dynamic[ind][res_k] = min_len\n            return min_len\n\n        # Two auxiliary lists - character groups (drop repeated) and number of characters in the group\n        frequency, chars = [], \"\"\n        for char in s:\n            if len(frequency)==0 or char != chars[-1]:\n                frequency.append(0)\n                chars = chars + char\n            frequency[-1] += 1\n\n        # Table with the results. Number of character groups by number of available deletions.\n        dynamic = [[-1] * (k + 1) for i in range(len(frequency))] + [[0]*(k + 1)]\n\n        return FindMinLen(0, k)",
        "solution_js": "var getLengthOfOptimalCompression = function(s, k) {\n    const memo = new Map()\n    \n    const backtrack = (i, lastChar, lastCharCount, k) => {\n        if (k < 0) return Number.POSITIVE_INFINITY\n        if (i >= s.length) return 0\n        \n        const memoKey = `${i}#${lastChar}#${lastCharCount}#${k}`\n        if (memoKey in memo) return memo[memoKey]\n        \n        if (s[i] === lastChar) {\n            const incrementor = [1, 9, 99].includes(lastCharCount) ? 1 : 0\n            memo[memoKey] = incrementor + backtrack(i+1, lastChar, lastCharCount+1, k)\n        } else {\n            memo[memoKey] = Math.min(\n                1 + backtrack(i+1, s[i], 1, k), //keep char\n                backtrack(i+1, lastChar, lastCharCount, k-1) //delete char\n            )\n        }\n        return memo[memoKey]\n    }\n    return backtrack(0, '', 0, k)\n};",
        "solution_java": "class Solution {\n\t public int getLengthOfOptimalCompression(String s, int k) {\n        Map<String, Integer> memo = new HashMap<>();\n        return recur(s, '\\u0000', 0, k, 0, memo);\n    }\n\n    private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map<String, Integer> memo) {\n\n        if (index == s.length()) {\n            return 0;\n        }\n        String key = prevChar + \", \" + prevCharCount + \", \" + k + \", \" + index;\n        Integer keyVal = memo.get(key);\n\n        if (keyVal != null) {\n            return keyVal;\n        }\n        char ch = s.charAt(index);\n        int count = 1;\n        int nextIndex = index + 1;\n\n        for (int i = index + 1; i < s.length(); i++) {\n\n            if (s.charAt(i) == ch) {\n                count++;\n                nextIndex = i + 1;\n            } else {\n                nextIndex = i;\n                break;\n            }\n        }\n        int totalCount = count;\n        int prevCountRepresentation = 0;\n        //if prev char is equal to current char that means we have removed middle element\n        //So we have to subtract the previous representation length and add the new encoding\n        //representation length\n        if (ch == prevChar) {\n            totalCount += prevCharCount;\n            prevCountRepresentation = getLength(prevCharCount);\n        }\n\n        int representaionLength = getLength(totalCount);\n        int ans = representaionLength + recur(s, ch, totalCount, k, nextIndex, memo) - prevCountRepresentation;\n\n        if (k > 0) {\n\n            for (int i = 1; i <= k && i <= count; i++) {\n                int currentCount = totalCount - i;\n                int length = getLength(currentCount);\n                //checking if we have to send current char and current char count or previous char\n                //and previous char count\n                int holder = length + recur(s, currentCount == 0 ? prevChar : ch,\n                        currentCount == 0 ? prevCharCount : currentCount, k - i, nextIndex, memo) -\n                        prevCountRepresentation;\n                ans = Math.min(ans, holder);\n            }\n        }\n        memo.put(key, ans);\n        return ans;\n    }\n    //Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc.\n    private int getLength(int n) {\n\n        if (n == 0) {\n            return 0;\n        } else if (n == 1) {\n            return 1;\n        } else if (n < 10) {\n            return 2;\n        } else if (n < 100) {\n            return 3;\n        } else  {\n            return 4;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[101][101];\n    int dfs(string &s, int left, int K) {\n        int k = K;\n        if(s.size() - left <= k) return 0;\n        if(dp[left][k] >= 0) return dp[left][k];\n        int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1;\n        for(int i = left + 1; i <= s.size(); ++i) {\n            res = min(res, dfs(s, i, k) + 1 + (c >= 100 ? 3 : (c >= 10 ? 2 : (c > 1 ? 1 :0))));\n            if(i == s.size()) break;\n            if(s[i] == s[left]) ++c;\n            else if(--k < 0) break;\n        }\n        return dp[left][K] = res;\n    }\n    \n    int getLengthOfOptimalCompression(string s, int k) {\n        memset(dp, -1, sizeof(dp));\n        return dfs(s, 0, k);\n    }\n};"
    },
    {
        "title": "Minimum Number of Removals to Make Mountain Array",
        "algo_input": "You may recall that an array arr is a mountain array if and only if:\n\n\n\tarr.length &gt;= 3\n\tThere exists some index i (0-indexed) with 0 &lt; i &lt; arr.length - 1 such that:\n\t\n\t\tarr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i]\n\t\tarr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]\n\t\n\t\n\n\nGiven an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,1]\nOutput: 0\nExplanation: The array itself is a mountain array so we do not need to remove any elements.\n\n\nExample 2:\n\nInput: nums = [2,1,1,5,6,2,3,1]\nOutput: 3\nExplanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 109\n\tIt is guaranteed that you can make a mountain array out of nums.\n\n",
        "solution_py": "class Solution:\n    def minimumMountainRemovals(self, nums: List[int]) -> int:\n        n = len(nums)\n        inc = [0] * n\n        dec = [0] * n\n        \n#  Longest Increasing Subsequence\n        for i in range(1,n):\n            for j in range(0,i):\n                if nums[i] > nums[j]:\n                    inc[i] = max(inc[i], inc[j] + 1)\n                \n#  Longest Decreasing Subsequence\n        for i in range(n-2,-1,-1):\n            for j in range(n-1,i,-1):\n                if nums[i] > nums[j]:\n                    dec[i] = max(dec[i], dec[j] + 1)\n        \n# Final calculation\n        res = 0\n        for i in range(0,n):\n            if inc[i] > 0 and dec[i] > 0:\n                res = max(res, inc[i] + dec[i])\n                \n# Final conclusion        \n        return n - res - 1",
        "solution_js": "var minimumMountainRemovals = function(nums) {\n    let n=nums.length\n    let previous=Array.from({length:n},item=>1)\n    let previous2=Array.from({length:n},item=>1)\n    //calcultaing left and right side LIS in single iteration\n    for (let i=0;i<n;i++){\n        for (let j=0;j<i;j++){\n            //reverse indexes\n            let i2=n-1-i\n            let j2=n-1-j\n            //calculating first dp serially \n            if (nums[i]>nums[j] && previous[i]<previous[j]+1){\n                previous[i]=previous[j]+1\n            }\n            //calculating second dp reversely\n            if (nums[i2]>nums[j2] && previous2[i2]<previous2[j2]+1){\n                previous2[i2]=previous2[j2]+1\n            }\n        }\n    }\n    let max=0\n    for (let i=0;i<n;i++){\n        //golden condition// to avoid only increasing and decreasing\n        //because if a combination of 1 indicates its increasing fully or decreasing !\n        if (previous[i]>1 && previous2[i]>1){\n        //at a specific index highest increasing will come from left LIS\n        // and highest decreasing will come from right side LIS\n        max=Math.max(max,previous[i]+previous2[i]-1)\n        }\n    }\n    return n-max //we need to remove the rest from total\n};",
        "solution_java": "class Solution {\n    public int minimumMountainRemovals(int[] nums) {\n\n        int n = nums.length;\n        int[] LIS = new int[n];\n        int[] LDS = new int[n];\n\n        Arrays.fill(LIS, 1);\n        Arrays.fill(LDS, 1);\n        // calculate the longest increase subsequence (LIS) for every index i\n        for(int i=1 ; i < n ; i++)\n        {\n            for(int j = 0 ; j < i ; j++)\n            {\n                if(nums[i] > nums[j] && LIS[j]+1 > LIS[i])\n                    LIS[i] = LIS[j]+1;\n            }\n        }\n\n        // calculate the longest decreasing subsequence(LDS) for every index i and keep track of the maximum of LIS+LDS\n        int max = 0;\n        for(int i=n-2 ; i >= 0 ; i--)\n        {\n            for(int j = n-1 ; j > i ; j--)\n            {\n                if(nums[i] > nums[j] && LDS[j]+1 > LDS[i])\n                    LDS[i] = LDS[j]+1;\n            }\n\n            if(LIS[i] > 1 && LDS[i] > 1)\n                max = Math.max(LIS[i]+LDS[i]-1, max);\n        }\n        return n - max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumMountainRemovals(vector<int>& nums) {\n        int n = nums.size();\n\n        vector<int> dp1(n,1), dp2(n,1);\n\n        // LIS from front\n        for(int i=0; i<n; i++)\n        {\n            for(int j=0; j<i; j++)\n            {\n                if(nums[i] > nums[j] && 1 + dp1[j] > dp1[i])\n                {\n                    dp1[i] = 1 + dp1[j];\n                }\n            }\n        }\n\n        //LIS from back\n        for(int i=n-1; i>=0; i--)\n        {\n            for(int j=n-1; j>i; j--)\n            {\n                if(nums[i] > nums[j] && dp2[j] + 1 > dp2[i]){\n                    dp2[i] = dp2[j] + 1;\n                }\n            }\n        }\n\n        int maxi = 1;\n        for(int i=0; i<n; i++){\n            if(dp1[i] > 1 && dp2[i] > 1){\n                maxi = max(maxi, dp1[i] + dp2[i] -1);\n            }\n        }\n        return (n-maxi);\n    }\n};"
    },
    {
        "title": "Minimize Malware Spread II",
        "algo_input": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\n\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.\n\nWe will remove exactly one node from initial, completely removing it and any connections from this node to any other node.\n\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n\n&nbsp;\nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\nExample 2:\nInput: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput: 1\nExample 3:\nInput: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput: 1\n\n&nbsp;\nConstraints:\n\n\n\tn == graph.length\n\tn == graph[i].length\n\t2 &lt;= n &lt;= 300\n\tgraph[i][j] is 0 or 1.\n\tgraph[i][j] == graph[j][i]\n\tgraph[i][i] == 1\n\t1 &lt;= initial.length &lt;&nbsp;n\n\t0 &lt;= initial[i] &lt;= n - 1\n\tAll the integers in initial are unique.\n\n",
        "solution_py": "from collections import defaultdict\nfrom collections import deque\nclass Solution:\n    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n        n = len(graph)\n        G = defaultdict(list)\n        for v in range(n):\n            for w in range(n):\n                if graph[v][w]:\n                    G[v].append(w)\n                    \n        affect = defaultdict(list)\n        for s in initial:\n            visited = set([v for v in initial if v != s])\n            que = deque([s])\n            while que:\n                v = que.popleft()\n                if v in visited: continue\n                visited.add(v)\n                affect[v].append(s)\n                for w in G[v]:\n                    que.append(w)\n        res = [0]*n\n        for v in affect:\n            if len(affect[v]) == 1:\n                res[affect[v].pop()] += 1\n        if not max(res): return min(initial)\n        return res.index(max(res))",
        "solution_js": "var minMalwareSpread = function(graph, initial) {\nlet n = graph.length\nlet AdjList = new Map();\nlet listFromGraph = (mat) => {// convert adj matrix to adj list\n    for(let i=0; i<n; i++){\n        AdjList[i] = [];\n        for(let j=0; j<n; j++){\n            if(mat[i][j] === 1 && i!==j){\n                AdjList[i].push(j);\n            }\n        }\n    }\n}\nlistFromGraph(graph);\nlet visitedSet = new Set();//visited set, to manage the visited nodes & their count as they are unique\nlet dfs = (curr,node) => {// dfs helper, visit the graph assuming that node, given as 2nd parameter is deleted\n    if(curr===node){\n        return;\n    }\n    if(visitedSet.has(curr)){\n        return;\n    }\n    visitedSet.add(curr);// size of visited shows how many nodes are visited/affected by the malware\n    let neighbours = AdjList[curr];\n    for(let i in neighbours){// visit all the neighbours\n        dfs(neighbours[i],node);\n    }\n}\nlet MinSpread = n;// min index of node with max reduction in malware\nlet SpreadDist = n;// number of nodes affected by malware if MinSpread was deleted\nfor(let i=0; i<initial.length; i++){\n    for(let j=0; j<initial.length; j++){// find the total nodes affected if ith node is removed\n        dfs(initial[j],initial[i]);\n    }\n    if(SpreadDist == visitedSet.size){// to get min index but same impact\n        MinSpread = Math.min(initial[i],MinSpread);\n    }\n    if(SpreadDist > visitedSet.size){// to get max impact\n        MinSpread = initial[i];\n        SpreadDist = visitedSet.size;\n    }\n    visitedSet.clear();// clear visited set for next index to be deleted\n}\nreturn MinSpread;\n};",
        "solution_java": "class Solution {\n    int[] parent;\n    int[] size;\n   \n    public int find(int x){\n        if(parent[x]==x) return x;\n        int f = find(parent[x]);\n        parent[x] = f;\n        return f;\n    }\n    \n    void merge(int x, int y){\n        if(size[x]>size[y]){\n            parent[y] = x;\n            size[x] += size[y];\n        }else{\n            parent[x] =y;\n            size[y] +=size[x];\n        }\n    }\n    \n    public int minMalwareSpread(int[][] graph, int[] initial) {\n        int n =graph.length;\n        \n        parent = new int[n];\n        size= new int[n];\n        // putting initially infected nodes in hashset to ignore them while making graph\n        HashSet<Integer> hs = new HashSet<>();\n        for(int a : initial){\n            hs.add(a);\n        }\n        //initializing Parent for DSU\n        for(int i=0;i<parent.length;i++){\n            parent[i] = i;\n            size[i]=1;\n        }\n        //constructing groups DSU\n        for(int i=0;i<graph.length;i++){\n            for(int j=0;j<graph[0].length;j++){\n                if(graph[i][j]==1 && !hs.contains(i) && !hs.contains(j)){\n                    int p1 = find(i);\n                    int p2 = find(j);\n                    if(p1!=p2){\n                        merge(p1,p2); //merging if they are not already\n                    }\n                }\n            }\n        }\n        //Storing initial Nodes vs parents of connected node...if there are multiple edge to same component then we will get the same parent twice ...so we will take hashset for that purpose.\n        HashMap<Integer,HashSet<Integer>> map = new HashMap<>();\n        //We need to ensure increase the count whenever a parent is influenced by initial Nodes...because if it influenced by more than one infectious node then it would still remain infectious.\n        int[] infected = new int[n]; \n        for(int e: initial){\n            map.put(e,new HashSet<>());\n            for(int j=0;j<n;j++){\n                // in adjaceny graph[i][i] is always one so we will ignore that\n                if(!hs.contains(j) && e!=j && graph[e][j]==1){ \n                    int p = find(j);\n                    if(!map.get(e).contains(p)){\n                        map.get(e).add(p);\n                        infected[p]++;\n                    }\n                }\n            }\n        }\n        int max = -1;\n        int ans =-1;\n        \n        for(int e:initial){\n            HashSet<Integer> par = map.get(e);\n            int total =0;\n            for(int p: par){\n                if(infected[p]==1){ //add to total only if influenced by only one infectious node.\n                    total+=size[p];\n                }\n            }\n            if(total>=max){\n                if(max==total){\n                    ans = Math.min(ans,e);\n                }else{\n                    ans =e;\n                }\n                max =total;\n            }\n        }\n        \n        if(ans!=-1) return ans;\n        //for returining smallest element.\n        Arrays.sort(initial);\n        \n        return initial[0];\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n        \n        sort(initial.begin(), initial.end());\n        int ans = -1, mn = INT_MAX, n = graph.size();\n        \n        vector<vector<int>> new_graph(n);\n        for(int i = 0; i < n; i++)\n            for(int j = 0; j < n; j++)\n                if(graph[i][j])\n                    new_graph[i].push_back(j);\n        \n        for(auto &k : initial)\n        {\n            vector<int> dsu(n, -1);\n            for(int i = 0; i < n; i++)\n                for(auto &j : new_graph[i])\n                    if(i != k && j != k)\n                    {\n                        int a = findParent(dsu, i), b = findParent(dsu, j);\n                        if(a != b)\n                            dsu[b] += dsu[a], dsu[a] = b;\n                    }\n            \n            vector<int> infected(n, 0);\n            for(auto &i : initial)\n                if(i != k)\n                    infected[findParent(dsu, i)]++;\n            \n            int total_infected = 0;\n            for(int i = 0; i < n; i++)\n                if(infected[i])\n                    total_infected += abs(dsu[i]);\n            \n            if(total_infected < mn)\n                mn = total_infected, ans = k;\n        }\n        \n        return ans == -1 ? initial[0] : ans;\n    }\n    \n    int findParent(vector<int> &dsu, int i)\n    {\n        int a = i;\n        while(dsu[i] >= 0)\n            i = dsu[i];\n        \n        if(i != a)\n            dsu[a] = i;\n            \n        return i;\n    }\n};"
    },
    {
        "title": "Surface Area of 3D Shapes",
        "algo_input": "You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).\n\nAfter placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.\n\nReturn the total surface area of the resulting shapes.\n\nNote: The bottom face of each shape counts toward its surface area.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,2],[3,4]]\nOutput: 34\n\n\nExample 2:\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 32\n\n\nExample 3:\n\nInput: grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput: 46\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 50\n\t0 &lt;= grid[i][j] &lt;= 50\n\n",
        "solution_py": "class Solution:\n    def surfaceArea(self, grid: List[List[int]]) -> int:        \n        m, n = len(grid), len(grid[0])\n        \n        area = 0\n        for r in range(m):               \n            for c in range(n):\n                if grid[r][c] != 0:\n                    area += 2\n                \n                if r == 0 or r == m - 1:\n                    area += grid[r][c] if m != 1 else 2*grid[r][c]\n                if r != m - 1:                    \n                    area += abs(grid[r][c] - grid[r+1][c])\n                    \n                if c == 0 or c == n - 1:\n                    area += grid[r][c] if n != 1 else 2*grid[r][c]\n                if c != n - 1:                    \n                    area += abs(grid[r][c] - grid[r][c+1])                    \n                \n        return area",
        "solution_js": "var surfaceArea = function(grid) {\n    let cube=0, overlap=0;\n    for(let i=0; i<grid.length; i++){\n        for(let j=0; j<grid[i].length; j++){\n            cube+=grid[i][j];\n            if(i>0){overlap+=Math.min(grid[i][j], grid[i-1][j]);} // x-direction\n            if(j>0){overlap+=Math.min(grid[i][j], grid[i][j-1]);} // y-direction\n\t\t\tif(grid[i][j]>1){overlap+=grid[i][j]-1}; // z-direction\n        }\n    }\n    return cube*6-overlap*2;\n};",
        "solution_java": "class Solution {\n    public int surfaceArea(int[][] grid) {\n        int area = 0;\n        int n = grid.length;\n        for(int i=0; i<n; i++){\n            for(int j=0; j<n; j++){\n\n                // Adding the top part of grid\n                if(i==0) area += grid[i][j];\n                else area += Math.abs(grid[i][j] - grid[i-1][j]);\n\n                // Adding the left part of grid\n                if(j==0) area += grid[i][j];\n                else area += Math.abs(grid[i][j] - grid[i][j-1]);\n\n                // Adding bottom part of bottom-most cubes\n                if(i == n-1) area += grid[i][j];\n\n                // Adding right part for right-most cubes\n                if(j == n-1) area += grid[i][j];\n\n                // Add top and bottom surfaces if there is no hole in grid\n                if(grid[i][j] != 0) area += 2;\n            }\n        }\n        return area;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int surfaceArea(vector<vector<int>>& grid) {\n        int area = 0;\n        \n        for(int i  = 0; i < grid.size(); i++) {\n            for(int j = 0; j < grid[0].size(); j++) {\n\t\t\t\t//adding 4 sides\n                area += grid[i][j]*4;\n\t\t\t\t\n\t\t\t\t//adding two because of there will only one top and one bottom if cube is placed upon each other\n                if(grid[i][j] != 0)\n                    area+=2;\n\t\t\t\t\n\t\t\t\t//subtracting adjacent side area if any\n                if(i-1 >= 0)\n                    area -= min(grid[i-1][j], grid[i][j]);\n                if(i+1 < grid.size())\n                    area -= min(grid[i+1][j], grid[i][j]);\n                if(j-1 >= 0)\n                    area -= min(grid[i][j-1], grid[i][j]);\n                if(j+1 < grid.size())\n                    area -= min(grid[i][j+1], grid[i][j]);\n            }\n        }\n        \n        return area;\n    }\n};"
    },
    {
        "title": "Sum of Digits of String After Convert",
        "algo_input": "You are given a string s consisting of lowercase English letters, and an integer k.\n\nFirst, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.\n\nFor example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following operations:\n\n\n\tConvert: \"zbax\" ➝ \"(26)(2)(1)(24)\" ➝ \"262124\" ➝ 262124\n\tTransform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4&nbsp;➝ 17\n\tTransform #2: 17 ➝ 1 + 7 ➝ 8\n\n\nReturn the resulting integer after performing the operations described above.\n\n&nbsp;\nExample 1:\n\nInput: s = \"iiii\", k = 1\nOutput: 36\nExplanation: The operations are as follows:\n- Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999\n- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36\nThus the resulting integer is 36.\n\n\nExample 2:\n\nInput: s = \"leetcode\", k = 2\nOutput: 6\nExplanation: The operations are as follows:\n- Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545\n- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33\n- Transform #2: 33 ➝ 3 + 3 ➝ 6\nThus the resulting integer is 6.\n\n\nExample 3:\n\nInput: s = \"zbax\", k = 2\nOutput: 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\t1 &lt;= k &lt;= 10\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def getLucky(self, s: str, k: int) -> int:\n        nums = [str(ord(c) - ord('a') + 1) for c in s]\n        for _ in range(k):\n            nums = str(sum(int(digit) for num in nums for digit in num))\n        return nums",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nvar getLucky = function(s, k) {\n    function alphabetPosition(text) {\n      var result = [];\n      for (var i = 0; i < text.length; i++) {\n        var code = text.toUpperCase().charCodeAt(i)\n        if (code > 64 && code < 91) result.push(code - 64);\n      }\n      return result;\n    }\n\n    let str = alphabetPosition(s).join(\"\");\n    let sum = 0;\n    let newArr;\n\n    while(k>0){\n        newArr = str.split(\"\");\n        sum = newArr.reduce((acc, e) => parseInt(acc)+parseInt(e));\n        str = sum.toString();\n        k--;\n    }\n    return sum\n\n};",
        "solution_java": "class Solution {\n    public int getLucky(String s, int k) {\n    \n        StringBuilder sb=new StringBuilder();\n\n        for(int i=0;i<s.length();i++)\n        sb.append((s.charAt(i)-'a')+1);\n        String result=sb.toString();\n \n        if(result.length()==1)\n        return Character.getNumericValue(result.charAt(0));\n        \n        int sum=0;\n        while(k-->0 && result.length()>1)\n        {   \n            sum=0;\n            for(int i=0;i<result.length();i++)\n            sum+=Character.getNumericValue(result.charAt(i));\n            \n            result=String.valueOf(sum);\n        }\n        \n        return sum;   \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getLucky(string s, int k) {\n        \n        long long sum=0,d;\n        string convert;\n        \n        for(auto& ch: s)\n        {\n            convert+= to_string((ch-96));\n        }\n\n        while(k--)\n        {\n            sum=0;\n            for(auto& ch: convert)\n            {\n               sum+= (ch-48);\n            }\n            convert=to_string(sum);\n        }\n       \n        return sum;\n    }\n};"
    },
    {
        "title": "Sqrt(x)",
        "algo_input": "Given a non-negative integer x,&nbsp;compute and return the square root of x.\n\nSince the return type&nbsp;is an integer, the decimal digits are truncated, and only the integer part of the result&nbsp;is returned.\n\nNote:&nbsp;You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or&nbsp;x ** 0.5.\n\n&nbsp;\nExample 1:\n\nInput: x = 4\nOutput: 2\n\n\nExample 2:\n\nInput: x = 8\nOutput: 2\nExplanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= x &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def mySqrt(self, x: int) -> int:\n        beg =0\n        end =x\n        while beg <=end:\n            mid = (beg+end)//2\n            sqr = mid*mid\n            if sqr == x:\n                return mid\n            elif sqr < x:\n                beg = mid+1\n            else:\n                end = mid-1\n        return end\n        ",
        "solution_js": "/**\n * @param {number} x\n * @return {number}\n */\nvar mySqrt = function(x) {\n    const numx = x;\n    let num = 0;\n\n    while (num <= x) {\n        const avg = Math.floor((num+x) / 2);\n        if (avg * avg > numx) x = avg - 1;\n        else num = avg + 1;\n    }\n    return x;\n};",
        "solution_java": "class Solution {\n    public int mySqrt(int x) {\n        long answer = 0;\n        while (answer * answer <= x) {\n            answer += 1;\n        }\n        return (int)answer - 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mySqrt(int x) {\n        int s = 0 , e = x , mid;\n        \n        while(s<e)\n        {\n            mid = s + (e-s)/2 ;\n            if(e-s == 1)\n                break ;\n            long double sqr = (long double)mid *mid;\n            if(sqr <= x)\n                s = mid ;\n            else\n                e = mid - 1 ;\n        }\n        if(e*e <= x )\n            return e ;\n        else\n            return s ;\n    }\n}; ```"
    },
    {
        "title": "Linked List in Binary Tree",
        "algo_input": "Given a binary tree root and a&nbsp;linked list with&nbsp;head&nbsp;as the first node.&nbsp;\n\nReturn True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree&nbsp;otherwise return False.\n\nIn this context downward path means a path that starts at some node and goes downwards.\n\n&nbsp;\nExample 1:\n\n\n\nInput: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\nExplanation: Nodes in blue form a subpath in the binary Tree.  \n\n\nExample 2:\n\n\n\nInput: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\n\n\nExample 3:\n\nInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: false\nExplanation: There is no path in the binary tree that contains all the elements of the linked list from head.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 2500].\n\tThe number of nodes in the list will be in the range [1, 100].\n\t1 &lt;= Node.val&nbsp;&lt;= 100&nbsp;for each node in the linked list and binary tree.\n\n",
        "solution_py": "class Solution(object):\n    def isSubPath(self, head, root):\n        if not root:\n            return False\n        if self.issame(head, root):\n            return True\n        return self.isSubPath(head, root.left) or self.isSubPath(head, root.right)\n    def issame(self, head, root):\n        if not head:\n            return True\n        if not root:\n            return False\n        if head.val != root.val:\n            return False\n        return self.issame(head.next, root.left) or self.issame(head.next, root.right)",
        "solution_js": "var isSubPath = function(head, root) {\n    if(!root)    return false\n    if(issame(head, root))  return true\n    return isSubPath(head, root.left) || isSubPath(head, root.right)\n};\n\nfunction issame(head, root){\n    if(!head)   return true\n    if(!root)   return false\n    if(head.val != root.val)    return false\n    return issame(head.next, root.left) || issame(head.next, root.right)\n};",
        "solution_java": "class Solution {\n    public boolean isSubPath(ListNode head, TreeNode root) {\n        if(root == null) return false;\n        if(issame(head, root)) return true;\n        return isSubPath(head, root.left) || isSubPath(head, root.right);\n    }\n    private boolean issame(ListNode head, TreeNode root) {\n        if(head == null) return true;\n        if(root == null) return false;\n        if(head.val != root.val) return false;\n        return issame(head.next, root.left) || issame(head.next, root.right);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool func(ListNode *head,TreeNode *root){\n        if(!head) return true;\n        if(!root) return false;\n        if(head->val == root->val) return func(head->next,root->left) or func(head->next,root->right);\n        return false;\n    }\n    bool isSubPath(ListNode* head, TreeNode* root) {\n        if(!root) return false;\n        if(func(head,root)) return true;\n        return isSubPath(head,root->left) or isSubPath(head,root->right); \n    }\n};"
    },
    {
        "title": "Reverse Substrings Between Each Pair of Parentheses",
        "algo_input": "You are given a string s that consists of lower case English letters and brackets.\n\nReverse the strings in each pair of matching parentheses, starting from the innermost one.\n\nYour result should not contain any brackets.\n\n&nbsp;\nExample 1:\n\nInput: s = \"(abcd)\"\nOutput: \"dcba\"\n\n\nExample 2:\n\nInput: s = \"(u(love)i)\"\nOutput: \"iloveu\"\nExplanation: The substring \"love\" is reversed first, then the whole string is reversed.\n\n\nExample 3:\n\nInput: s = \"(ed(et(oc))el)\"\nOutput: \"leetcode\"\nExplanation: First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 2000\n\ts only contains lower case English characters and parentheses.\n\tIt is guaranteed that all parentheses are balanced.\n\n",
        "solution_py": "class Solution:\n    def reverseParentheses(self, s: str) -> str:\n        stack = []\n        ans = \"\"\n        res = deque([])\n        s = list(s)\n        for i in s:\n            if i==\")\":\n                while stack[-1] != \"(\":\n                    res.append(stack.pop())\n                stack.pop()\n                while res:\n                    stack.append(res.popleft())\n            else:\n                stack.append(i)\n        return \"\".join(stack)",
        "solution_js": "function reverse(s){\n    return s.split(\"\").reverse().join(\"\");\n}\n\nfunction solve(s,index) {    \n    let ans = \"\";   \n    let j = index;\n    while(j<s.length)\n    {   \n        if(s[j] == '(')\n        {\n            let store = solve(s,j+1);\n            ans += store.ans;\n            j = store.j;\n        }\n        else if(s[j] == ')')\n            return {ans : reverse(ans),j};          \n        else\n            ans+=s[j];            \n        j++;\n    }    \n        \n    return ans;\n}\n\nvar reverseParentheses = function(s) {\n    return solve(s,0);\n};",
        "solution_java": "class Solution {\n    public String reverseParentheses(String s) {\n        Stack<String> stack = new Stack<>();\n\n        int j = 0;\n        while(j < s.length()){\n            /*\n                We need to keep on adding whatever comes\n                as long as it is not a ')'.\n            */\n            if(s.charAt(j) != ')')\n                stack.push(s.charAt(j)+\"\");\n\n            /*\n                Now that we have encountered an ')', its time\n                to start popping from top of stack unless we find an opening\n                parenthesis\n\n                then we just need to reverse the string formed by popping\n                and put it back on stack.\n\n                Try dry running and it will all make sense\n            */\n            else{\n                StringBuilder sb = new StringBuilder();\n                while(!stack.isEmpty() && !stack.peek().equals(\"(\")){\n                    sb.append(stack.pop());\n                }\n\n                stack.pop();\n                stack.push(sb.reverse().toString());\n            }\n            j++;\n        }\n\n        /*\n            We have our result string in the stack now,\n            we just need to pop it and return the reverse of it.\n        */\n        StringBuilder res = new StringBuilder();\n        while(!stack.isEmpty())\n            res.append(stack.pop());\n\n        return res.reverse().toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reverseParentheses(string s) {\n        stack<int> st;\n        for(int i=0;i<s.size();i++)\n        {\n            if(s[i]=='(')\n            {\n                st.push(i);\n            }\n            else if(s[i]==')')\n            {\n              int strt=st.top();\n              strt=strt+1;\n              int end=i;\n              reverse(s.begin()+strt,s.begin()+end);\n              st.pop();\n            }\n        }\n        string ans=\"\";\n        for(int i=0;i<s.size();i++)\n        {\n            if(s[i]=='(' || s[i]==')')\n            {\n                continue;\n            }\n            ans+=s[i];\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Peeking Iterator",
        "algo_input": "Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.\n\nImplement the PeekingIterator class:\n\n\n\tPeekingIterator(Iterator&lt;int&gt; nums) Initializes the object with the given integer iterator iterator.\n\tint next() Returns the next element in the array and moves the pointer to the next element.\n\tboolean hasNext() Returns true if there are still elements in the array.\n\tint peek() Returns the next element in the array without moving the pointer.\n\n\nNote: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.\n\n&nbsp;\nExample 1:\n\nInput\n[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 2, 2, 3, false]\n\nExplanation\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next();    // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek();    // return 2, the pointer does not move [1,2,3].\npeekingIterator.next();    // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 1000\n\tAll the calls to next and peek are valid.\n\tAt most 1000 calls will be made to next, hasNext, and peek.\n\n\n&nbsp;\nFollow up: How would you extend your design to be generic and work with all types, not just integer?",
        "solution_py": "class PeekingIterator:\n  def __init__ (self,iterator):\n    self.arr = iterator.v \n    self._next = 0 \n    self.is_has_next = True \n  \n  def next(self):\n    val = self.arr[self._next] \n    self.next+=1 \n    if self.next >= len(self.arr):\n      self.is_has_next = False \n    return val \n  \n  def hasNext(self):\n    return self.is_has_next \n  \n  def peek(self):\n    return self.arr[self._next]",
        "solution_js": "var PeekingIterator = function(iterator) {\n    this.iterator = iterator\n    this.curr = iterator.next()\n\n};\n\nPeekingIterator.prototype.peek = function() {\n    return this.curr\n};\n\nPeekingIterator.prototype.next = function() {\n    let temp = this.curr\n    this.curr = this.iterator.next()\n    return temp\n};\n\nPeekingIterator.prototype.hasNext = function() {\n    return this.curr > 0   // the input iterator return -100000000 when next() after it run out of members, instead of return undefined.\n};",
        "solution_java": "// Java Iterator interface reference:\n// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator<Integer> {\n    Queue<Integer> q;\n\tpublic PeekingIterator(Iterator<Integer> iterator) {\n\t    // initialize any member here.\n\t    q= new LinkedList<>();\n        while(iterator.hasNext())\n          q.add(iterator.next());  \n\t}\n\t\n    // Returns the next element in the iteration without advancing the iterator.\n\tpublic Integer peek() {\n        return q.peek();\n\t}\n\t\n\t// hasNext() and next() should behave the same as in the Iterator interface.\n\t// Override them if needed.\n\t@Override\n\tpublic Integer next() {\n\t    return q.remove();\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t    return q.size()!=0;\n\t}\n}",
        "solution_c": "/*\n * Below is the interface for Iterator, which is already defined for you.\n * **DO NOT** modify the interface for Iterator.\n *\n * class Iterator {\n * struct Data;\n * Data* data;\n * public:\n * Iterator(const vector<int>& nums);\n * Iterator(const Iterator& iter);\n *\n * // Returns the next element in the iteration.\n * int next();\n *\n * // Returns true if the iteration has more elements.\n * bool hasNext() const;\n * };\n */\n\nclass PeekingIterator : public Iterator {\npublic:\n    int _nextVal;\n    bool _hasNext;\n    PeekingIterator(const vector<int>& nums) : Iterator(nums) {\n        // Initialize any member here.\n        // **DO NOT** save a copy of nums and manipulate it directly.\n        // You should only use the Iterator interface methods.\n        _nextVal = 0;\n        _hasNext = Iterator::hasNext();\n        if (_hasNext)\n            _nextVal = Iterator::next();\n    }\n\n    // Returns the next element in the iteration without advancing the iterator.\n    int peek() {\n        return (_nextVal);\n    }\n\n    // hasNext() and next() should behave the same as in the Iterator interface.\n    // Override them if needed.\n    int next() {\n        int tmp = _nextVal;\n\n        _hasNext = Iterator::hasNext();\n        if (_hasNext)\n            _nextVal = Iterator::next();\n        return (tmp);\n    }\n\n    bool hasNext() const {\n        return (_hasNext);\n    }\n};"
    },
    {
        "title": "Count Number of Ways to Place Houses",
        "algo_input": "There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.\n\nReturn the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.\n\nNote that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: 4\nExplanation: \nPossible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 9\nExplanation: The 9 possible arrangements are shown in the diagram above.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def countHousePlacements(self, n: int) -> int:\n        \n        \n        @lru_cache(None)\n        def rec(i, k):\n            \n            # i is the index of the house \n            # k is the state of last house, 1 if there was a house on the last index else 0\n            \n            if i>=n:\n                return 1\n            \n            elif k==0:\n                return rec(i+1,1) + rec(i+1,0)\n            \n            else:\n                return rec(i+1,0)\n        \n        \n        \n        #l1 are the combinations possible in lane 1, the final answer will be the square \n\t\t#of of l1 as for every combination of l1 there will be \"l1\" combinations in lane2.\n        \n        l1 = rec(1,0) + rec(1,1)\n        \n        \n        mod = 10**9 +7\n        return pow(l1, 2, mod) #use this when there is mod involved along with power \n            ",
        "solution_js": "const mod = (10 ** 9) + 7\nvar countHousePlacements = function(n) {\n    let prev2 = 1\n    let prev1 = 1\n    let ways = 2\n    \n    for ( let i = 2; i <= n; i++ ) {\n        prev2 = prev1\n        prev1 = ways\n        ways = ( prev1 + prev2 ) % mod\n    }\n    \n    return (ways ** 2) % mod\n}",
        "solution_java": "class Solution {\n    int mod = (int)1e9+7;\n    public int countHousePlacements(int n) {\n        \n        if(n == 1)\n            return 4;\n        if(n == 2)\n            return 9;\n        long a = 2;\n        long b = 3;\n        if(n==1)\n            return (int)(a%mod);\n        if(n==2)\n            return (int)(b%mod);\n        long c=0;\n        for(int i=3;i<=n;i++)\n        {\n            c = (a+b)%mod;\n            a=b%mod;\n            b=c%mod;\n        }\n        \n        return (int)((c*c)%mod);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    typedef long long ll;\n    ll mod = 1e9+7;\n    int countHousePlacements(int n) {\n        ll house=1, space=1;\n        ll total = house+space;\n        for(int i=2;i<=n;i++){\n\t        house = space;\n\t        space = total;\n\t        total = (house+space)%mod;\n\t    }\n\t    return (total*total)%mod;\n    }\n};"
    },
    {
        "title": "Escape the Spreading Fire",
        "algo_input": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:\n\n\n\t0 represents grass,\n\t1 represents fire,\n\t2 represents a wall that you and fire cannot pass through.\n\n\nYou are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.\n\nReturn the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109.\n\nNote that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.\n\nA cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput: 3\nExplanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.\n\nExample 2:\n\nInput: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput: -1\nExplanation: The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.\n\n\nExample 3:\n\nInput: grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput: 1000000000\nExplanation: The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t2 &lt;= m, n &lt;= 300\n\t4 &lt;= m * n &lt;= 2 * 104\n\tgrid[i][j] is either 0, 1, or 2.\n\tgrid[0][0] == grid[m - 1][n - 1] == 0\n\n",
        "solution_py": "class Solution(object):\n    def maximumMinutes(self, A):\n        m, n = len(A), len(A[0])\n        inf = 10 ** 10\n        d = [[0,1],[1,0],[0,-1],[-1,0]]\n        fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1]\n        A = [[inf if a < 2 else -1 for a in r] for r in A]\n\n        def bfs(queue, seen):\n            for i, j, t in queue:\n                if seen[i][j] < inf: continue\n                seen[i][j] = t\n                for di,dj in d:\n                    x, y = i + di, j + dj\n                    if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]:\n                        queue.append([x, y, t + 1])\n        \n        def die(t):\n            seen = [[inf + 10] * n for i in range(m)]\n            bfs([[0, 0, t]], seen)\n            return seen[-1][-1] > A[-1][-1]\n\n        bfs(fires, A)\n        A[-1][-1] += 1\n        return bisect_left(range(10**9 + 1), True, key=die) - 1",
        "solution_js": "var maximumMinutes = function(grid) {\n  let fireSpread = getFireSpreadTime(grid);\n  let low = 0, high = 10 ** 9;\n  while (low < high) {\n    let mid = Math.ceil((low + high) / 2);\n    if (canReachSafehouse(grid, fireSpread, mid)) low = mid;\n    else high = mid - 1;\n  }\n  return canReachSafehouse(grid, fireSpread, low) ? low : -1;\n};\n\nfunction canReachSafehouse(originalGrid, fireSpread, timeToWait) {\n  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n  let grid = originalGrid.map((row) => [...row]);\n  let m = grid.length, n = grid[0].length;\n  let queue = [[0, 0]], time = timeToWait;\n  while (queue.length) {\n    for (let i = queue.length; i > 0; i--) {\n      let [row, col] = queue.shift();\n      if (row === m - 1 && col === n - 1) {\n        return true;\n      }\n      for (let [x, y] of directions) {\n        let newX = row + x, newY = col + y;\n        if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass\n        let isTarget = newX === m - 1 && newY === n - 1;\n        if ((isTarget && time + 1 <= fireSpread[newX][newY]) || time + 1 < fireSpread[newX][newY]) { // only visit if fire will not spread to new cell at the next minute\n          grid[newX][newY] = 1;\n          queue.push([newX, newY]);\n        }\n      }\n    }\n    time++;\n  }\n  return false;\n}\n\nfunction getFireSpreadTime(originalGrid) {\n  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n  let grid = originalGrid.map((row) => [...row]);\n  let m = grid.length, n = grid[0].length;\n  let queue = [];\n  for (let i = 0; i < m; i++) {\n    for (let j = 0; j < n; j++) {\n      if (grid[i][j] === 1) {\n        queue.push([i, j]);\n      }\n    }\n  }\n  \n  let time = 0, fireSpread = Array(m).fill(0).map(() => Array(n).fill(Infinity));\n  while (queue.length) {\n    for (let i = queue.length; i > 0; i--) {\n      let [row, col] = queue.shift();\n      fireSpread[row][col] = time;\n      for (let [x, y] of directions) {\n        let newX = row + x, newY = col + y;\n        if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass\n        grid[newX][newY] = 1;\n        queue.push([newX, newY]);\n      }\n    }\n    time++;\n  }\n  return fireSpread;\n}",
        "solution_java": "import java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\nclass Solution {\n\n    public boolean ok(int[][] grid, int[][] dist, int wait_time) {\n        int n = grid.length;\n        int m = grid[0].length;\n\n        Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>();\n        Q.add(new Pair<>(0, 0, wait_time));\n\n        int[][] visited = new int[n][m];\n        visited[0][0] = 1;\n\n        while (!Q.isEmpty()) {\n            Pair<Integer, Integer, Integer> at = Q.poll();\n            int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n            for (int[] to : moves) {\n                int ii = at.first + to[0];\n                int jj = at.second + to[1];\n                if (!inBounds(ii, jj, n, m) || visited[ii][jj] == 1 || grid[ii][jj] == 2) continue;\n                if (ii == n - 1 && jj == m - 1 && dist[ii][jj] >= at.third + 1) return true;\n                if (dist[ii][jj] <= at.third + 1) continue;\n                Q.add(new Pair<>(ii, jj, 1 + at.third));\n                visited[ii][jj] = 1;\n            }\n        }\n        return false;\n    }\n\n    public boolean inBounds(int i, int j, int n, int m) {\n        return (0 <= i && i < n && 0 <= j && j < m);\n    }\n\n    public int maximumMinutes(int[][] grid) {\n        int n = grid.length;\n        int m = grid[0].length;\n\n        int[][] dist = new int[n][m];\n\n        for (int[] r : dist) Arrays.fill(r, Integer.MAX_VALUE);\n\n        Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>();\n\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                if (grid[i][j] == 1) {\n                    Q.add(new Pair<>(i, j, 0));\n                    dist[i][j] = 0;\n                }\n            }\n        }\n\n        while (!Q.isEmpty()) {\n            Pair<Integer, Integer, Integer> at = Q.poll();\n            int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n            for (int[] to : moves) {\n                int ii = at.first + to[0];\n                int jj = at.second + to[1];\n                if (!inBounds(ii, jj, n, m) || grid[ii][jj] == 2 || dist[ii][jj] <= at.third + 1) continue;\n                dist[ii][jj] = 1 + at.third;\n                Q.add(new Pair<>(ii, jj, 1 + at.third));\n            }\n        }\n\n        int left = 0;\n        int right = 1_000_000_000;\n\n        int ans = -1;\n\n        while (left <= right) {\n            int mid = left + (right - left) / 2;\n            if (ok(grid, dist, mid)) {\n                ans = mid;\n                left = mid + 1;\n            } else right = mid - 1;\n        }\n\n        return ans;\n    }\n\n    static class Pair<T, K, L> {\n        T first;\n        K second;\n        L third;\n\n        public Pair(T first, K second, L third) {\n            this.first = first;\n            this.second = second;\n            this.third = third;\n        }\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumMinutes(vector<vector<int>>& grid) {\n        int m = grid.size();\n        int n = grid[0].size();\n        vector<vector<int>> firetime(m, vector<int>(n, INT_MAX));\n        queue<pair<int, int>> q;\n        // push fire positions into queue, and set the time as 0\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                if(grid[i][j]==1){\n                    q.push(make_pair(i, j));\n                    firetime[i][j] = 0;\n                }\n            }\n        }\n        int time = 0;\n        pair<int, int> xy;\n        int x,y;\n        // use BFS to find fire spread time\n        while(!q.empty()){\n            int points = q.size();\n            time++;\n            for(int i=0; i<points; i++){\n                xy = q.front();\n                q.pop();\n                x = xy.first, y = xy.second;\n                if(x-1>=0 && grid[x-1][y]==0 && firetime[x-1][y]==INT_MAX){\n                    q.push(make_pair(x-1, y));\n                    firetime[x-1][y] = time;\n                }\n                if(x+1<m && grid[x+1][y]==0 && firetime[x+1][y]==INT_MAX){\n                    q.push(make_pair(x+1, y));\n                    firetime[x+1][y] = time;\n                }\n                if(y-1>=0 && grid[x][y-1]==0 && firetime[x][y-1]==INT_MAX){\n                    q.push(make_pair(x, y-1));\n                    firetime[x][y-1] = time;\n                }\n                if(y+1<n && grid[x][y+1]==0 && firetime[x][y+1]==INT_MAX){\n                    q.push(make_pair(x, y+1));\n                    firetime[x][y+1] = time;\n                }\n            }\n        }\n        vector<vector<int>> peopletime(m, vector<int>(n, INT_MAX));\n        time = 0;\n        // push the initial position of the top left cell into the queue\n        // and set the time as 0\n        q.push(make_pair(0, 0));\n        peopletime[0][0] = 0;\n        // use BFS to find the traversal time\n        while(!q.empty()){\n            int points = q.size();\n            time++;\n            for(int i=0; i<points; i++){\n                xy = q.front();\n                q.pop();\n                x = xy.first, y = xy.second;\n                if(x-1>=0 && grid[x-1][y]==0 && peopletime[x-1][y]==INT_MAX && firetime[x-1][y]>time){\n                    q.push(make_pair(x-1, y));\n                    peopletime[x-1][y] = time;\n                }\n                if(x+1<m && grid[x+1][y]==0 && peopletime[x+1][y]==INT_MAX && firetime[x+1][y]>time){\n                    q.push(make_pair(x+1, y));\n                    peopletime[x+1][y] = time;\n                }\n                if(y-1>=0 && grid[x][y-1]==0 && peopletime[x][y-1]==INT_MAX && firetime[x][y-1]>time){\n                    q.push(make_pair(x, y-1));\n                    peopletime[x][y-1] = time;\n                }\n                if(y+1<n && grid[x][y+1]==0 && peopletime[x][y+1]==INT_MAX && firetime[x][y+1]>time){\n                    q.push(make_pair(x, y+1));\n                    peopletime[x][y+1] = time;\n                }\n                if(((x==m-2 && y==n-1) || (x==m-1 && y==n-2))&&(firetime[m-1][n-1]<=time)){\n                    q.push(make_pair(m-1, n-1));\n                    peopletime[m-1][n-1] = time;\n                }\n            }\n        }\n        // if you cannot reach the safehouse or fire reaches the safehouse first,\n        // return -1\n        if(peopletime[m-1][n-1]==INT_MAX || firetime[m-1][n-1]<peopletime[m-1][n-1]){\n            return -1;\n        }\n        // if fire can never reach the safehouse,\n        // return 1000000000\n        if(firetime[m-1][n-1]==INT_MAX){\n            return 1000000000;\n        }\n        if(firetime[m-1][n-1]==peopletime[m-1][n-1]){\n            return 0;\n        }\n        int diff = (firetime[m-1][n-1]-peopletime[m-1][n-1]);\n        if(m>1 && n>1){\n            if(peopletime[m-2][n-1]!=INT_MAX && peopletime[m-1][n-2]!=INT_MAX && ((firetime[m-2][n-1]-peopletime[m-2][n-1])>diff || (firetime[m-1][n-2]-peopletime[m-1][n-2]>diff))){\n                return diff;\n            }\n        }\n        return diff-1;\n    }\n};"
    },
    {
        "title": "Pyramid Transition Matrix",
        "algo_input": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.\n\nTo make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given&nbsp;as a list of&nbsp;three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.\n\n\n\tFor example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom.\n\n\nYou start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.\n\nGiven bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput: true\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.\n\n\nExample 2:\n\nInput: bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput: false\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= bottom.length &lt;= 6\n\t0 &lt;= allowed.length &lt;= 216\n\tallowed[i].length == 3\n\tThe letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.\n\tAll the values of allowed are unique.\n\n",
        "solution_py": "class Solution(object):\n    def pyramidTransition(self, bottom, allowed):\n        \"\"\"\n        :type bottom: str\n        :type allowed: List[str]\n        :rtype: bool    \n        \"\"\"\n        dic = defaultdict(list)\n        for i in allowed:\n            dic[(i[0], i[1])].append(i[2])\n        \n        res = []\n        \n        def dfs(arr, nxt):\n            #base case second floor and check top exists\n            if len(arr) == 2 and dic[(arr[0], arr[1])]:\n                return True\n            \n            #go to the next row now\n            if len(arr) == len(nxt) + 1:\n                return dfs(nxt, [])\n\n            #keep iterating the same row\n            if dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n                for val in dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n                    if dfs(arr, nxt + [val]):\n                        return True\n            return False\n        \n        return dfs(bottom, [])",
        "solution_js": "var pyramidTransition = function(bottom, allowed) {\n    const set = new Set(allowed);\n    const memo = new Map();\n    const chars = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"];\n    \n    return topDown(bottom, bottom.length - 1);\n    \n    function topDown(prev, row) {\n        const key = `${prev}#${row}`;\n        \n        if (row === 0) return true;\n        if (memo.has(key)) return memo.get(key);\n\n        let pats = new Set();\n        pats.add(\"\");\n\n        for (let i = 0; i < row; i++) {\n            const tmp = new Set();\n\n            const leftBot = prev.charAt(i);\n            const rightBot = prev.charAt(i + 1);\n\n            for (const char of chars) {\n                const triadStr = leftBot + rightBot + char;\n\n                if (set.has(triadStr)) {\n                    for (const pat of pats) {\n                        tmp.add(pat + char);\n                    }                 \n                }\n            }\n          \n            pats = tmp;\n        }\n        \n        for (const pat of pats) {\n            if (topDown(pat, row - 1)) return true;\n        }\n        \n        memo.set(key, false);\n        return false;\n    }\n};",
        "solution_java": "class Solution {\n    HashMap<String, List<Character>> map = new HashMap<>();\n    HashMap<String, Boolean> dp = new HashMap<>();\n    \n    public boolean pyramidTransition(String bottom, List<String> allowed) {\n        for(String s:allowed){\n            String sub = s.substring(0,2);\n            \n            char c = s.charAt(2);\n            \n            if(!map.containsKey(sub))\n                map.put(sub, new ArrayList<>());\n            \n            map.get(sub).add(c);\n        }\n        \n        return dfs(bottom, \"\", 0);\n    }\n    \n    boolean dfs(String currBottom, String newBottom, int index){\n        \n        if(currBottom.length()==1)\n            return true;\n        if(index+1>=currBottom.length())\n            return false;\n        \n        String sub = currBottom.substring(index,index+2);\n        \n        String state = currBottom+\" \"+newBottom+\" \"+index;\n        \n        if(dp.containsKey(state))\n            return dp.get(state);\n        \n        if(map.containsKey(sub)){\n            List<Character> letters = map.get(sub);\n            \n            for(char c:letters){\n                if(index==currBottom.length()-2){\n                    if(dfs(newBottom+c, \"\", 0))\n                    {\n                        dp.put(state, true);\n                        return true;\n                    }\n                }\n                else if(dfs(currBottom, newBottom+c, index+1))\n                {\n                    dp.put(state, true);\n                    return true;\n                }\n            }\n        }\n        \n        dp.put(state, false);\n        return false;\n    }\n}",
        "solution_c": "class Solution {\n    unordered_map<string,vector<char> > m;\npublic:\n    bool dfs(string bot,int i,string tem){\n        if(bot.size()==1) return true;\n        if(i==bot.size()-1) {\n            string st;\n            return dfs(tem,0,st);\n        }\n        for(auto v:m[bot.substr(i,2)]){\n            tem.push_back(v);\n            if(dfs(bot,i+1,tem)){\n                return true;\n            }\n            tem.pop_back();\n        }\n        return false;\n    }\n    bool pyramidTransition(string bottom, vector<string>& allowed) {\n        for(auto a:allowed){\n            m[a.substr(0,2)].push_back(a[2]);\n        }\n        string te;\n        return dfs(bottom,0,te);\n    }\n};"
    },
    {
        "title": "Elimination Game",
        "algo_input": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:\n\n\n\tStarting from left to right, remove the first number and every other number afterward until you reach the end of the list.\n\tRepeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.\n\tKeep repeating the steps again, alternating left to right and right to left, until a single number remains.\n\n\nGiven the integer n, return the last number that remains in arr.\n\n&nbsp;\nExample 1:\n\nInput: n = 9\nOutput: 6\nExplanation:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr = [2, 4, 6, 8]\narr = [2, 6]\narr = [6]\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def lastRemaining(self, n: int) -> int:\n        beg = 1\n        len = n\n        d = 1\n        fromleft = True\n\n        while len > 1:\n            if(fromleft or len%2 == 1):\n                beg += d\n            d <<= 1\n            len >>= 1\n            fromleft = not fromleft\n        \n        return beg",
        "solution_js": "var lastRemaining = function(n) {\n    let sum=1;  let num=1;  let bool=true;\n    while(n>1){       \n        if(bool){sum+=num; bool=false;}\n        else{if(n%2){sum+=num;} bool=true;}\n        num*=2; n=Math.floor(n/2);\n    }\n    return sum;\n}; ",
        "solution_java": "class Solution {\n    public int lastRemaining(int n) {\n        int head = 1;\n        int remain = n;\n        boolean left = true;\n        int step =1;\n        \n        while(remain > 1){\n            if(left || remain%2==1){\n                head = head + step;\n            }\n            remain /= 2;\n            step *= 2;\n            left = !left;\n        }\n        return head;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lastRemaining(int n) {\n        bool left=true;\n        int head=1,step=1;//step is the difference between adjacent elements.\n        while(n>1){\n            if(left || (n&1)){//(n&1)->odd\n                head=head+step;\n            }\n            step=step*2;\n            n=n/2;\n            left=!left;\n        }\n        return head;\n    }\n};"
    },
    {
        "title": "Middle of the Linked List",
        "algo_input": "Given the head of a singly linked list, return the middle node of the linked list.\n\nIf there are two middle nodes, return the second middle node.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5]\nOutput: [3,4,5]\nExplanation: The middle node of the list is node 3.\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5,6]\nOutput: [4,5,6]\nExplanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 100].\n\t1 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        # basically we create two pointers\n        # move one pointer extra fast\n        # another pointer would be slow\n        # when fast reaches end slow would be in mid\n        slow = fast = head\n        while fast and fast.next:\n            slow = slow.next\n            fast = fast.next.next\n        return slow",
        "solution_js": "var middleNode = function(head) {\n    var runner1 = head\n    var runner2 = head?.next\n    while(runner1 && runner2) {\n        runner1 = runner1?.next\n        runner2 = (runner2?.next)?.next\n    }\n    return runner1\n};",
        "solution_java": "class Solution {\n    public ListNode middleNode(ListNode head) {\n        \n        ListNode temp = head;\n        int size = 0;\n        while(temp!=null){\n            size++;\n            temp = temp.next;\n        }\n        int mid = size/2;\n        temp = head;\n        for(int i=0;i<mid;i++){\n            temp = temp.next;\n        }\n        \n        return temp;\n        \n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* middleNode(ListNode* head) {\n         ListNode * slow=head;\n        ListNode * fast=head;\n        while(fast!=NULL && fast->next!=NULL){\n            slow=slow->next;\n            fast=fast->next->next;\n        }\n        return slow;\n    }\n};"
    },
    {
        "title": "Design a Food Rating System",
        "algo_input": "Design a food rating system that can do the following:\n\n\n\tModify the rating of a food item listed in the system.\n\tReturn the highest-rated food item for a type of cuisine in the system.\n\n\nImplement the FoodRatings class:\n\n\n\tFoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.\n\n\t\n\t\tfoods[i] is the name of the ith food,\n\t\tcuisines[i] is the type of cuisine of the ith food, and\n\t\tratings[i] is the initial rating of the ith food.\n\t\n\t\n\tvoid changeRating(String food, int newRating) Changes the rating of the food item with the name food.\n\tString highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.\n\n\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n\n&nbsp;\nExample 1:\n\nInput\n[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]\nOutput\n[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]\n\nExplanation\nFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n                                    // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n                                      // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n                                      // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n                                      // Both \"sushi\" and \"ramen\" have a rating of 16.\n                                      // However, \"ramen\" is lexicographically smaller than \"sushi\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 104\n\tn == foods.length == cuisines.length == ratings.length\n\t1 &lt;= foods[i].length, cuisines[i].length &lt;= 10\n\tfoods[i], cuisines[i] consist of lowercase English letters.\n\t1 &lt;= ratings[i] &lt;= 108\n\tAll the strings in foods are distinct.\n\tfood will be the name of a food item in the system across all calls to changeRating.\n\tcuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.\n\tAt most 2 * 104 calls in total will be made to changeRating and highestRated.\n\n",
        "solution_py": "from heapq import heapify, heappop, heappush\n\nclass RatedFood:\n    def __init__(self, rating, food):\n        self.rating = rating\n        self.food = food\n        \n    def __lt__(self, other):\n        if other.rating == self.rating:\n            return self.food < other.food\n        return self.rating < other.rating\n\nclass FoodRatings:\n    def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n        self.cuis_to_score_heap = defaultdict(list)\n        self.food_to_latest_ratings = defaultdict(int)\n        self.food_to_cuis = defaultdict(str)\n        \n        for food, cuis, rating in zip(foods, cuisines, ratings):\n            self.food_to_cuis[food] = cuis\n            self.food_to_latest_ratings[food] = rating\n            heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food))\n        \n        \n\n    def changeRating(self, food: str, newRating: int) -> None:\n        self.food_to_latest_ratings[food] = newRating\n        cuis = self.food_to_cuis[food]\n        heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food))\n        \n\n    def highestRated(self, cuisine: str) -> str:\n        while True:\n            ratedFood = heappop(self.cuis_to_score_heap[cuisine])\n            if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating):\n\t\t\t\n\t\t\t\t# because the food item is still valid, we put it back into the heap\n                heappush(self.cuis_to_score_heap[cuisine], ratedFood)\n\t\t\t\t\n                return ratedFood.food",
        "solution_js": "var FoodRatings = function(foods, cuisines, ratings) {\n  this.heaps = {}, this.foods = {};\n  let n = foods.length;\n  for (let i = 0; i < n; i++) {\n    let food = foods[i], cuisine = cuisines[i], rating = ratings[i];\n    if (!this.heaps[cuisine]) this.heaps[cuisine] = new PriorityQueue((a, b) => { // [food, rating]\n      return a[1] === b[1] ? a[0].localeCompare(b[0]) : b[1] - a[1];\n    })\n    this.heaps[cuisine].add([food, rating]);\n    this.foods[food] = { cuisine, rating };\n  }\n};\n\nFoodRatings.prototype.changeRating = function(food, newRating) {\n  this.foods[food].rating = newRating;\n  let { cuisine } = this.foods[food];\n  this.heaps[cuisine].add([food, newRating]);\n};\n\nFoodRatings.prototype.highestRated = function(cuisine) {\n  let heap = this.heaps[cuisine];\n  while (this.foods[heap.top()[0]].rating !== heap.top()[1]) {\n    heap.remove();\n  }\n  return heap.top()[0];\n};\n\nclass PriorityQueue {\n  constructor(comparator = ((a, b) => a - b)) {\n    this.values = [];\n    this.comparator = comparator;\n    this.size = 0;\n  }\n  add(val) {\n    this.size++;\n    this.values.push(val);\n    let idx = this.size - 1, parentIdx = Math.floor((idx - 1) / 2);\n    while (parentIdx >= 0 && this.comparator(this.values[parentIdx], this.values[idx]) > 0) {\n      [this.values[parentIdx], this.values[idx]] = [this.values[idx], this.values[parentIdx]];\n      idx = parentIdx;\n      parentIdx = Math.floor((idx - 1) / 2);\n    }\n  }\n  remove() {\n    if (this.size === 0) return -1;\n    this.size--;\n    if (this.size === 0) return this.values.pop();\n    let removedVal = this.values[0];\n    this.values[0] = this.values.pop();\n    let idx = 0;\n    while (idx < this.size && idx < Math.floor(this.size / 2)) {\n      let leftIdx = idx * 2 + 1, rightIdx = idx * 2 + 2;\n      if (rightIdx === this.size) {\n        if (this.comparator(this.values[leftIdx], this.values[idx]) > 0) break;\n        [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]];\n        idx = leftIdx;\n      } else if (this.comparator(this.values[leftIdx], this.values[idx]) < 0 || this.comparator(this.values[rightIdx], this.values[idx]) < 0) {\n        if (this.comparator(this.values[leftIdx], this.values[rightIdx]) <= 0) {\n          [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]];\n          idx = leftIdx;\n        } else {\n          [this.values[rightIdx], this.values[idx]] = [this.values[idx], this.values[rightIdx]];\n          idx = rightIdx;\n        }\n      } else {\n        break;\n      }\n    }\n    return removedVal;\n  }\n  top() {\n    return this.values[0];\n  }\n  isEmpty() {\n    return this.size === 0;\n  }\n}",
        "solution_java": "class FoodRatings {\n    HashMap<String, TreeSet<String>> cuiToFood = new HashMap();\n    HashMap<String, Integer> foodToRat = new HashMap();\n    HashMap<String, String> foodToCui = new HashMap();\n    public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {\n        for(int i = 0; i < foods.length; i++){\n            TreeSet<String> foodOfThisCuisine = cuiToFood.getOrDefault(cuisines[i], new TreeSet<String> ((a,b)->\n            foodToRat.get(a).equals(foodToRat.get(b)) ? a.compareTo(b) : foodToRat.get(b)-foodToRat.get(a)));\n\t\t\t\n\t\t\t// Both comparators are equal\n\t\t\t/* new Comparator<String>(){\n                @Override\n                public int compare(String a, String b){\n                    int aRat = foodToRat.get(a);\n                    int bRat = foodToRat.get(b);\n                    \n                    if(aRat != bRat) return bRat - aRat; // largest rating first\n                    for(int i = 0; i < Math.min(a.length(), b.length()); i++){\n                        if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i);\n                    }\n                    return a.length() - b.length();\n                }\n            })\n\t\t\t*/\n            \n            foodToRat.put(foods[i], ratings[i]);\n            foodOfThisCuisine.add(foods[i]);\n            foodToCui.put(foods[i], cuisines[i]);    \n            \n            cuiToFood.put(cuisines[i], foodOfThisCuisine);\n        }\n    }\n    \n    // CompareTo() is used to compare whether 2 strings are equal in hashSet! So remove, change value of key in HashMap, then insert again\n    public void changeRating(String food, int newRating) {\n        String cui = foodToCui.get(food);\n        TreeSet<String> foodOfThisCui = cuiToFood.get(cui);\n        foodOfThisCui.remove(food);\n        foodToRat.put(food, newRating);\n        \n        foodOfThisCui.add(food);\n        cuiToFood.put(cui, foodOfThisCui);\n    }\n    \n    public String highestRated(String cuisine) {\n        return cuiToFood.get(cuisine).first();\n    }\n}",
        "solution_c": "class FoodRatings {\npublic:\n    unordered_map<string, set<pair<int, string>>> cuisine_ratings;\n    unordered_map<string, string> food_cuisine;\n    unordered_map<string, int> food_rating;\n    FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {\n        for (int i = 0; i < foods.size(); ++i) {\n            cuisine_ratings[cuisines[i]].insert({ -ratings[i], foods[i] });\n            food_cuisine[foods[i]] = cuisines[i];\n            food_rating[foods[i]] = ratings[i];\n        }\n    }\n    void changeRating(string food, int newRating) {\n        auto &cuisine = food_cuisine.find(food)->second;\n        cuisine_ratings[cuisine].erase({ -food_rating[food], food });\n        cuisine_ratings[cuisine].insert({ -newRating, food });\n        food_rating[food] = newRating;\n    }\n    string highestRated(string cuisine) {\n        return begin(cuisine_ratings[cuisine])->second;\n    }\n};"
    },
    {
        "title": "Champagne Tower",
        "algo_input": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.&nbsp; Each glass holds one cup&nbsp;of champagne.\n\nThen, some champagne is poured into the first glass at the top.&nbsp; When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.&nbsp; When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.&nbsp; (A glass at the bottom row has its excess champagne fall on the floor.)\n\nFor example, after one cup of champagne is poured, the top most glass is full.&nbsp; After two cups of champagne are poured, the two glasses on the second row are half full.&nbsp; After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.&nbsp; After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\n\n\n\nNow after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)\n\n&nbsp;\nExample 1:\n\nInput: poured = 1, query_row = 1, query_glass = 1\nOutput: 0.00000\nExplanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\n\n\nExample 2:\n\nInput: poured = 2, query_row = 1, query_glass = 1\nOutput: 0.50000\nExplanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\n\n\nExample 3:\n\nInput: poured = 100000009, query_row = 33, query_glass = 17\nOutput: 1.00000\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;=&nbsp;poured &lt;= 109\n\t0 &lt;= query_glass &lt;= query_row&nbsp;&lt; 100\n",
        "solution_py": "class Solution:\n    def champagneTower(self, poured: int, r: int, c: int) -> float:\n        quantity=defaultdict(int)\n        quantity[(0,0)]=poured\n        for i in range(r+1):\n            flag=False\n            for j in range(i+1):\n                prev_flow=quantity[(i,j)]-1\n                if prev_flow<=0:\n                    continue\n                flag=True\n                quantity[(i,j)]=1\n                quantity[(i+1,j)]+=prev_flow/2\n                quantity[(i+1,j+1)]+=prev_flow/2\n            if not flag: break\n        return quantity[(r,c)]",
        "solution_js": "var champagneTower = function(poured, query_row, query_glass) {\n    \n    let water = [poured];\n    let hasOverflow = true;\n    let row = 0;\n\n    while(true){\n        \n        if (! hasOverflow) return 0   // We haven't reached query_row yet, and water ran out\n        hasOverflow = false;\n        \n        let rowGlass = Array(water.length).fill(0);    // List of glasses at current row\n        for (let i = 0; i < rowGlass.length; i++){\n            let input = water[i];\n            if (input <= 1){\n                rowGlass[i] = input;\n                water[i] = 0\n            }else{\n                rowGlass[i] = 1;\n                water[i]--\n            }\n            if (row == query_row && i == query_glass){  // Return if we reach goal before water run out\n                return rowGlass[i]\n            }\n        }\n        // console.log('row,rowGlass',row,rowGlass);  // to debug\n        \n        let nextWater = Array(water.length + 1).fill(0);  // water poured towards next row, \n        for (let i = 0; i < rowGlass.length; i++){\n            let overflow = water[i];\n            \n            if (overflow > 0) hasOverflow = true;\n            \n            nextWater[i] += overflow / 2;\n            nextWater[i+1] += overflow / 2;\n        }\n        water = nextWater;\n        row ++;\n    }\n};",
        "solution_java": "// Champagne Tower\n// Leetcode: https://leetcode.com/problems/champagne-tower/\n\nclass Solution {\n    public double champagneTower(int poured, int query_row, int query_glass) {\n        if (poured == 0) return 0;\n        double[] memo = new double[101];\n        memo[0] = poured;\n        for (int i=0; i<100; i++) {\n            for (int j=i; j>=0; j--) {\n                if (memo[j] > 1) {\n                    if (i == query_row && j == query_glass) return 1;\n                    double val = (memo[j] - 1) / 2;\n                    memo[j+1] += val;\n                    memo[j] = val;\n                } else {\n                    if (i == query_row && j == query_glass) return memo[query_glass];\n                    memo[j+1] += 0;\n                    memo[j] = 0;\n                }\n            }\n        }\n        return memo[query_glass];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double champagneTower(int poured, int query_row, int query_glass) {\n        vector<double> currRow(1, poured);\n\t\t\n        for(int i=0; i<=query_row; i++){ //we need to make the dp matrix only till query row. No need to do after that\n            vector<double> nextRow(i+2, 0); //If we are at row 0, row 1 will have 2 glasses. So next row will have currRow number + 2 number of glasses.\n            for(int j=0; j<=i; j++){ //each row will have currRow number + 1 number of glasses.\n                if(currRow[j]>=1){ //if the champagne from the current glass is being overflowed.\n                    nextRow[j] += (currRow[j]-1)/2.0; //fill the left glass with the overflowing champagne\n                    nextRow[j+1] += (currRow[j]-1)/2.0; //fill the right glass with the overflowing champagne\n                    currRow[j] = 1; //current glass will store only 1 cup of champagne\n                }\n            }\n            if(i!=query_row) currRow = nextRow; //change the currRow for the next iteration. But if we have already reached the query_row, then the next iteration will not even take place, so the currRow is the query_row itself. So don't change as we need the currRow only.\n        }\n        return currRow[query_glass];\n    }\n};"
    },
    {
        "title": "Percentage of Letter in String",
        "algo_input": "Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.\n\n&nbsp;\nExample 1:\n\nInput: s = \"foobar\", letter = \"o\"\nOutput: 33\nExplanation:\nThe percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.\n\n\nExample 2:\n\nInput: s = \"jjjj\", letter = \"k\"\nOutput: 0\nExplanation:\nThe percentage of characters in s that equal the letter 'k' is 0%, so we return 0.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of lowercase English letters.\n\tletter is a lowercase English letter.\n\n",
        "solution_py": "class Solution:\n    def percentageLetter(self, s: str, letter: str) -> int:\n        return (s.count(letter)*100)//len(s)",
        "solution_js": "var percentageLetter = function(s, letter) {\n    let count = 0;\n    for (let i of s) { // count how many letters are in s\n        if (i == letter) count++;\n    }\n    return (Math.floor((count*1.0) / (s.length*1.0) * 100)) // get percentage\n};",
        "solution_java": "class Solution {\n    public int percentageLetter(String str, char letter) {\n        int count=0;\n        int n=str.length();\n        for(int i=0;i<n;i++){\n            if(str.charAt(i)==letter){\n\n                count ++;\n            }\n        }\n                 int per= (100*count)/n;\n         return per;   \n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int percentageLetter(string s, char letter) {\n        int count=0;\n        for(int i=0;i<s.length();i++)\n        {  if(s[i]==letter)\n            {\n                count++;\n            }\n        }\n        return (count*100)/s.length();\n        \n    }\n};"
    },
    {
        "title": "Car Fleet II",
        "algo_input": "There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:\n\n\n\tpositioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni &lt; positioni+1.\n\tspeedi is the initial speed of the ith car in meters per second.\n\n\nFor simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\n\nReturn an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.\n\n&nbsp;\nExample 1:\n\nInput: cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput: [1.00000,-1.00000,3.00000,-1.00000]\nExplanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n\n\nExample 2:\n\nInput: cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput: [2.00000,1.00000,1.50000,-1.00000]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= cars.length &lt;= 105\n\t1 &lt;= positioni, speedi &lt;= 106\n\tpositioni &lt; positioni+1\n\n",
        "solution_py": "class Car:\n    def __init__(self, pos, speed, idx, prev=None, next=None):\n        self.pos = pos\n        self.speed = speed\n        self.idx = idx\n        self.prev = prev\n        self.next = next\n\nclass Solution:\n    def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n        colis_times = [-1] * len(cars)\n        cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n        for i in range(len(cars)-1): cars[i].next = cars[i+1]\n        for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n        \n        catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n                        for i, (a, b) \n                        in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n        heapify(catchup_order)\n        \n        while catchup_order:\n            catchup_time, idx, car = heappop(catchup_order)\n            if colis_times[idx] > -1: continue # ith car has already caught up\n            colis_times[idx] = catchup_time\n            if not car.prev: continue # no car is following us\n            car.prev.next, car.next.prev = car.next, car.prev\n            if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n            new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n            heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n        \n        return colis_times",
        "solution_js": "var getCollisionTimes = function(cars) {\n    // create a stack to hold all the indicies of the cars that can be hit\n    const possibleCarsToHit = [];\n    const result = new Array(cars.length).fill(-1);\n\t\n    for (let i = cars.length - 1; i >= 0; i--) {\n\t\n\t    // if there are cars to hit, check if the current car will hit the car before or after hitting\n\t\t// the car in front of them\n\t\t// you can also think of this as if the current car will hit the car before or after being absorbed by\n\t\t// the slower car in front.\n        while (possibleCarsToHit.length && result[possibleCarsToHit[possibleCarsToHit.length - 1]] >= 0) {\n            const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];\n            const timeToCatchNextCar = \n                getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);\n            const timeToCatchNextNextCar = result[nextCarIndex];\n            if (timeToCatchNextCar > 0 && \n                timeToCatchNextCar <= timeToCatchNextNextCar) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t// pop off the stack because the car was absorbed by the next car\n\t\t\t// before getting hit by the current car\n            possibleCarsToHit.pop();\n        }\n        if (possibleCarsToHit.length) {\n            const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];\n            result[i] = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);\n        }\n        possibleCarsToHit.push(i);\n    }\n    return result;\n};\n    \n    \nfunction getTimeToCatchNextCar(leftCar, rightCar) {\n    const [leftCarPosition, leftCarSpeed] = leftCar\n    const [rightCarPosition, rightCarSpeed] = rightCar;\n    const distanceToCatchCar = rightCarPosition - leftCarPosition;\n    const differenceInSpeed = leftCarSpeed - rightCarSpeed;\n    return differenceInSpeed > 0 ? distanceToCatchCar / differenceInSpeed : -1;\n}",
        "solution_java": "class Solution {\n    public double[] getCollisionTimes(int[][] cars) {\n        int n = cars.length;\n        double[] res = new double[n];\n        Arrays.fill(res, -1.0);\n\n        // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that\n        // after catching c2, we may view c1 as non-existing (cars before c1 may not catches c1);\n\n        /** Define a stack storing the index of cars as follows:\n\n        Assuming cars c_0, c_1, c_2, ... , c_k are in the stack, they satisfy:\n            1. v0 > v1 > v2 ... > vk where v_i is the velocity of car c_i\n            2. c_(i+1) is the car that c_i vanishes into\n\n        Namely, if only these cars exist, then what will happened is that c_0 vanishes into c_1,\n        then c_1 vanishes into c_2, ..., c_(k-1) vanishes into c_k;\n        */\n        Deque<Integer> stack = new LinkedList<>();\n        for (int i = n-1; i >= 0; i--) {\n            int[] c1 = cars[i];\n            while (!stack.isEmpty()) {\n                int j = stack.peekLast();\n                int[] c2 = cars[j];\n\n                /** If both conditions are satisfied:\n                    1. c1 is faster than c2\n                    2. c1 catches c2 before c2 vanishes into other car\n\n                Then we know that c2 is the car that c1 catches first (i.e., c1 vanishes into c2)\n                    ==> get the result for c1\n\n                Note neither c1 nor c2 is polled out from the stack considering the rule of stack.\n                */\n\n                if (c1[1] > c2[1] && (res[j] == -1.0 || catchTime(cars, i, j) <= res[j])) {\n                    res[i] = catchTime(cars, i, j);\n                    break;\n                }\n\n                /** Now we have either one of situations\n                    1. c1 is slower than c2\n                    2. c1 potentially catches c2 AFTER c2 vanishes\n\n                    Claim: no car before c1 will vanish into c2\n\n                    1. ==> cars before c1 will vanish into c1 first before catching c2\n                    2. <==> c2 \"vanishes\" into another car even before c1 catches it\n\n                Either way, c2 can not be catched by c1 or cars beofre c1 ==> poll it out from stack\n\n                */\n                stack.pollLast();\n            }\n            stack.offerLast(i);\n        }\n        return res;\n    }\n\n    // time for cars[i] to catch cars[j]\n    private double catchTime(int[][] cars, int i, int j) {\n        int dist = cars[j][0] - cars[i][0];\n        int v = cars[i][1] - cars[j][1];\n\n        return (double)dist / v;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<double> getCollisionTimes(vector<vector<int>>& cars)\n    {\n        int n = cars.size();\n        vector<double> res(n,-1.0);\n        stack<int> st;// for storing indices\n        for(int i=n-1;i>=0;i--)\n        {\n    //traversing from back if someone has greater speed and ahead of lesser speed car it will always be ahead \n            while(!st.empty() && cars[st.top()][1]>= cars[i][1])\n                st.pop();\n            while(!st.empty()) // for lesser speed car ahead of greater spped car\n            {\n                double collision_time = (double)(cars[st.top()][0]-cars[i][0])/(cars[i][1]-cars[st.top()][1]);\n                if(collision_time <=res[st.top()] || res[st.top()] == -1)\n                {\n                    res[i] = collision_time;\n                    break;\n                }\n                st.pop();\n            }\n            \n            st.push(i);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Longest Turbulent Subarray",
        "algo_input": "Given an integer array arr, return the length of a maximum size turbulent subarray of arr.\n\nA subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.\n\nMore formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:\n\n\n\tFor i &lt;= k &lt; j:\n\n\t\n\t\tarr[k] &gt; arr[k + 1] when k is odd, and\n\t\tarr[k] &lt; arr[k + 1] when k is even.\n\t\n\t\n\tOr, for i &lt;= k &lt; j:\n\t\n\t\tarr[k] &gt; arr[k + 1] when k is even, and\n\t\tarr[k] &lt; arr[k + 1] when k is odd.\n\t\n\t\n\n\n&nbsp;\nExample 1:\n\nInput: arr = [9,4,2,10,7,8,8,1,9]\nOutput: 5\nExplanation: arr[1] &gt; arr[2] &lt; arr[3] &gt; arr[4] &lt; arr[5]\n\n\nExample 2:\n\nInput: arr = [4,8,12,16]\nOutput: 2\n\n\nExample 3:\n\nInput: arr = [100]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 4 * 104\n\t0 &lt;= arr[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maxTurbulenceSize(self, arr: List[int]) -> int:\n        def cmp(a,b):\n            if a == b: return 0\n            if a > b : return 1\n            return -1\n\n        n = len(arr)\n        ans = 1\n        prev = 0\n        for i in range(1,n):\n            c = cmp(arr[i-1],arr[i])\n            if c == 0:\n                # we shift prev to i\n                prev = i\n            elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1:\n                ans = ans if ans > i - prev + 1 else i - prev + 1\n                prev = i\n        return ans",
        "solution_js": "var maxTurbulenceSize = function(arr) {\n    const len = arr.length;\n    const dp = Array.from({ length: len + 1 }, () => {\n        return new Array(2).fill(0);\n    });\n    let ans = 0;\n    for(let i = 1; i < len; i++) {\n        if(arr[i-1] > arr[i]) {\n            dp[i][0] = dp[i-1][1] + 1;\n        } else if(arr[i-1] < arr[i]) {\n            dp[i][1] = dp[i-1][0] + 1;\n        }\n        ans = Math.max(ans, ...dp[i]);\n    }\n\n    // console.log(dp);\n    return ans + 1;\n};",
        "solution_java": "class Solution {\n    public int maxTurbulenceSize(int[] arr) {\n        if(arr.length == 1) {\n            return 1;\n        } \n        int l = 0, r = 1;\n        int diff = arr[l] - arr[r];\n        int max;\n        if(diff == 0) {\n            l = 1;\n            r = 1;\n            max = 1;\n        } else {\n            l = 0;\n            r = 1;\n            max = 2;\n        }\n        for(int i = 1; r < arr.length-1; i++) {\n            int nextdiff = arr[i] - arr[i+1];\n            if(diff < 0) {\n                if(nextdiff > 0) {\n                    r++;\n                } else if(nextdiff == 0) {\n                    l = i+1;\n                    r = i+1;\n                } else {\n                    l = i;\n                    r = i+1;\n                }\n            } else {\n                if(nextdiff < 0) {\n                    r++;\n                } else if(nextdiff == 0) {\n                    l = i+1;\n                    r = i+1;\n                } else {\n                    l = i;\n                    r = i+1;\n                }\n            }\n            diff = nextdiff;\n            max = Math.max(max, r-l+1);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxTurbulenceSize(vector<int>& arr) {\n        vector<int> table1(arr.size(), 0);\n        vector<int> table2(arr.size(), 0);\n        table1[0] = 1;\n        table2[0] = 1;\n        int max_len = 1;\n        for (int i=1; i<arr.size(); ++i) {\n            table1[i] = 1;\n            table2[i] = 1;\n            if (arr[i] < arr[i - 1] && (i & 1) == 0) {\n                table1[i] = table1[i - 1] + 1;\n            } else if (arr[i] > arr[i - 1] && (i & 1) == 1) {\n                table1[i] = table1[i - 1] + 1;\n            }\n            if (arr[i] > arr[i - 1] && (i & 1) == 0) {\n                table2[i] = table2[i - 1] + 1;\n            } else if (arr[i] < arr[i - 1] && (i & 1) == 1) {\n                table2[i] = table2[i - 1] + 1;\n            }\n            max_len = max(max_len, table1[i]);\n            max_len = max(max_len, table2[i]);\n        }\n        return max_len;\n    }\n};"
    },
    {
        "title": "Pascal's Triangle II",
        "algo_input": "Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n\n&nbsp;\nExample 1:\nInput: rowIndex = 3\nOutput: [1,3,3,1]\nExample 2:\nInput: rowIndex = 0\nOutput: [1]\nExample 3:\nInput: rowIndex = 1\nOutput: [1,1]\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= rowIndex &lt;= 33\n\n\n&nbsp;\nFollow up: Could you optimize your algorithm to use only O(rowIndex) extra space?\n",
        "solution_py": "class Solution:\n    def getRow(self, rowIndex: int) -> List[int]:\n        # base case\n        # we know that there exist two base case one which is for zero input\n        # One when we have to exit our recursive loop \n        if rowIndex == 0:\n            return [1]\n        if rowIndex == 1:\n            return [1,1]\n        #recurance relation or prev call\n        prev_prob = self.getRow(rowIndex-1)\n        # post processing on data \n        # if someone has given us prev_Row what operation we can perform to get current_Row\n        return [1]+[prev_prob[i]+prev_prob[i-1] for i in range(1,len(prev_prob))]+[1]",
        "solution_js": "var getRow = function(rowIndex) {\n    const triangle = [];\n\n    for (let i = 0; i <= rowIndex; i++) {\n        const rowValue = [];\n\n        for (let j = 0; j < i + 1; j++) {\n             if (j === 0 || j === i) {\n                 rowValue[j] = 1;\n             } else {\n                 rowValue[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];\n             }\n        }\n        triangle.push(rowValue)\n    }\n\n    return triangle[rowIndex];\n};",
        "solution_java": "class Solution {\n    public List<Integer> getRow(int rowIndex) {\n        List<List<Integer>> out = new ArrayList<>();\n        for(int i = 0; i<=rowIndex; i++){\n            List<Integer>in = new ArrayList<>(i+1);\n            for(int j = 0 ; j<= i; j++){\n                if(j == 0 || j == i){\n                    in.add(1);\n                }\n                else{\n                    in.add(out.get(i-1).get(j-1) + out.get(i-1).get(j));\n                }\n                \n            }\n            out.add(in);\n        }\n        return out.get(rowIndex);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> getRow(int rowIndex) {\n        vector<int> ans(rowIndex+1,0);\n        ans[0]=1;\n        for(int i=1;i<rowIndex+1;i++){\n            for(int j=i;j>=1;j--){\n                ans[j]=ans[j]+ans[j-1];\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Increasing Path in a Matrix",
        "algo_input": "Given an m x n integers matrix, return the length of the longest increasing path in matrix.\n\nFrom each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput: 4\nExplanation: The longest increasing path is [1, 2, 6, 9].\n\n\nExample 2:\n\nInput: matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput: 4\nExplanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.\n\n\nExample 3:\n\nInput: matrix = [[1]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 200\n\t0 &lt;= matrix[i][j] &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n        ROWS, COLS = len(matrix), len(matrix[0])\n        dp = {}\n        \n        def dfs(r, c, prevVal):\n            if (r < 0 or r == ROWS or\n                c < 0 or c == COLS or\n                matrix[r][c] <= prevVal):\n                return 0\n            if (r, c) in dp:\n                return dp[(r, c)]\n            res = 1\n            res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))\n            res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))\n            res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))\n            res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))\n            dp[(r, c)] = res\n            return res\n        for r in range(ROWS):\n            for c in range(COLS):\n                dfs(r, c, -1)\n        return max(dp.values())",
        "solution_js": "var longestIncreasingPath = function(matrix) {\n    const m = matrix.length, n = matrix[0].length;\n    const dp = new Array(m).fill(0).map(() => {\n        return new Array(n).fill(-1);\n    });\n\n    let ans = 0;\n    const dir = [0, -1, 0, 1, 0];\n\n    const dfs = (x, y) => {\n        if(dp[x][y] != -1) return dp[x][y];\n\n        for(let i = 1; i <= 4; i++) {\n            const [nx, ny] = [x + dir[i], y + dir[i - 1]];\n            if(\n                nx >= 0 && ny >= 0 &&\n                nx < m && ny < n &&\n                matrix[nx][ny] > matrix[x][y]\n            ) {\n                dp[x][y] = Math.max(dp[x][y], 1 + dfs(nx, ny));\n            }\n        }\n\n        if(dp[x][y] == -1) dp[x][y] = 1;\n        ans = Math.max(ans, dp[x][y]);\n        return dp[x][y];\n    }\n\n    for(let i = 0; i < m; i++) {\n        for(let j = 0; j < n; j++) {\n            if(dp[i][j] == -1) dfs(i, j);\n        }\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int longestIncreasingPath(int[][] matrix) {\n        int[][] memo = new int[matrix.length][matrix[0].length];\n        int longestPath = 0;\n        for (int i = 0; i < matrix.length; i++) {\n            for (int j = 0; j < matrix[0].length; j++) {\n                dfs(matrix, i, j, memo);\n                longestPath = Math.max(longestPath, memo[i][j]);\n            }\n        }\n        return longestPath;\n    }\n\n    private void dfs(int[][] matrix, int i, int j, int[][] memo) {\n        if (memo[i][j] != 0)\n            return;\n        int[][] dirs = {{-1,0}, {0,1}, {1,0}, {0,-1}};\n        int max = 0;\n        for (int k = 0; k < dirs.length; k++) {\n            int x = dirs[k][0] + i;\n            int y = dirs[k][1] + j;\n            if (isValid(matrix, x, y) && matrix[x][y] > matrix[i][j]) {\n                // Get/compute the largest path for that index\n                if (memo[x][y] == 0) { // If longest path doesn't exist for that path then compute it\n                    dfs(matrix, x, y, memo);\n                }\n                max = Math.max(max, memo[x][y]);\n            }\n        }\n        memo[i][j] = 1 + max;\n    }\n\n    private boolean isValid(int[][] matrix, int i, int j) {\n        if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)\n            return false;\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    // declare a dp\n    \n    int dp[205][205];\n    \n    // direction coordinates of left, right, up, down\n    \n    vector<int> dx = {-1, 0, 1, 0};\n    \n    vector<int> dy = {0, 1, 0, -1};\n    \n    // dfs function\n    \n    int dfs(vector<vector<int>>& matrix, int i, int j, int n, int m)\n    {\n        // if value is already calculated for (i, j)th cell\n        \n        if(dp[i][j] != -1)\n            return dp[i][j];\n        \n        // take the maximum of longest increasing path from all four directions\n        \n        int maxi = 0;\n        \n        for(int k = 0; k < 4; k++)\n        {\n            int new_i = i + dx[k];\n            \n            int new_j = j + dy[k];\n            \n            if(new_i >= 0 && new_i < n && new_j >= 0 && new_j < m && matrix[new_i][new_j] > matrix[i][j])\n            {\n                maxi = max(maxi, dfs(matrix, new_i, new_j, n, m));\n            }\n        }\n        \n        // store the res and return it\n        \n        return dp[i][j] = 1 + maxi;\n    }\n    \n    int longestIncreasingPath(vector<vector<int>>& matrix) {\n        \n        int n = matrix.size();\n        \n        int m = matrix[0].size();\n        \n        // initialize dp with -1\n        \n        memset(dp, -1, sizeof(dp));\n        \n        // find the longest increasing path for each cell and take maximum of it\n        \n        int maxi = INT_MIN;\n        \n        for(int i = 0; i < n; i++)\n        {\n            for(int j = 0; j < m; j++)\n            {\n                int ans = dfs(matrix, i, j, n, m);\n                \n                maxi = max(maxi, ans);\n            }\n        }\n        \n        return maxi;\n    }\n};"
    },
    {
        "title": "Jump Game VII",
        "algo_input": "You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:\n\n\n\ti + minJump &lt;= j &lt;= min(i + maxJump, s.length - 1), and\n\ts[j] == '0'.\n\n\nReturn true if you can reach index s.length - 1 in s, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: s = \"011010\", minJump = 2, maxJump = 3\nOutput: true\nExplanation:\nIn the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.\n\n\nExample 2:\n\nInput: s = \"01101110\", minJump = 2, maxJump = 3\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\ts[0] == '0'\n\t1 &lt;= minJump &lt;= maxJump &lt; s.length\n\n",
        "solution_py": "class Solution:\n    def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n\t\t# dp[i] represents whether i is reachable\n        dp = [False for _ in s]\n        dp[0] = True\n\n        for i in range(1, len(s)):\n            if s[i] == \"1\":\n                continue\n\n\t\t\t# iterate through the solutions in range [i - maxJump, i - minJump]\n\t\t\t# and if any previous spot in range is reachable, then i is also reachable\n            window_start = max(0, i - maxJump)\n            window_end = i - minJump\n            for j in range(window_start, window_end + 1):\n                if dp[j]:\n                    dp[i] = True\n                    break\n        \n        return dp[-1]       ",
        "solution_js": "var canReach = function(s, minJump, maxJump) {\n    const validIdxs = [0];\n    for (let i = 0; i < s.length; i++) {\n        // skip if character is a 1 or if all the \n        // valid indicies are too close\n        if (s[i] === '1' || i - validIdxs[0] < minJump) {\n            continue;\n        }\n        \n        // remove all the indexes that are too far\n        while (validIdxs.length && i - validIdxs[0] > maxJump) {\n            validIdxs.shift();\n        }\n        if (validIdxs.length === 0) {\n            return false;\n        }\n        \n        validIdxs.push(i);\n        \n        // if we are at the last index\n        // return if we have an index within range\n        if (i === s.length - 1) {\n            return i - validIdxs[0] >= minJump;\n        }\n    }\n    // if the last character is a 1 we must return False\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean canReach(String s, int minJump, int maxJump) {\n        if(s.charAt(s.length() - 1) != '0')\n            return false;\n        \n        Queue<Integer> queue = new LinkedList<>();\n        queue.add(0);\n        \n        // This variable tells us till which index we have processed\n        int maxReach = 0;\n        \n        while(!queue.isEmpty()){\n            int idx = queue.remove();\n            // If we reached the last index\n            if(idx == s.length() - 1)\n                return true;\n            \n            // start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)]\n            for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){\n                if(s.charAt(j) == '0')\n                    queue.add(j);\n            }\n            \n            // since we have processed till idx + maxJump so update maxReach to next index\n            maxReach = Math.min(idx + maxJump + 1, s.length() - 1);\n        }\n        \n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canReach(string s, int minJump, int maxJump) {\n        int n = s.length();\n        if(s[n-1]!='0')\n            return false;\n        \n        int i = 0;\n        queue<int> q;\n        q.push(0);\n        int curr_max = 0;\n        \n        while(!q.empty()){\n            i = q.front();\n            q.pop();\n            if(i == n-1)\n                return true;\n            \n            for(int j = max(i + minJump, curr_max); j <= min(i + maxJump, n - 1); j++){\n                if(s[j] == '0')   q.push(j);\n            }   \n            curr_max = min(i+maxJump+1, n);\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Online Election",
        "algo_input": "You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].\n\nFor each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.\n\nImplement the TopVotedCandidate class:\n\n\n\tTopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.\n\tint q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]\nOutput\n[null, 0, 1, 1, 0, 0, 1]\n\nExplanation\nTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= persons.length &lt;= 5000\n\ttimes.length == persons.length\n\t0 &lt;= persons[i] &lt; persons.length\n\t0 &lt;= times[i] &lt;= 109\n\ttimes is sorted in a strictly increasing order.\n\ttimes[0] &lt;= t &lt;= 109\n\tAt most 104 calls will be made to q.\n\n",
        "solution_py": "class TopVotedCandidate:\n\n    def __init__(self, persons: List[int], times: List[int]):\n        counter = defaultdict(int)\n\n        mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i]\n        largestVote = -1 # keep largest vote person index\n        for i in range(len(persons)):\n            counter[persons[i]] += 1\n            if largestVote == -1 or counter[persons[i]] >= counter[largestVote]:\n                largestVote = persons[i]\n            mostVotePersons[i] = largestVote\n        \n        self.times = times\n        self.mostVotePersons = mostVotePersons\n\n    def q(self, t: int) -> int:\n        idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t\n        return self.mostVotePersons[idx]",
        "solution_js": "var TopVotedCandidate = function(persons, times) {\n    this.times = times;\n    this.len = times.length;\n    this.votes = new Array(this.len).fill(0);\n    \n    let max = 0; // max votes received by any single candidate so far.\n    let leader = -1l;\n    \n    this.leaders = persons.map((person, i) => {\n        this.votes[person]++;\n        \n        if (this.votes[person] >= max) {\n            max = this.votes[person];\n            leader = person;\n        }\n        \n        return leader;\n    });\n    \n};\n\nTopVotedCandidate.prototype.q = function(t) {\n    let left = 0;\n    let right = this.len - 1;\n    \n    while (left <= right) {\n        const mid = left + Math.floor((right - left) / 2);\n        \n        if (this.times[mid] === t) return this.leaders[mid];\n        else if (this.times[mid] < t) left = mid + 1;\n        else right = mid - 1;\n    }\n\t\n    return this.leaders[right];\n};",
        "solution_java": "class TopVotedCandidate {\n    int[] persons;\n    int[] times;\n    int length;\n    Map<Integer, Integer> voteCount;\n    Map<Integer, Integer> voteLead;\n\n    public TopVotedCandidate(int[] persons, int[] times) {\n        this.persons = persons;\n        this.times = times;\n        length = times.length-1;\n        int leadCount = 0;\n        int leadPerson = -1;\n        voteCount = new HashMap<>();\n        voteLead = new HashMap<>();\n        for(int i=0; i<=length; i++){\n            int newCount = voteCount.getOrDefault(persons[i], 0) + 1;\n            voteCount.put(persons[i], newCount);\n            if(newCount >= leadCount){\n                leadCount = newCount;\n                leadPerson = persons[i];\n            }\n            voteLead.put(times[i], leadPerson);\n        }\n    }\n\n    public int q(int t) {\n        int leadPerson = -1;\n        if(voteLead.containsKey(t)) {\n            leadPerson = voteLead.get(t);\n        }\n        else if(t < times[0]){\n            leadPerson = voteLead.get(times[0]);\n        }\n        else if(t > times[length]){\n            leadPerson = voteLead.get(times[length]);\n        }\n        else {\n            int low = 0;\n            int high = length;\n            while(low <= high){\n                int mid = low + (high-low)/2;\n                if(times[mid] > t) high = mid - 1;\n                else low = mid + 1;\n            }\n            leadPerson = voteLead.get(times[high]);\n        }\n        return leadPerson;\n    }\n}",
        "solution_c": "class TopVotedCandidate {\npublic:\n    vector<int> pref;\n    vector<int> glob_times;\n    TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n        int n = times.size();\n        glob_times = times;\n        pref.resize(n);\n        vector<int> cnt;\n        int sz = persons.size();\n        cnt.resize(sz+1, 0);\n        cnt[persons[0]]++;\n        pref[0] = persons[0];\n        int maxi = 1;\n        int maxi_person = persons[0];\n        for(int i = 1; i < n; i++){            \n            cnt[persons[i]]++;\n            if(cnt[persons[i]] > maxi){\n                maxi = cnt[persons[i]];\n                maxi_person = persons[i];\n            }\n            else if(cnt[persons[i]] == maxi){\n                maxi_person = persons[i];\n            }\n            \n            pref[i] = maxi_person;\n        }\n    } \n    \n    int q(int t) {\n        \n        int it = upper_bound(glob_times.begin(), glob_times.end(), t) - glob_times.begin();\n        if(it == 0) it++;\n        return pref[it-1];\n    }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */"
    },
    {
        "title": "Four Divisors",
        "algo_input": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.\n\n&nbsp;\nExample 1:\n\nInput: nums = [21,4,7]\nOutput: 32\nExplanation: \n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\n\nExample 2:\n\nInput: nums = [21,21]\nOutput: 64\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "import math \nclass Solution:\n    def sumFourDivisors(self, nums: List[int]) -> int:\n        s=0\n        for i in nums:\n            r=i+1\n            c=2\n            for j in range(2, int(math.sqrt(i))+1):\n                if i%j==0:\n                    if (i / j == j) :\n                        c+=1\n                        r+=j\n                    else :\n                        c+=2\n                        r+=j+int(i/j)\n            print(c, r)\n            if c==4:\n                s+=r\n        return s",
        "solution_js": "var sumFourDivisors = function(nums) {\n    let check = (num) => {\n        let divs = [num]; // init the array with the number itself\n        let orig = num;\n        num = num >> 1; // divide in half to avoid checking too many numbers\n        while (num > 0) {\n            if (orig % num === 0) divs.push(num);\n            num--;\n            if (divs.length > 4) return 0;\n        }\n        if (divs.length === 4) {\n            return divs.reduce((a, b) => a + b, 0);\n        }\n        return 0;\n    }\n    \n    let total = 0;\n    \n    for (let num of nums) {\n        total += check(num);\n    }\n    \n    return total;\n};",
        "solution_java": "class Solution {\n    public int sumFourDivisors(int[] nums) {\n        int res = 0;\n        for(int val : nums){\n            int sum = 0;\n            int count = 0;\n            for(int i=1;i*i <= val;i++){\n                if(val % i == 0){\n                    sum += i;\n                    count++;\n                    if(i != val/i){\n                        sum += val/i;\n                        count++;\n                    }\n                }\n            }\n            if(count == 4){\n                res += sum;\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumFourDivisors(vector<int>& nums) {\n        int n = nums.size();\n        int sum = 0,cnt=0,temp=0;\n        for(int i=0;i<n;i++){\n            \n            int x = nums[i];\n            int sq = sqrt(x);\n            \n            for(int j=1;j<=sq;j++){\n                if(x%j==0){\n                    cnt+=2; temp += (j+x/j);\n                    \n                    if(j==x/j){\n                        cnt--; temp-=j;\n                    }\n                    \n                    if(cnt>4)\n                        break;\n                }\n            }\n            if(cnt==4){\n                sum += temp;\n            }\n            temp=0; cnt=0;\n        }\n        return sum;\n    }\n};"
    },
    {
        "title": "Smallest Value of the Rearranged Number",
        "algo_input": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.\n\nReturn the rearranged number with minimal value.\n\nNote that the sign of the number does not change after rearranging the digits.\n\n&nbsp;\nExample 1:\n\nInput: num = 310\nOutput: 103\nExplanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.\n\n\nExample 2:\n\nInput: num = -7605\nOutput: -7650\nExplanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.\n\n\n&nbsp;\nConstraints:\n\n\n\t-1015 &lt;= num &lt;= 1015\n\n",
        "solution_py": "class Solution:\n    def smallestNumber(self, num: int) -> int:\n        lst=[i for i in str(num)]\n        if num<0:\n            return ''.join(['-'] + sorted(lst[1:],reverse=True))\n        lst=sorted(lst)\n        if '0' in lst:\n            itr=0\n            while itr<len(lst) and lst[itr]=='0':\n                itr+=1\n            if itr==len(lst): #All zeroes\n                return ''.join(lst)\n            return ''.join([lst[itr]]+lst[:itr]+lst[itr+1:])\n        return ''.join(lst)",
        "solution_js": "var smallestNumber = function(num) {\n    let arr = Array.from(String(num));\n    if(num>0){\n    arr.sort((a,b)=>{\n         return a-b;\n    })\n    }\n    else{\n         arr.sort((a,b)=>{\n              return b-a;\n         })\n    }\n    for(let i=0;i<arr.length;i++){\n       if(arr[i]!=0){\n            [arr[0],arr[i]]=[arr[i],arr[0]];\n            break;\n       }\n  }\n    return arr.join(\"\");\n};",
        "solution_java": "class Solution {\n    public long smallestNumber(long num) {\n        if(num == 0){\n            return 0;\n        }\n        boolean isNegative = num < 0;\n        num  = num < 0 ? num * -1 : num;\n        \n        char[] c = String.valueOf(num).toCharArray();\n        Arrays.sort(c);\n        String str;\n        if(!isNegative){\n            int non = 0;\n\t\t\t//if not negative we need to find out the first non-leading zero then swap with first zero\n            for(; non < c.length; non++){\n                if(c[non] != '0'){\n                    break;\n                }\n            }\n            char temp = c[non];\n            c[non] = c[0];\n            c[0] = temp;\n            str = new String(c);\n        }else{\n            str = new String(c);\n            StringBuilder sb = new StringBuilder(str);\n            str = \"-\".concat(sb.reverse().toString());\n        }\n        return Long.valueOf(str);\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    long long smallestNumber(long long num)\n    {\n        if (num < 0)\n        {\n            string s = to_string(-num);\n            sort(s.rbegin(), s.rend());\n            return -stoll(s);\n        }\n        else if (num == 0)\n            return 0;\n        string s = to_string(num);\n        sort(s.begin(), s.end());\n        int i = 0;\n        while (s[i] == '0')\n            i++;\n        char c = s[i];\n        s.erase(s.begin() + i);\n        s = c + s;\n        return stoll(s);\n    }\n};"
    },
    {
        "title": "Sequential Digits",
        "algo_input": "An&nbsp;integer has sequential digits if and only if each digit in the number is one more than the previous digit.\n\nReturn a sorted list of all the integers&nbsp;in the range [low, high]&nbsp;inclusive that have sequential digits.\n\n&nbsp;\nExample 1:\nInput: low = 100, high = 300\nOutput: [123,234]\nExample 2:\nInput: low = 1000, high = 13000\nOutput: [1234,2345,3456,4567,5678,6789,12345]\n\n&nbsp;\nConstraints:\n\n\n\t10 &lt;= low &lt;= high &lt;= 10^9\n\n",
        "solution_py": "class Solution:\n    def sequentialDigits(self, low: int, high: int) -> List[int]:\n        l = len(str(low))\n        h = len(str(high))\n        ans = []\n        for i in range(l,h+1):\n            for j in range(1,11-i):\n                t = str(j)\n                for k in range(i-1):\n                    t+=str(int(t[-1])+1)\n                if int(t)<=high and int(t)>=low:\n                    ans.append(int(t))\n        ans.sort()\n        return ans",
        "solution_js": "var sequentialDigits = function(low, high) {\n    const digits = '123456789';\n    const ans = [];\n    \n    const minLen = low.toString().length;\n    const maxLen = high.toString().length;\n    \n    for (let windowSize = minLen; windowSize <= maxLen; ++windowSize) {\n        for (let i = 0; i + windowSize <= digits.length; ++i) {\n            const num = parseInt(digits.substring(i, i + windowSize));\n            \n            if (num >= low && num <= high) {\n                ans.push(num);\n            }\n        }\n    }\n    \n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public List<Integer> sequentialDigits(int low, int high) {\n        int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length();\n        List<Integer> output = new ArrayList<>();\n\n        for(int size=lowSize; size<=highSize; size++) {\n            int seedNumber = getSeedNumber(size);\n            int increment = getIncrement(size);\n            int limit = (int)Math.pow(10,size);\n            // System.out.println(seedNumber+\":\"+increment+\":\"+limit);\n            while(true){\n                if(seedNumber>=low && seedNumber<=high)\n                    output.add(seedNumber);\n                if(seedNumber%10==9 || seedNumber>high) break;\n                seedNumber+=increment;\n            }\n        }\n        return output;\n    }\n\n    private int getSeedNumber(int size) {\n        int seed = 1;\n        for(int i=2;i<=size;i++)\n            seed=10*seed + i;\n        return seed;\n    }\n\n    private int getIncrement(int size) {\n        int increment = 1;\n        for(int i=2;i<=size;i++)\n            increment=10*increment + 1;\n        return increment;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> sequentialDigits(int low, int high) {\n        string lf = to_string(low);\n        string rt = to_string(high);\n        \n        vector<int> ans;\n        for(int i = lf.size(); i <= rt.size(); i++){ // 字符串长度\n            for(int st = 1; st <= 9; st++){\n                string base(i, '0'); // \"000000\" i个0\n                for(int j = 0; j < i; j++){\n                    base[j] += st + j;\n                }\n                \n                if(base.back() <= '9'){\n                    int num = stoi(base);\n                     if(low <= num && num <= high){\n                         ans.push_back(num);\n                     }\n                }\n            }\n        }\n        \n        return ans;\n    }\n    \n};"
    },
    {
        "title": "Sender With Largest Word Count",
        "algo_input": "You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].\n\nA message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.\n\nReturn the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.\n\nNote:\n\n\n\tUppercase letters come before lowercase letters in lexicographical order.\n\t\"Alice\" and \"alice\" are distinct.\n\n\n&nbsp;\nExample 1:\n\nInput: messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]\nOutput: \"Alice\"\nExplanation: Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return \"Alice\".\n\n\nExample 2:\n\nInput: messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]\nOutput: \"Charlie\"\nExplanation: Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.\n\n&nbsp;\nConstraints:\n\n\n\tn == messages.length == senders.length\n\t1 &lt;= n &lt;= 104\n\t1 &lt;= messages[i].length &lt;= 100\n\t1 &lt;= senders[i].length &lt;= 10\n\tmessages[i] consists of uppercase and lowercase English letters and ' '.\n\tAll the words in messages[i] are separated by a single space.\n\tmessages[i] does not have leading or trailing spaces.\n\tsenders[i] consists of uppercase and lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n        d={}\n        l=[]\n        for i in range(len(messages)):\n            if senders[i] not in d:\n                d[senders[i]]=len(messages[i].split())\n            else:\n                d[senders[i]]+=len(messages[i].split())\n        x=max(d.values())\n        for k,v in d.items():\n            if v==x :\n                l.append(k)\n        if len(l)==1:\n            return l[0]\n        else:\n            l=sorted(l)[::-1]      #Lexigograhical sorting of list\n            return l[0]",
        "solution_js": "/**\n * @param {string[]} messages\n * @param {string[]} senders\n * @return {string}\n */\nvar largestWordCount = function(messages, senders) {\n    let wordCount = {}\n    let result = ''\n    let maxCount = -Infinity\n    for (let i = 0; i < messages.length;i++) {\n        let count=messages[i].split(' ').length\n        wordCount[senders[i]] = wordCount[senders[i]] == undefined ? count : wordCount[senders[i]] + count;\n        if (wordCount[senders[i]]  > maxCount || (wordCount[senders[i]]  == maxCount && senders[i] > result)) {\n            maxCount = wordCount[senders[i]];\n            result = senders[i];\n        }\n    }\n    return result;\n\n};",
        "solution_java": "class Solution {\n    public String largestWordCount(String[] messages, String[] senders) {\n        HashMap<String,Integer> hm=new HashMap<>();\n\t\t\n        int max=0;\n        String name=\"\";\n        for(int i=0;i<messages.length;i++){\n            String[] words=messages[i].split(\" \");\n            \n            int freq=hm.getOrDefault(senders[i],0)+words.length;\n            hm.put(senders[i],freq);\n            \n            if(hm.get(senders[i])>max){\n                max=hm.get(senders[i]);\n                name=senders[i];\n            }\n            else if(hm.get(senders[i])==max && name.compareTo(senders[i])<0){\n                name=senders[i];\n            } \n        }\n        \n        return name;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestWordCount(vector<string>& messages, vector<string>& senders) {\n\n        int n(size(messages));\n        map<string, int> m;\n        for (auto i=0; i<n; i++) {\n\n            stringstream ss(messages[i]);\n            string word;\n            int count(0);\n            while (ss >> word) count++;\n            m[senders[i]] += count;\n        }\n\n        int count(0);\n        string res;\n        for (auto& p : m) {\n            if (p.second >= count) {\n                count = p.second;\n                if (!res.empty() or res < p.first) res = p.first;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Arithmetic Slices II - Subsequence",
        "algo_input": "Given an integer array nums, return the number of all the arithmetic subsequences of nums.\n\nA sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n\n\n\tFor example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.\n\tFor example, [1, 1, 2, 5, 7] is not an arithmetic sequence.\n\n\nA subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n\n\n\tFor example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\n\n\nThe test cases are generated so that the answer fits in 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,4,6,8,10]\nOutput: 7\nExplanation: All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]\n\n\nExample 2:\n\nInput: nums = [7,7,7,7,7]\nOutput: 16\nExplanation: Any subsequence of this array is arithmetic.\n\n\n&nbsp;\nConstraints:\n\n\n\t1&nbsp; &lt;= nums.length &lt;= 1000\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n        sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0\n        for i in range(1, sz):\n            for j in range(i):\n                difference = nums[i] - nums[j]\n                dp[i][difference] += 1\n                if difference in dp[j]:\n                    dp[i][difference] += dp[j][difference]\n                    ans += dp[j][difference]\n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numberOfArithmeticSlices = function(nums) {\n  let dp = new Array(nums.length);\n  for(let i = 0; i < nums.length; i++) {\n    dp[i] = new Map();\n  }\n  let ans = 0;\n  for(let j = 1; j < nums.length; j++) {\n    for(let i = 0; i < j; i++) {\n      let commonDifference = nums[j] - nums[i];\n      if ((commonDifference > (Math.pow(2, 31) - 1)) || commonDifference < (-Math.pow(2, 31))) {\n        continue;\n      }\n      let apsEndingAtI = dp[i].get(commonDifference) || 0\n      let apsEndingAtJ = dp[j].get(commonDifference) || 0\n\n      dp[j].set(commonDifference, (apsEndingAtI + apsEndingAtJ + 1));\n      ans += apsEndingAtI;\n    }\n  }\n  return ans;\n};",
        "solution_java": "class Solution {\n    public int numberOfArithmeticSlices(int[] nums) {\n        int n=nums.length;\n        \n        HashMap<Integer,Integer> []dp=new HashMap[n];\n        \n        for(int i=0;i<n;i++){\n            dp[i]=new HashMap<Integer,Integer>();\n        }\n        \n        int ans=0;\n        \n        for(int i=1;i<n;i++){\n            for(int j=0;j<i;j++){\n                long cd=(long)nums[i]-(long)nums[j];\n                \n                if(cd<=Integer.MIN_VALUE || cd>=Integer.MAX_VALUE){\n                    continue;\n                }\n                \n                int endingAtj=dp[j].getOrDefault((int)cd,0);\n                int endingAti=dp[i].getOrDefault((int)cd,0);\n                \n                ans+=endingAtj;\n                \n                dp[i].put((int)cd,endingAtj+endingAti+1);\n            }\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfArithmeticSlices(vector<int>& nums) {\n        int n=nums.size(),ans=0;\n        unordered_map<long long, unordered_map<int,int>> ma;   // [diff, [index, count]]\n        unordered_map<int,int> k;\n        for(int i=1;i<n;i++)\n        {\n            for(int j=0;j<i;j++)\n            {\n                long long diff= (long long)nums[i]-(long long)nums[j];\n                if(ma.find(diff)==ma.end())\n                    ma[diff]= k;\n                if(ma[diff].find(j)==ma[diff].end())\n                    ma[diff][j]=0;\n                ma[diff][i] += ma[diff][j] + 1;\n                ans += ma[diff][j];\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Partition List",
        "algo_input": "Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.\n\nYou should preserve the original relative order of the nodes in each of the two partitions.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,4,3,2,5,2], x = 3\nOutput: [1,2,2,4,3,5]\n\n\nExample 2:\n\nInput: head = [2,1], x = 2\nOutput: [1,2]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 200].\n\t-100 &lt;= Node.val &lt;= 100\n\t-200 &lt;= x &lt;= 200\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n    def partition(self, head, x):\n        \"\"\"\n        :type head: ListNode\n        :type x: int\n        :rtype: ListNode\n        \"\"\"\n        lessthan = []\n        greateql = []\n\n        while head:\n            if head.val < x:\n                lessthan.append(head.val)\n            else:\n                greateql.append(head.val)\n            head = head.next\n\n        h = res = ListNode()\n\n        for i in range(len(lessthan)):\n            res.next = ListNode(lessthan[i])\n            res = res.next\n        for i in range(len(greateql)):\n            res.next = ListNode(greateql[i])\n            res = res.next\n\n        return h.next",
        "solution_js": "var partition = function(head, x) {\n    if (!head) {\n        return head;\n    }\n    const less = [];\n    const greater = [];\n    let concat;\n    rec(head);\n    return head;\n    \n    \n    function rec(currentNode) {\n        if (currentNode.val < x) {\n            less.push(currentNode.val);\n        } else {\n            greater.push(currentNode.val);\n        }\n        if (!currentNode.next) {\n            concat = [...less, ...greater];\n            currentNode.val = concat.pop();       \n            return;\n        }\n        rec(currentNode.next);\n        currentNode.val = concat.pop();\n    }\n    \n};",
        "solution_java": "class Solution {\n    public ListNode partition(ListNode head, int x) {\n        ListNode left = new ListNode(0);\n        ListNode right = new ListNode(0);\n        \n        ListNode leftTail = left;\n        ListNode rightTail = right;\n        \n        while(head != null){\n            if(head.val < x){\n                leftTail.next = head;\n                leftTail = leftTail.next;\n            }\n            else{\n                rightTail.next = head;\n                rightTail = rightTail.next;\n            }\n            head = head.next;\n        }\n        \n        leftTail.next = right.next;\n        rightTail.next = null;\n        \n        return left.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* partition(ListNode* head, int x) {\n        ListNode *left = new ListNode(0);\n        ListNode *right = new ListNode(0);\n        \n        ListNode *leftTail = left;\n        ListNode *rightTail = right;\n        \n        while(head != NULL){\n            if(head->val < x){\n                leftTail->next = head;\n                leftTail = leftTail->next;\n            }\n            else{\n                rightTail->next = head;\n                rightTail = rightTail->next;\n            }\n            head = head->next;\n        }\n        \n        leftTail->next = right->next;\n        rightTail->next = NULL;\n        \n        return left->next;\n    }\n};"
    },
    {
        "title": "Toeplitz Matrix",
        "algo_input": "Given an m x n matrix, return&nbsp;true&nbsp;if the matrix is Toeplitz. Otherwise, return false.\n\nA matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: true\nExplanation:\nIn the above grid, the&nbsp;diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.\n\n\nExample 2:\n\nInput: matrix = [[1,2],[2,2]]\nOutput: false\nExplanation:\nThe diagonal \"[1, 2]\" has different elements.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 20\n\t0 &lt;= matrix[i][j] &lt;= 99\n\n\n&nbsp;\nFollow up:\n\n\n\tWhat if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?\n\tWhat if the matrix is so large that you can only load up a partial row into the memory at once?\n\n",
        "solution_py": "###########################################################################################\n#       Number of rows(M) x expected numbers(N)\n#   Space: O(N)\n#       We need to store the expected numbers in list\n############################################################################################\nclass Solution:\n    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n        # Validate Input\n        if not matrix or not matrix[0]:\n            return False                \n        \n        # Create a deque tracking the expected values for the next row\n        expected = matrix[0]\n        # We only care about the elements before last element\n        expected.pop()\n        \n        # From the second row, pop out the last element of the expected numbers and compare it with the target row[1:]\n        for row in matrix[1:]:\n            # Compare row with expected numbers, invalidate it as soon as we find the numbers are not the same (O(N))\n            if row[1:] != expected:\n                return False\n            else:\n                # Pop the last element from row, use it as the expected numbers for the next iteration\n                row.pop()\n                expected = row\n        # If we've reached here, all diagonals aligned\n        return True",
        "solution_js": "var isToeplitzMatrix = function(matrix) {\n    for (let i=0; i < matrix.length-1; i++) {\n        for (let j=0; j < matrix[i].length-1; j++) {\n            if (matrix[i][j] !== matrix[i+1][j+1]) {\n                return false\n            }\n        }\n    }\n\n    return true\n};",
        "solution_java": "class Solution {\n    public boolean isToeplitzMatrix(int[][] matrix) {\n          \n        \n        int n = matrix.length;\n        int m = matrix[0].length;\n        \n        for(int i = 0; i < m; i++){\n            int row = 0;\n            int col = i;\n            int e = matrix[row++][col++];\n           while(row < n && col< m){\n               if(e == matrix[row][col]){\n                   row++;\n                   col++;\n               }else{\n                   return false;\n               }\n           }  \n        }\n        \n        for(int r = 1; r < n; r++){\n            int row = r;\n            int col = 0;\n            int e =matrix[row++][col++];\n            while(row < n && col < m){\n                if(e == matrix[row][col]){\n                    row++;\n                    col++;\n                }else{\n                    return false;\n                }\n            }\n        }\n        \n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isToeplitzMatrix(vector<vector<int>>& matrix) {\n        int m = matrix.size(), n = matrix[0].size();\n        for (int i = 1; i < m; i++)\n            for (int j = 1; j < n; j++)\n                if (matrix[i][j] != matrix[i - 1][j - 1])\n                    return false;\n        return true;\n    }\n};"
    },
    {
        "title": "Number of Burgers with No Waste of Ingredients",
        "algo_input": "Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:\n\n\n\tJumbo Burger: 4 tomato slices and 1 cheese slice.\n\tSmall Burger: 2 Tomato slices and 1 cheese slice.\n\n\nReturn [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].\n\n&nbsp;\nExample 1:\n\nInput: tomatoSlices = 16, cheeseSlices = 7\nOutput: [1,6]\nExplantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.\n\n\nExample 2:\n\nInput: tomatoSlices = 17, cheeseSlices = 4\nOutput: []\nExplantion: There will be no way to use all ingredients to make small and jumbo burgers.\n\n\nExample 3:\n\nInput: tomatoSlices = 4, cheeseSlices = 17\nOutput: []\nExplantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= tomatoSlices, cheeseSlices &lt;= 107\n\n",
        "solution_py": "class Solution(object):\n    def numOfBurgers(self, t, c):\n        \n        if t==c==0:\n            return [0,0]\n        four=(t-2*c)//2  # no of jumbo burgers by solving 4x+2y=t and x+y=c\n        two=c-four #number of small burgers\n        if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list\n            return []\n        \n        return [four,two]\n        ",
        "solution_js": "/**\n * @param {number} tomatoSlices\n * @param {number} cheeseSlices\n * @return {number[]}\n */\nvar numOfBurgers = function(tomatoSlices, cheeseSlices) {\n    if (tomatoSlices & 1) return []; // return [] if tomatoSlices is odd\n    const j = (tomatoSlices >> 1) - cheeseSlices; // jumbo = (tomatoSlices / 2) - cheeseSlices\n    return j < 0 || j > cheeseSlices ? [] : [j, cheeseSlices - j]; // small = cheeseSlices - jumbo, if any of jmbo and small < 0 return [] otherwise return [jumbo, small]\n};",
        "solution_java": "class Solution {\n    public List<Integer> numOfBurgers(int tomatoSlices, int cheeseSlices) {\n        List<Integer>list=new ArrayList<>();\n        int ts=tomatoSlices;\n        int cs=cheeseSlices;\n        if (ts<cs*2 || ts>cs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0))\n        {\n            return list;\n        }\n        int cnt=0;\n        while(ts>0 && cs>0 && ts!=cs*2)\n        {\n            ts-=4;\n            cnt++;\n            cs--;\n        }\n        list.add(cnt);\n        list.add(cs);\n        return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {\n        // Observation\n        // Total Number of Burgers is Equal to Number of cheeseSlices\n        // Try to make 1 --> cheeseSlices Amount of Jumbo Burgers and\n        // remaining will be Small Burger\n        vector <int> ans;\n        if(tomatoSlices == 0 and cheeseSlices == 0) {\n            ans.push_back(0), ans.push_back(0);\n            return ans;\n        }\n        // Do Binary Search to Get Ideal Division.\n        int low = 0, high = cheeseSlices;\n        while(low < high) {\n            int mid = (low + high) / 2;\n            int jumbo = mid, small = cheeseSlices - mid;\n            // Jumbo needs 4 tomatoes per burger\n            // Small needs 2 tomatoes per burger\n            int needJumboTom = jumbo * 4;\n            int needSmallTom = small * 2;\n            // Should Add Upto tomatoSlices\n            if(needJumboTom + needSmallTom == tomatoSlices) {\n                ans.push_back(jumbo), ans.push_back(small);\n                break;\n            } else if(needJumboTom + needSmallTom < tomatoSlices) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "N-ary Tree Level Order Traversal",
        "algo_input": "Given an n-ary tree, return the level order traversal of its nodes' values.\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [[1],[3,2,4],[5,6]]\n\n\nExample 2:\n\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe height of the n-ary tree is less than or equal to 1000\n\tThe total number of nodes is between [0, 104]\n\n",
        "solution_py": "class Solution:\n    def levelOrder(self, root: 'Node') -> List[List[int]]:\n        if not root:\n            return []\n        \n        result = []\n        level = [root]\n        \n        while level:\n            current_level = []\n            next_level = []\n            \n            for node in level:\n                current_level.append(node.val)\n                next_level += node.children\n                \n            result.append(current_level)\n            level = next_level\n        \n        return result",
        "solution_js": "var levelOrder = function(root) {\n    if(!root) return [];\n    \n    const Q  = [[root, 0]];\n    const op = [];\n    \n    while(Q.length) {\n        const [node, level] = Q.shift();\n        \n        if(op.length <= level) {\n            op[level] = [];\n        }\n        op[level].push(node.val);\n        \n        for(const child of node.children) {\n            Q.push([child, level + 1]);\n        }\n    }\n    return op;\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> result= new ArrayList();\n    public List<List<Integer>> levelOrder(Node root) {\n       if(root==null) return result;\n        helper(root,0);\n        return result;\n    }\n    \n    private void helper(Node node,int level){\n       if(result.size()<=level){\n           result.add(new ArrayList());\n       }\n        result.get(level).add(node.val);\n        for(Node child:node.children){\n            helper(child,level+1);\n        }\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    vector<vector<int>> ans;\n    \n    vector<vector<int>> levelOrder(Node* root) {\n        \n        dfs(root, 0);\n        return ans;\n    }\n    \n    void dfs(Node* root, int level) {\n        \n        if(!root) {\n            return;\n        }\n        if(level == ans.size()) {\n            ans.push_back({});\n        }\n        ans[level].push_back(root->val);\n        for(auto i : root->children) {\n            dfs(i, level+1);\n        }\n        \n    }\n    \n};"
    },
    {
        "title": "Exam Room",
        "algo_input": "There is an exam room with n seats in a single row labeled from 0 to n - 1.\n\nWhen a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.\n\nDesign a class that simulates the mentioned exam room.\n\nImplement the ExamRoom class:\n\n\n\tExamRoom(int n) Initializes the object of the exam room with the number of the seats n.\n\tint seat() Returns the label of the seat at which the next student will set.\n\tvoid leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]\nOutput\n[null, 0, 9, 4, 2, null, 5]\n\nExplanation\nExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.\n\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\tIt is guaranteed that there is a student sitting at seat p.\n\tAt most 104 calls will be made to seat and leave.\n\n",
        "solution_py": "class ExamRoom:\n\n    def __init__(self, n: int):\n        self.N = n\n        self.pq = []\n        self.dict = {}\n        self.addSegment(0, self.N - 1)\n\n    def seat(self) -> int:\n        start, end, distance = heapq.heappop(self.pq)\n        self.dict.pop(start, None) #Remove old segment from dictionary\n        self.dict.pop(end, None)\n\n        if start == end:\n            position = start\n\n        elif start == 0:\n            position = start\n            right = self.addSegment(start + 1, end)\n\n        elif end == self.N - 1:\n            position = end\n            left = self.addSegment(start, end - 1)\n\n        elif end - start == 1: #ONLY ONE PLACE TO PUT\n            position = start\n            left = self.addSegment(start + 1, end)\n\n        else:\n            position = start + (end - start) // 2\n            right = self.addSegment(start, position - 1)\n            left = self.addSegment(position + 1, end)\n\n        return position\n\n    def leave(self, p: int) -> None:\n        left = self.dict.get(p - 1, None)\n        right = self.dict.get(p + 1, None)\n\n        new_start = new_end = p\n\n        if left:\n            self.removeSegment(left)\n            new_start = left.start\n\n        if right:\n            self.removeSegment(right)\n            new_end = right.end\n\n        self.addSegment(new_start, new_end)\n\n    def addSegment(self, start, end):\n            segment = Segment(start, end, self.N)\n            self.dict[segment.start] = segment\n            self.dict[segment.end] = segment\n            heapq.heappush(self.pq, segment)\n\n    def removeSegment(self, segment):\n            self.dict.pop(segment.start, None)\n            self.dict.pop(segment.end, None)\n            self.pq.remove(segment)\n\nclass Segment():\n    def __init__(self, start, end, N):\n        self.start = start\n        self.end = end\n        self.distance = self.calculateDistance(start, end, N)\n\n    def __lt__(self, other_segment):\n        return self.distance > other_segment.distance if self.distance != other_segment.distance else self.start < other_segment.start\n\n    def calculateDistance(self, start, end, N):\n        if start == 0:\n            return end\n\n        if end == N - 1:\n            return end - start\n\n        else:\n            return (end - start) // 2\n\n    def __iter__(self):\n        return iter((self.start, self.end, self.distance))",
        "solution_js": "/**\n * @param {number} n\n */\nvar ExamRoom = function(n) {\n    this.n = n\n    this.list = []\n};\n\n/**\n * @return {number}\n */\nExamRoom.prototype.seat = function() {\n    // if nothing in the list, seat the first student at index 0.\n    if(this.list.length === 0){\n        this.list.push(0)\n        return 0\n    }\n\n    // find the largest distance between left wall and first student, and right wall and last student\n    let distance = Math.max(this.list[0], this.n - 1 - this.list[this.list.length-1])\n    // update the largest distance by considering the distance between students\n    for(let i=0; i<this.list.length-1; i++){\n        distance = Math.max(distance, Math.floor((this.list[i+1] - this.list[i]) / 2))\n    }\n\n    // in case the largest distance is between left wall and first student, we seat next student at the left wall\n    if(distance === this.list[0]){\n        this.list.unshift(0)\n        return 0\n    }\n\n    // in case the largest distance is between two student, we seat the next student in between these two students\n    for(let i=0; i<this.list.length-1; i++){\n        if(distance === Math.floor( (this.list[i+1]-this.list[i])/2 )){\n            let insertIndex = Math.floor( (this.list[i+1]+this.list[i]) / 2 )\n            this.list.splice(i+1,0, insertIndex)\n            return insertIndex\n        }\n    }\n\n    // in case the largest distance is between the last student and the right wall, we seat the next student at the right wall\n    this.list.push(this.n-1)\n    return this.n - 1\n};\n\n/**\n * @param {number} p\n * @return {void}\n */\nExamRoom.prototype.leave = function(p) {\n    // We iterate through the list and find the index where the student p sit at, then remove that index.\n    for(let i=0; i<this.list.length; i++){\n        if(this.list[i] === p) {\n            this.list.splice(i, 1)\n            break\n        }\n    }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * var obj = new ExamRoom(n)\n * var param_1 = obj.seat()\n * obj.leave(p)\n */",
        "solution_java": "class ExamRoom {\n\n    private final int max;\n    private final TreeSet<Interval> available;\n    private final TreeSet<Integer> taken;\n\n    public ExamRoom(int n) {\n        this.max = n - 1;\n        this.available = new TreeSet<>((a, b) -> {\n            var distA = getMinDistance(a);\n            var distB = getMinDistance(b);\n            return distA == distB ? a.s - b.s : distB - distA;\n        });\n        this.available.add(new Interval(0, max));\n        this.taken = new TreeSet<>();\n    }\n\n    public int seat() {\n        var inter = available.pollFirst();\n        var idx = getInsertPosition(inter);\n        taken.add(idx);\n        if ((idx - 1) - inter.s >= 0)\n            available.add(new Interval(inter.s, idx - 1));\n        if (inter.e - (idx + 1) >= 0)\n            available.add(new Interval(idx + 1, inter.e));\n        return idx;\n    }\n\n    public void leave(int p) {\n        taken.remove(p);\n        var lo = taken.lower(p);\n        if (lo == null)\n            lo = -1;\n        var hi = taken.higher(p);\n        if (hi == null)\n            hi = max + 1;\n        available.remove(new Interval(lo + 1, p - 1));\n        available.remove(new Interval(p + 1, hi - 1));\n        available.add(new Interval(lo + 1, hi - 1));\n    }\n\n    private int getInsertPosition(Interval inter) {\n        if (inter.s == 0)\n            return 0;\n        else if (inter.e == max)\n            return max;\n        else\n            return inter.s + (inter.e - inter.s) / 2;\n    }\n\n    private int getMinDistance(Interval in) {\n        return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2;\n    }\n\n    private final class Interval {\n        private final int s;\n        private final int e;\n\n        Interval(int s, int e) {\n            this.s = s;\n            this.e = e;\n        }\n\n        @Override\n        public String toString() {\n            return \"[\" + s + \",\" + e + \"]\";\n        }\n    }\n}",
        "solution_c": "class ExamRoom {\npublic:\n    set<int> s;  // ordered set\n    int num;\n    ExamRoom(int n) {\n        num=n;    // total seats\n    }\n    \n    int seat() {\n        if(s.size()==0) { s.insert(0); return 0;}     // if size is zero place at seat 0\n        auto itr = s.begin();\n        if(s.size()==1) {                                      // if size==1 -> check if its closer to 0 or last seat (num-1) \n            if(*itr > num-1-(*itr)){ s.insert(0); return 0; }\n              else{  s.insert(num-1); return num-1;}\n        }\n        int mx=-1;     // for max gap\n        int l=0;          // for left index of the student to max gap.\n        \n        if(s.find(0)==s.end()){mx = (*itr); l=-mx;}    // if 0 is not seated -> check gap with 0 and starting seat.\n\t\t\n\t\t// Iterate the set to calculate gaps \n        for(int i=0;i<s.size()-1;i++)\n        {\n           int a=*itr;    // seat number  for 1st element \n           itr++;\n           int b = *itr;   // seat number of next element in the set\n\t\t   \n\t\t   // check the gap and update\n           if(mx<(b-a)/2){\n               mx=(b-a)/2;\n               l=a;\n           }\n        }\n        if(s.find(num-1)==s.end()) {   // if last seat is vacant -> check gap with last filled seat and (num-1)\n           if(mx< num-1-(*itr)) {\n               mx = (num-1-(*itr));\n               l=*itr;\n           }\n        }\n        s.insert(l+mx);   // place the student at l+mx\n        return l+mx;\n        \n        \n    }\n    \n    void leave(int p) {\n\t// remove student from set\n        s.erase(p);\n    }\n};"
    },
    {
        "title": "Largest Substring Between Two Equal Characters",
        "algo_input": "Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aa\"\nOutput: 0\nExplanation: The optimal substring here is an empty substring between the two 'a's.\n\nExample 2:\n\nInput: s = \"abca\"\nOutput: 2\nExplanation: The optimal substring here is \"bc\".\n\n\nExample 3:\n\nInput: s = \"cbzxy\"\nOutput: -1\nExplanation: There are no characters that appear twice in s.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 300\n\ts contains only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n        last, ans = {}, -1 \n        for i, c in enumerate(s):\n            if c not in last:\n                last[c] = i\n            else:\n                ans = max(ans, i - last[c] - 1)\n        return ans ",
        "solution_js": "var maxLengthBetweenEqualCharacters = function(s) {\n    \n    const map = new Map();\n    let max=-1;\n    for(let i=0;i<s.length;i++){\n\n        if(map.has(s[i])){\n            max=Math.max(max,i-(map.get(s[i])+1))\n        }else{\n            map.set(s[i],i)    \n        }\n        \n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maxLengthBetweenEqualCharacters(String s) {\n        int ans = -1;\n        Map<Character, Integer> map = new HashMap<>();\n        for (int i = 0; i < s.length(); i++) {\n            char ch  = s.charAt(i);\n            if (map.containsKey(ch)) {\n                ans = Math.max(ans, i - 1 - map.get(ch));\n            }\n            else {\n                map.put(ch, i);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxLengthBetweenEqualCharacters(string s) {\n        vector<int> v(26, -1);\n        int maxi = -1;\n        \n        for (int i = 0; i < s.size(); i++) {\n            if (v[s[i] - 'a'] == -1) v[s[i] - 'a'] = i;\n            else maxi = max(maxi, abs(v[s[i] - 'a'] - i) - 1);      \n        }\n        \n        return maxi;\n    }\n};"
    },
    {
        "title": "Reachable Nodes With Restrictions",
        "algo_input": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n\nYou are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.\n\nReturn the maximum number of nodes you can reach from node 0 without visiting a restricted node.\n\nNote that node 0 will not be a restricted node.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput: 4\nExplanation: The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\nExample 2:\n\nInput: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput: 3\nExplanation: The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 105\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tedges represents a valid tree.\n\t1 &lt;= restricted.length &lt; n\n\t1 &lt;= restricted[i] &lt; n\n\tAll the values of restricted are unique.\n\n",
        "solution_py": "class Solution:\n    def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n        # ignore restricted node\n        # bfs from 0\n        \n        # O(E), EDITED: the time complexity here is wrong, plz see my comment\n        adj_dict = collections.defaultdict(list)\n        for u, v in edges:\n            if u in restricted or v in restricted:  # EDITED: not O(1)\n                continue\n            adj_dict[u].append(v)\n            adj_dict[v].append(u)\n        \n        # O(V + E)\n        queue = collections.deque([0])\n        visited = {0}\n        while queue:\n            cur = queue.popleft()\n            for neighbor in adj_dict[cur]:\n                if neighbor in visited:\n                    continue\n                visited.add(neighbor)\n                queue.append(neighbor)\n\n        return len(visited)",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} restricted\n * @return {number}\n */\nvar reachableNodes = function(n, edges, restricted) {\n    const adj = {};\n    \n    for (const [u, v] of edges) {\n        if (adj[u]) {\n            adj[u].add(v);\n        } else {\n            adj[u] = new Set().add(v);\n        }\n        if (adj[v]) {\n            adj[v].add(u);\n        } else {\n            adj[v] = new Set().add(u);\n        }\n    }\n    \n    const restrictedSet = new Set(restricted);\n    const visited = new Set();\n    \n    let ans = 0;\n    \n    function dfs(node) {\n        if (restrictedSet.has(node) || visited.has(node)) {\n            return;\n        }\n        \n        ans++;\n        visited.add(node);\n        \n        for (const adjNode of adj[node]) {\n            dfs(adjNode);\n        }\n    }\n    \n    dfs(0);\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    int count=0;\n    ArrayList<ArrayList<Integer>> adj=new ArrayList<>();\n    public int reachableNodes(int n, int[][] edges, int[] restricted) {\n        boolean[] vis=new boolean[n];\n        for(int i:restricted){\n            vis[i]=true;\n        }\n        for(int i=0;i<n;i++){\n            adj.add(new ArrayList<>());\n        }\n        for(int[] ii:edges){\n            adj.get(ii[0]).add(ii[1]);\n            adj.get(ii[1]).add(ii[0]);\n        }\n        dfs(0,vis);\n        return count;\n    }\n    private void dfs(int node,boolean[] vis){\n        vis[node]=true;\n        count++;\n        for(int it:adj.get(node)){\n            if(vis[it]==false){\n                dfs(it,vis);\n            }\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int count=1;  // node 0 is already reached as it is starting point\n    vector<vector<int>> graph;\n    unordered_set<int> res;  // to store restricted numbers for fast fetch\n    vector<bool> vis;  // visited array for DFS\n    \n    void dfs(int i){\n        for(int y: graph[i]){\n            if(!vis[y] && res.count(y)==0){\n                vis[y]= true;\n                dfs(y);\n                count++;\n            }\n        }\n    }\n    \n    int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) {\n        for(int x:restricted) res.insert(x);\n        \n        // creating graph\n        graph.resize(n);\n        vis.resize(n);\n        for(auto &x:edges){\n            graph[x[0]].push_back(x[1]);\n            graph[x[1]].push_back(x[0]);\n        }\n        \n        // mark 0 as visited coz it is starting point and is already reached \n        vis[0]= true;\n        dfs(0);\n        \n        return count;\n    }\n};"
    },
    {
        "title": "Find Minimum in Rotated Sorted Array",
        "algo_input": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:\n\n\n\t[4,5,6,7,0,1,2] if it was rotated 4 times.\n\t[0,1,2,4,5,6,7] if it was rotated 7 times.\n\n\nNotice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n\nGiven the sorted rotated array nums of unique elements, return the minimum element of this array.\n\nYou must write an algorithm that runs in&nbsp;O(log n) time.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,4,5,1,2]\nOutput: 1\nExplanation: The original array was [1,2,3,4,5] rotated 3 times.\n\n\nExample 2:\n\nInput: nums = [4,5,6,7,0,1,2]\nOutput: 0\nExplanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\n\n\nExample 3:\n\nInput: nums = [11,13,15,17]\nOutput: 11\nExplanation: The original array was [11,13,15,17] and it was rotated 4 times. \n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 5000\n\t-5000 &lt;= nums[i] &lt;= 5000\n\tAll the integers of nums are unique.\n\tnums is sorted and rotated between 1 and n times.\n\n",
        "solution_py": "class Solution:\n    def findMin(self, nums: List[int]) -> int:\n        if len(nums) == 1 or nums[0] < nums[-1]:\n            return nums[0]\n        \n        l, r = 0, len(nums) - 1\n        \n        while l <= r:\n            mid = l + (r - l) // 2\n            \n            if mid > 0 and nums[mid - 1] > nums[mid]:\n                return nums[mid]\n            \n\t\t\t# We compare the middle number and the right index number\n\t\t\t# but why we cannot compare it with the left index number?\n            if nums[mid] > nums[r]:\n                l = mid + 1\n            else:\n                r = mid - 1",
        "solution_js": "var findMin = function(nums) {\n    let min = Math.min(...nums)\n    return min;\n};",
        "solution_java": "class Solution {\n    public int findMin(int[] nums)\n    {\n        int min=nums[0];\n\n        for(int i=0;i<nums.length;i++)\n        {\n            if(min>nums[i])\n            {\n                min=nums[i];\n            }\n        }\n        return min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findMin(vector<int>& nums) {\n        int result = -1;\n        int first = nums[0];\n\n        // check the array for rotated point when it is obtained break the loop and assign result as rotation point\n        for(int i = 1; i<nums.size();i++){\n            if(nums[i-1]>nums[i]){\n                result = nums[i];\n                break;\n            }\n        }\n        // if the array is not sorted return first element\n        if(result == -1) {\n            return first;\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Reverse Bits",
        "algo_input": "Reverse bits of a given 32 bits unsigned integer.\n\nNote:\n\n\n\tNote that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\n\tIn Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.\n\n\n&nbsp;\nExample 1:\n\nInput: n = 00000010100101000001111010011100\nOutput:    964176192 (00111001011110000010100101000000)\nExplanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.\n\n\nExample 2:\n\nInput: n = 11111111111111111111111111111101\nOutput:   3221225471 (10111111111111111111111111111111)\nExplanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe input must be a binary string of length 32\n\n\n&nbsp;\nFollow up: If this function is called many times, how would you optimize it?\n",
        "solution_py": "class Solution:\n# @param n, an integer\n# @return an integer\ndef reverseBits(self, n):\n    res=0\n    for i in range(32):\n        bit=(n>>i)&1\n        res=res|bit<<(31-i)\n    return res",
        "solution_js": "/**\n * @param {number} n - a positive integer\n * @return {number} - a positive integer\n */\n\n// remember the binary must always be of length 32 ;);\nvar reverseBits = function(n) {\n    const reversedBin = n.toString(2).split('').reverse().join('');\n    const result =  reversedBin.padEnd(32,'0'); \n    return parseInt(result, 2);\n};",
        "solution_java": "public class Solution {\n    // you need treat n as an unsigned value\n    public int reverseBits(int n) {\n        int mask = 0;\n        int smask = 0;\n        int j = 0;\n        int rev = 0;\n        \n        // basically we are checking that the number is set bit or not \n        // if the number is set bit then we are appending that to our main answer i.e, rev\n        for(int i=31 ; i>=0 ; i--){\n            mask = 1<<i;\n            if((mask&n)!=0){\n                smask = 1<<j;\n                rev = rev|smask;\n            }\n            j++;\n        }\n        \n        // Time Complexity : O(32 for int)\n        // Space Complexity : O(1)\n        return rev;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    uint32_t reverseBits(uint32_t n) {\n        int ans =0;\n        int i =1;\n        int bit =0;\n        while(i<32){\n            bit = n&1;\n            ans = ans|bit;\n            n = n>>1;\n            ans = ans<<1;\n            i++;\n        }\n        if (i ==32){\n            bit = n&1;\n            ans = ans|bit;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Cat and Mouse",
        "algo_input": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\n\nThe graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.\n\nThe mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.\n\nDuring each player's turn, they must travel along one&nbsp;edge of the graph that meets where they are.&nbsp; For example, if the Mouse is at node 1, it must travel to any node in graph[1].\n\nAdditionally, it is not allowed for the Cat to travel to the Hole (node 0.)\n\nThen, the game can end in three&nbsp;ways:\n\n\n\tIf ever the Cat occupies the same node as the Mouse, the Cat wins.\n\tIf ever the Mouse reaches the Hole, the Mouse wins.\n\tIf ever a position is repeated (i.e., the players are in the same position as a previous turn, and&nbsp;it is the same player's turn to move), the game is a draw.\n\n\nGiven a graph, and assuming both players play optimally, return\n\n\n\t1&nbsp;if the mouse wins the game,\n\t2&nbsp;if the cat wins the game, or\n\t0&nbsp;if the game is a draw.\n\n\n&nbsp;\nExample 1:\n\nInput: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput: 0\n\n\nExample 2:\n\nInput: graph = [[1,3],[0],[3],[0,2]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= graph.length &lt;= 50\n\t1&nbsp;&lt;= graph[i].length &lt; graph.length\n\t0 &lt;= graph[i][j] &lt; graph.length\n\tgraph[i][j] != i\n\tgraph[i] is unique.\n\tThe mouse and the cat can always move.&nbsp;\n\n",
        "solution_py": "class Solution:\n    def catMouseGame(self, graph: List[List[int]]) -> int:\n        def getPreStates(m,c,t):\n            ans = []\n            if t == 1:\n                for c2 in graph[c]:\n                    if c2 == 0:continue\n                    ans.append((m,c2,2))\n            else:\n                for m2 in graph[m]:\n                    ans.append((m2,c,1))\n            return ans\n        \n        def ifAllNextMovesFailed(m,c,t):\n            if t == 1:\n                for m2 in graph[m]:\n                    if result[(m2,c,2)] != 2:return False\n            else:\n                for c2 in graph[c]:\n                    if c2 == 0:continue\n                    if result[(m,c2,1)] != 1:return False\n            return True\n        \n        result = defaultdict(lambda:0) \n        # key = (m,c,turn) value = (0/1/2)\n        n = len(graph)\n        queue = deque()\n        \n        for t in range(1,3):\n            for i in range(1,n):\n                # mouse win \n                result[(0,i,t)] = 1\n                queue.append((0,i,t))\n                # cat win\n                result[(i,i,t)] = 2\n                queue.append((i,i,t))\n        \n        while queue:\n            m,c,t = queue.popleft()\n            r = result[(m,c,t)]\n            for m2,c2,t2 in getPreStates(m,c,t):\n                r2 = result[(m2,c2,t2)]\n                if r2 > 0:continue\n                # populate prestate\n                if r == 3-t: # can always win\n                    result[(m2,c2,t2)] = r\n                    queue.append((m2,c2,t2))\n                elif ifAllNextMovesFailed(m2,c2,t2):\n                    result[(m2,c2,t2)] =3-t2\n                    queue.append((m2,c2,t2))\n        return result[(1,2,1)]\n                    ",
        "solution_js": "var catMouseGame = function(graph) {\n    let n=graph.length,\n        memo=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2*n+1)])),\n        seen=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2)]))\n    //dfs returns 0 1 2, whether the current player loses,wins, or draws respectively\n    let dfs=(M,C,level)=>{\n        let turn=level%2,curr=turn?C:M,draw=0,res=0\n        //draw when we ve seen the state before or cycles\n        if(seen[M][C][turn]!==undefined||level>=2*n) \n            return memo[M][C][level]=2 \n        if(M==0)// win for mouse if it reaches the hole, loss for cat\n            memo[M][C][level]=turn^1\n        if(M==C)// win for cat if it reaches the mouse, loss for mouse\n            memo[M][C][level]=turn \n        if(memo[M][C][level]===undefined){\n            seen[M][C][turn]=0 //set this state as visited\n            for(let i=0;i<graph[curr].length&&!res;i++) //traverse for the available edges\n                if( !(turn&&(!graph[curr][i]))){ //The cat cant move into the hole\n                    let val=turn?\n                            dfs(M,graph[curr][i],level+1):\n                            dfs(graph[curr][i],C,level+1)\n                    if(val===2) \n                        draw=1 //set draw as an available option\n                    else\n                        res|=(1^val) //minimax logic, always prefer the losing state of the opponent\n                }\n            memo[M][C][level]=res||(2*draw) // set in this order 1->2->0 \n        }\n        seen[M][C][turn]=undefined;// de-set the state for the current game,as it concluded\n        return memo[M][C][level]\n    }\n    return [2,1,0][dfs(1,2,0)] //js eye candy\n};",
        "solution_java": "class Solution {\n    int TIME_MAX = 200;\n    int DRAW = 0;\n    int MOUSE_WIN = 1;\n    int CAT_WIN = 2;\n    public int catMouseGame(int[][] graph) {\n        return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]);\n    }\n\n    private int dfs(int time, int[] p, int[][] graph, Integer[][][] memo){ // p[0] -> mouse position, p[1] -> cat position\n        Integer old = memo[time][p[0]][p[1]];\n        if (old != null) return old; // all the base cases here\n        if (time >= TIME_MAX) return DRAW;\n        if (p[0]==0) return MOUSE_WIN;\n        if (p[0]==p[1]) return CAT_WIN;\n        int state = 0;\n        int where = p[time&1];\n        int res = DRAW;\n        for (int i = 0; i < graph[where].length; i++){\n            if ((time&1)==0||graph[where][i]>0){ // if mouse turn or cat turn and the dest is not 0, do ...\n                p[time&1]=graph[where][i];\n                state |= 1 << dfs(time+1, p, graph, memo);\n                if ((time&1)>0&&(state&4)>0 || (time&1)==0&&(state&2)>0) // if mouse's turn & mouse win\n                    break; // or cat's turn & cat win, then we stop.\n            }\n        }\n        p[time&1]=where; // restore p\n        if (((time&1)>0 && (state & 4)>0)||((time&1)==0) && state==4){\n            res = CAT_WIN; // cat win when (cat's turn & cat win) or (mouse's turn and state = cat)\n        }else if (((time&1)==0 && (state & 2)>0)||(time&1)==1 && state==2){\n            res = MOUSE_WIN; // mouse win when (mouse's turn and mouse win) or (cat's turn and state = mouse)\n        }\n        return memo[time][p[0]][p[1]]=res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int catMouseGame(vector<vector<int>>& graph) {\n        int N = graph.size();\n        vector<vector<int>> dp[2];\n        vector<vector<int>> outdegree[2];\n        queue<vector<int>> q; // q of {turn, mouse position, cat position} for topological sort\n\n        dp[0] = vector<vector<int>>(N, vector<int>(N));\n        dp[1] = vector<vector<int>>(N, vector<int>(N));\n        outdegree[0] = vector<vector<int>>(N, vector<int>(N));\n        outdegree[1] = vector<vector<int>>(N, vector<int>(N));\n\n        // init dp and queue\n        for (int j = 0; j < N; ++j) {\n            dp[0][0][j] = dp[1][0][j] = 1;\n            q.push({0, 0, j});\n            q.push({1, 0, j});\n        }\n        for (int j = 1; j < N; ++j) {\n            dp[0][j][j] = dp[1][j][j] = 2;\n            q.push({0, j, j});\n            q.push({1, j, j});\n        }\n        // init outdegree\n        for (int i = 0; i < N; ++i) {\n            for (int j = 1; j < N; ++j) {\n                outdegree[0][i][j] = graph[i].size();\n                outdegree[1][i][j] = graph[j].size();\n            }\n        }\n        for (auto &v : graph[0]) {\n            for (int i = 0; i < N; ++i) {\n                outdegree[1][i][v]--;\n            }\n        }\n        // run the topological sort from queue\n        while (q.size()) {\n            auto turn = q.front()[0];\n            auto mouse = q.front()[1];\n            auto cat = q.front()[2];\n            q.pop();\n\n            if (turn == 0 && mouse == 1 && cat == 2) {\n                // the result has been inferenced\n                break;\n            }\n\n            if (turn == 0) { // mouse's turn\n                // v is the prev position of cat\n                for (auto &v : graph[cat]) {\n                    if (v == 0) {\n                        continue;\n                    }\n\n                    if (dp[1][mouse][v] > 0) {\n                        continue;\n                    }\n\n                    if (dp[turn][mouse][cat] == 2) {\n                        // cat wants to move from v to `cat` position, and thus cat wins\n                        dp[1][mouse][v] = 2;\n                        q.push({1, mouse, v});\n                        continue;\n                    }\n\n                    outdegree[1][mouse][v]--;\n                    if (outdegree[1][mouse][v] == 0) {\n                        dp[1][mouse][v] = 1;\n                        q.push({1, mouse, v});\n                    }\n                }\n            } else { // cat's turn\n                // v is the prev position of mouse\n                for (auto &v : graph[mouse]) {\n                    if (dp[0][v][cat] > 0) {\n                        continue;\n                    }\n\n                    if (dp[turn][mouse][cat] == 1) {\n                        // mouse wants to move from v to `mouse` position and thus mouse wins\n                        dp[0][v][cat] = 1;\n                        q.push({0, v, cat});\n                        continue;\n                    }\n\n                    outdegree[0][v][cat]--;\n                    if (outdegree[0][v][cat] == 0) {\n                        dp[0][v][cat] = 2;\n                        q.push({0, v, cat});\n                    }\n                }\n            }\n        }\n\n        return dp[0][1][2];\n    }\n};"
    },
    {
        "title": "Find Good Days to Rob the Bank",
        "algo_input": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time.\n\nThe ith day is a good day to rob the bank if:\n\n\n\tThere are at least time days before and after the ith day,\n\tThe number of guards at the bank for the time days before i are non-increasing, and\n\tThe number of guards at the bank for the time days after i are non-decreasing.\n\n\nMore formally, this means day i is a good day to rob the bank if and only if security[i - time] &gt;= security[i - time + 1] &gt;= ... &gt;= security[i] &lt;= ... &lt;= security[i + time - 1] &lt;= security[i + time].\n\nReturn a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.\n\n&nbsp;\nExample 1:\n\nInput: security = [5,3,3,3,5,6,2], time = 2\nOutput: [2,3]\nExplanation:\nOn day 2, we have security[0] &gt;= security[1] &gt;= security[2] &lt;= security[3] &lt;= security[4].\nOn day 3, we have security[1] &gt;= security[2] &gt;= security[3] &lt;= security[4] &lt;= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.\n\n\nExample 2:\n\nInput: security = [1,1,1,1,1], time = 0\nOutput: [0,1,2,3,4]\nExplanation:\nSince time equals 0, every day is a good day to rob the bank, so return every day.\n\n\nExample 3:\n\nInput: security = [1,2,3,4,5,6], time = 2\nOutput: []\nExplanation:\nNo day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= security.length &lt;= 105\n\t0 &lt;= security[i], time &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n        decreasing = [0] * len(security)\n        increasing = [0] * len(security)\n        for i in range(len(security)):\n            if i > 0 and security[i - 1] >= security[i]:\n                decreasing[i] = decreasing[i - 1] + 1\n        for i in reversed(range(len(security))):\n            if i < len(security) - 1 and security[i] <= security[i + 1]:\n                increasing[i] = increasing[i + 1] + 1\n        return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time]",
        "solution_js": "var goodDaysToRobBank = function(security, time) {\n    let res = [];\n    if(!time){\n       let i = 0;\n        while(i<security.length) res.push(i), i++;\n        return res;\n    }\n    let increasing = 0;\n    let decreasing = 0;\n    let set = new Set();\n    for(let i = 1; i < security.length; i++){\n        if(security[i]>security[i-1]) decreasing = 0;\n        else decreasing++;\n        if(security[i]<security[i-1]) increasing = 0;\n        else increasing++;\n        if(decreasing>=time) set.add(i);\n        if(increasing>=time&&set.has(i-time)) res.push(i-time);\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<Integer> goodDaysToRobBank(int[] security, int time) {\n        List<Integer> res = new ArrayList<>();\n        if (time == 0) {\n            for (int i = 0; i < security.length; i++) res.add(i);\n            return res;\n        }\n        Set<Integer> set = new HashSet<>();\n        int count = 1;\n        for (int i = 1; i < security.length; i++) {\n            if (security[i] <= security[i - 1]) {\n                count++;\n            } else {\n                count = 1;\n            }\n            if (count > time) {\n                set.add(i);\n            }\n        }\n        \n        count = 1;\n        for (int i = security.length - 2; i >= 0; i--) {\n            if (security[i] <= security[i + 1]) {\n                count++;\n            } else {\n                count = 1;\n            }\n            if (count > time && set.contains(i)) res.add(i);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> goodDaysToRobBank(vector<int>& security, int time) {\n        int n = security.size();\n        vector<int> prefix(n), suffix(n);\n        vector<int> ans;\n        \n        prefix[0] = 0;\n        for(int i=1;i<n;i++) {\n            if(security[i] <= security[i-1]) prefix[i] = prefix[i-1]+1;\n            else prefix[i] = 0;\n        }\n        \n        suffix[n-1] = 0;\n        for(int i=(n-2);i>=0;i--) {\n            if(security[i] <= security[i+1]) suffix[i] = suffix[i+1]+1;\n            else suffix[i] = 0;\n        }\n        \n        for(int i=0;i<n;i++) {\n            if(prefix[i]>=time && suffix[i]>=time) ans.push_back(i);\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Stone Game VI",
        "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nThere are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.\n\nYou are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.\n\nThe winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally.&nbsp;Both players know the other's values.\n\nDetermine the result of the game, and:\n\n\n\tIf Alice wins, return 1.\n\tIf Bob wins, return -1.\n\tIf the game results in a draw, return 0.\n\n\n&nbsp;\nExample 1:\n\nInput: aliceValues = [1,3], bobValues = [2,1]\nOutput: 1\nExplanation:\nIf Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.\n\n\nExample 2:\n\nInput: aliceValues = [1,2], bobValues = [3,1]\nOutput: 0\nExplanation:\nIf Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.\n\n\nExample 3:\n\nInput: aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput: -1\nExplanation:\nRegardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == aliceValues.length == bobValues.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= aliceValues[i], bobValues[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def stoneGameVI(self, A, B):\n        G  = [a+b for a,b in zip(A,B)]\n        G.sort()\n        L  = len(A)\n        d  = -sum(B) + sum( G[i] for i in range(L-1,-1,-2) )\n        return 1 if d>0 else ( -1 if d<0 else 0 )",
        "solution_js": "var stoneGameVI = function(aliceValues, bobValues) {\n    let aliceVal = 0\n    let bobVal = 0\n    let turn = true\n    const combined = {}\n    let n = aliceValues.length\n    for (let i = 0; i < n; i++) {\n        if (combined[aliceValues[i] + bobValues[i]]) {\n            combined[aliceValues[i] + bobValues[i]].push({value: aliceValues[i] + bobValues[i], id: i})\n        } else {\n            combined[aliceValues[i] + bobValues[i]] = [{value: aliceValues[i] + bobValues[i], id: i}]\n        }\n    }\n    Object.values(combined).reverse().forEach((value) => {\n        value.forEach(val => {\n            if (turn) {\n                aliceVal += aliceValues[val.id]\n            } else {\n                bobVal += bobValues[val.id]\n            }\n            turn = !turn\n        })\n    })\n    if (aliceVal === bobVal) return 0\n    return aliceVal > bobVal ? 1 : -1\n};",
        "solution_java": "class Solution \n{\nstatic class Pair\n{\n        int sum=0;\n        int alice=0;\n        int bob=0;\n    public Pair(int sum,int alice, int bob)\n{\n    this.sum=sum;\n\tthis.alice = alice;\n\tthis.bob = bob;\n}\n}\n\n// class to define user defined conparator\nstatic class Compare {\n\t\n\tstatic  void compare(Pair arr[], int n)\n\t{\n\t\t// Comparator to sort the pair according to second element\n\t\tArrays.sort(arr, new Comparator<Pair>() {\n\t\t\t@Override public int compare(Pair p1, Pair p2)\n\t\t\t{\n\t\t\t\treturn p2.sum - p1.sum;\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t}\n}\n    public int stoneGameVI(int[] aliceValues, int[] bobValues)\n    {\n        int n=aliceValues.length;\n        Pair[] a=new Pair[n];\n        for(int i=0;i<n;i++)\n        {\n            a[i]=new Pair(aliceValues[i]+bobValues[i],aliceValues[i],bobValues[i]);\n        }\n        Compare.compare(a,n);\n         int al=0;int bo=0;\n        for(int i=0;i<n;i++)\n        {\n            if(i%2==0)\n            {\n                al+=a[i].alice;\n            }\n            else\n            {\n                bo+=a[i].bob;\n            }\n        }\n        return Integer.compare(al,bo);\n    \n    \n    \n    }\n}",
        "solution_c": "vector<int> alice, bob;\n\nstruct myComp {\n  bool operator()(pair<int, int>& a, pair<int, int>& b){\n      return alice[a.second] + bob[a.second] < alice[b.second] + bob[b.second];\n  }\n};\n\nclass Solution {\npublic:\n    int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) {\n        alice = aliceValues;\n        bob = bobValues;\n        priority_queue<pair<int, int>, vector<pair<int, int>>, myComp> a,b;\n\n        for(int i=0;i<aliceValues.size();i++){\n            a.push({aliceValues[i], i});\n            b.push({bobValues[i], i});\n        }\n\n        int ans1, ans2;\n        ans1 = ans2 = 0;\n        int vis[100001] = {};\n\n        while(a.size()){\n            while(a.size() && vis[a.top().second] == 1) a.pop();\n            if(a.size()){\n                ans1 += a.top().first;\n                vis[a.top().second] = 1;\n                a.pop();\n            }\n\n            while(b.size() && vis[b.top().second] == 1) b.pop();\n            if(b.size()){\n                ans2 += b.top().first;\n                vis[b.top().second] = 1;\n                b.pop();\n            }\n        }\n\n        if(ans1 == ans2) return 0;\n        if(ans1 > ans2) return 1;\n        return -1;\n    }\n};"
    },
    {
        "title": "Find the Student that Will Replace the Chalk",
        "algo_input": "There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.\n\nYou are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.\n\nReturn the index of the student that will replace the chalk.\n\n&nbsp;\nExample 1:\n\nInput: chalk = [5,1,5], k = 22\nOutput: 0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.\n\nExample 2:\n\nInput: chalk = [3,4,1,2], k = 25\nOutput: 1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.\n\n\n&nbsp;\nConstraints:\n\n\n\tchalk.length == n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= chalk[i] &lt;= 105\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def chalkReplacer(self, chalk: List[int], k: int) -> int:\n        x = sum(chalk)\n        if x<k:\n            k = k%x\n        if x == k:\n            return 0\n        i = 0\n        n = len(chalk)\n        while True:\n            if chalk[i]<=k:\n                k -= chalk[i]\n            else:\n                break\n            i +=1\n               \n        return i",
        "solution_js": "var chalkReplacer = function(chalk, k) {\n    const sum = chalk.reduce((r, c) => r + c, 0);\n    \n    k %= sum;\n    \n    for (let i = 0; i < chalk.length; i++) {\n        if (chalk[i] > k) {\n            return i;\n        }\n\n        k -= chalk[i];\n    }\n};",
        "solution_java": "class Solution {\n\npublic int chalkReplacer(int[] chalk, int k) {\n    long sum = 0;\n    for (int c : chalk) {\n        sum += c;\n    }\n    long left = k % sum; \n    for (int i = 0; i < chalk.length; i++){\n        if(left >= chalk[i]){ \n            left -= chalk[i];\n        } else {    \n            return i;\n        }\n    }\n    return -1;  //just for return statement, put whatever you want here\n}\n}",
        "solution_c": "class Solution {\npublic:\n    // T(n) = O(n) S(n) = O(1) \n    int chalkReplacer(vector<int>& chalk, int k) {\n        // Size of the vector\n        int n = chalk.size();\n        // Store the sum of the elements in the vector\n        long sum = 0;\n        // Calculate the sum of the elements \n        for (int n : chalk) sum += n;\n        // Update k as the remainder of the sum \n        // to make sure that the while loop\n\t\t// will traverse the vector at most 1 time\n        k = k % sum;\n        // Start from the initial value in the array\n        int idx = 0;\n        // While the next student has enough chalk\n        while (k >= chalk[idx]) {\n            // Decrease the remaining chalk\n            k -= chalk[idx];\n            // Increase the index\n            idx = (idx + 1) % n;\n        }\n        // Return the index of the student without\n        // enough chalk\n        return idx;\n    }\n};"
    },
    {
        "title": "Largest Merge Of Two Strings",
        "algo_input": "You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options:\n\n\n\tIf word1 is non-empty, append the first character in word1 to merge and delete it from word1.\n\n\t\n\t\tFor example, if word1 = \"abc\" and merge = \"dv\", then after choosing this operation, word1 = \"bc\" and merge = \"dva\".\n\t\n\t\n\tIf word2 is non-empty, append the first character in word2 to merge and delete it from word2.\n\t\n\t\tFor example, if word2 = \"abc\" and merge = \"\", then after choosing this operation, word2 = \"bc\" and merge = \"a\".\n\t\n\t\n\n\nReturn the lexicographically largest merge you can construct.\n\nA string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c.\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"cabaa\", word2 = \"bcaaa\"\nOutput: \"cbcabaaaaa\"\nExplanation: One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.\n\n\nExample 2:\n\nInput: word1 = \"abcabc\", word2 = \"abdcaba\"\nOutput: \"abdcabcabcaba\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word1.length, word2.length &lt;= 3000\n\tword1 and word2 consist only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def largestMerge(self, word1: str, word2: str) -> str:\n        res = ''\n        p1 = 0\n        p2 = 0\n        while p1 < len(word1) and p2 < len(word2):\n            if word1[p1:] > word2[p2:]:\n                res += word1[p1]\n                p1 += 1\n            else:\n                res += word2[p2]\n                p2 += 1\n        \n        res += word1[p1:] + word2[p2:]\n\n        \n        return res",
        "solution_js": "var largestMerge = function(word1, word2) {\n    let ans = '';\n    let w1 = 0, w2 = 0;\n\n    while(w1 < word1.length && w2 < word2.length) {\n        if(word1[w1] > word2[w2]) ans += word1[w1++];\n        else if(word2[w2] > word1[w1]) ans += word2[w2++];\n        else {\n            const rest1 = word1.slice(w1);\n            const rest2 = word2.slice(w2);\n\n            if(rest1 > rest2) ans += word1[w1++];\n            else ans += word2[w2++];\n        }\n    }\n    ans += word1.slice(w1);\n    ans += word2.slice(w2);\n    return ans;\n};",
        "solution_java": "class Solution {\n    public String largestMerge(String word1, String word2) {\n        StringBuilder sb = new StringBuilder();\n        int i=0;\n        int j=0;\n        char[] w1 = word1.toCharArray();\n        char[] w2 = word2.toCharArray();\n        \n        int n1=w1.length;\n        int n2=w2.length;\n        \n        // we loop until we exhaust any one of the 2 words completely\n        while(i<n1 && j<n2){\n            \n            // if both the characters are equal we choose the one where the next largest occurs earlier\n            if(w1[i]==w2[j]){\n                if(check(w1,i,w2,j)){\n                    sb.append(w1[i++]);\n                }else{\n                    sb.append(w2[j++]);\n                }\n            }\n            \n            // else we greedily choose the largest of the two characters\n            else if(w1[i]>w2[j]){\n                sb.append(w1[i++]);\n            }else{\n                sb.append(w2[j++]);\n            }\n        }\n        \n        // at the end of the loop we append any remaining word\n        sb.append(word1.substring(i));\n        sb.append(word2.substring(j));\n\t\t\n        return sb.toString();\n    }\n    \n    private boolean check(char[] w1, int i, char[] w2, int j){\n        // will return true if we need to extract from word1 and false if we need to extract from word2\n        \n        while(i<w1.length && j<w2.length){\n            if(w1[i]==w2[j]){\n                i++;\n                j++;\n            }\n            else if(w1[i]>w2[j]){\n                return true;\n            }else{\n                return false;\n            }\n        }\n        \n        // if we are unable to find any exhaustable character till the end of the loop we use the one having larger length\n        if(i<w1.length){\n            return true;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestMerge(string word1, string word2) {\n        \n        string ans=\"\";\n        \n        while(word1.size()!=0 && word2.size()!=0){\n            if(word1>=word2) {ans+=word1[0];word1=word1.substr(1);}\n            \n            else             {ans+=word2[0];word2=word2.substr(1);}\n        }\n        \n        if(word1.size()!=0)ans=ans+word1;\n        if(word2.size()!=0)ans=ans+word2;\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Perfect Number",
        "algo_input": "A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.\n\nGiven an integer n, return true if n is a perfect number, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: num = 28\nOutput: true\nExplanation: 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.\n\n\nExample 2:\n\nInput: num = 7\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def checkPerfectNumber(self, num: int) -> bool:\n        sum = 0\n        root = num**0.5  \n        if num ==1:\n            return False\n        for i in range(2,int(root)+1):\n            if num%i== 0:\n                sum +=(num//i)+i\n        return sum+1 == num",
        "solution_js": "    /**\n * @param {number} num\n * @return {boolean}\n */\nvar checkPerfectNumber = function(num) {\n    let total = 0\n\n    for(let i = 1 ; i < num;i++){\n        if(num % i == 0){\n            total += i\n        }\n    }\n    return total == num ? true : false\n};",
        "solution_java": "class Solution {\n    public boolean checkPerfectNumber(int num) {\n        if(num==1)\n        return false;\n\n        int sum = 1;\n        for(int i=2; i<Math.sqrt(num); i++){\n            if(num%i==0){\n            sum += i + num / i;\n            }\n        }\n        if(sum==num){\n        return true;\n        }\n        else{\n        return false;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkPerfectNumber(int num) {\n    // we are initialising sum with 1 instead of 0 because 1 will be divisor of every number\n        int sum=1;\n        for(int i=2; i<sqrt(num); i++){\n            if(num%i==0){\n            // it checks if both are same factors, for ex, if num=9, i=3, num/i is also equal to 3. It is done so that repeated factors aren't added.\n                if(i==num/i){\n                    sum += i;\n                }\n                else{\n                // we are adding n/i because since we are running the loop for sqrt(num), we will be missing divisors >sqrt(num) so tto include that factor we'll add num/i; for ex if we have 64 as number than 8 is sqrt but 16 and 32 also divides 64 but our loop won't consider that case; so we are adding num/i, which means with 2 we are adding 32 and with 4 we are adding 16.\n                    sum += i + num/i;\n                }\n            }\n        }\n        if(sum==num && num!=1){\n            return true;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Making File Names Unique",
        "algo_input": "Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].\n\nSince two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\n\nReturn an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n\n&nbsp;\nExample 1:\n\nInput: names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput: [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation: Let's see how the file system creates folder names:\n\"pes\" --&gt; not assigned before, remains \"pes\"\n\"fifa\" --&gt; not assigned before, remains \"fifa\"\n\"gta\" --&gt; not assigned before, remains \"gta\"\n\"pes(2019)\" --&gt; not assigned before, remains \"pes(2019)\"\n\n\nExample 2:\n\nInput: names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput: [\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation: Let's see how the file system creates folder names:\n\"gta\" --&gt; not assigned before, remains \"gta\"\n\"gta(1)\" --&gt; not assigned before, remains \"gta(1)\"\n\"gta\" --&gt; the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --&gt; not assigned before, remains \"avalon\"\n\n\nExample 3:\n\nInput: names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput: [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation: When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= names.length &lt;= 5 * 104\n\t1 &lt;= names[i].length &lt;= 20\n\tnames[i] consists of lowercase English letters, digits, and/or round brackets.\n\n",
        "solution_py": "class Solution:\n    def getFolderNames(self, names: List[str]) -> List[str]:\n        # Hashmap will store the name as key and the number of times that name has duplicated so fas as value.\n        hashmap = {}\n\n        for name in names:\n            modified = name\n            # Check whether the name has already been used\n            if name in hashmap:\n                # Get the number of times the {name} has been used\n                k = hashmap[name]\n                # Calculate the next available suffix.\n                while modified in hashmap:\n                    k += 1\n                    modified = f'{name}({k})'\n                # Update the number of times the original {name} is used. This will help to efficiently check for next available suffix if the {name} again comes in future.\n                hashmap[name] = k\n            # Store the modified {name} with 0 as it is not duplicated yet.\n            hashmap[modified] = 0\n\n        # Return the keys of hashmap as that would be the unique file names.\n        return hashmap.keys()",
        "solution_js": "/**\n * @param {string[]} names\n * @return {string[]}\n */\nvar getFolderNames = function(names) {\n    // save existed folder names\n    let hashMap = new Map();\n    for(let name of names) {\n        let finalName = name;\n        // next smallest suffix number\n        // if this name is not present in the map, next smallest suffix will be 1\n        let number = hashMap.get(name) || 1;\n        if(hashMap.has(name)) {\n            // append suffix to original name\n            finalName += '(' + number +')';\n            // find the smallest suffix that hasn't been used before\n            while(hashMap.has(finalName)) {\n                number++;\n                // try to use new suffix to update name\n                finalName = name + '(' + number +')';\n            }\n            // update next smallest suffix number of new name\n            hashMap.set(finalName, 1);\n        }\n        // update next smallest suffix number of original name\n        hashMap.set(name, number);\n    }\n    return Array.from(hashMap.keys());\n};",
        "solution_java": "class Solution {\n    Map<String, Integer> map = new HashMap<>();\n    \n    public String[] getFolderNames(String[] names) {\n        String[] op = new String[names.length];\n        int i = 0;\n        \n        for(String cur : names){\n            if(map.containsKey(cur)) {\n                cur = generateCopyName(cur);\n                op[i++] = cur;\n             //   System.out.println(map.toString());\n                continue;\n            }\n            \n            op[i++] = cur;\n            map.put(cur, 0);\n           // System.out.println(map.toString());\n        }\n        \n        return op;\n    }\n    \n    private String generateCopyName(String s) {\n        int count = map.get(s) + 1;\n        \n        String postfix = \"(\" + count + \")\";\n        StringBuilder sb = new StringBuilder(s);\n        sb.append(postfix);\n        \n        boolean isChanged = false;\n        while(map.containsKey(sb.toString())) {\n            sb = new StringBuilder(s);\n            sb.append(\"(\" + count + \")\");\n            count++;\n            isChanged = true;\n        }\n        String res = sb.toString();\n        //System.out.println(res);\n        \n        \n        if(isChanged)\n            count = count -1;\n        \n        map.put(s, count);\n        map.put(res, 0);\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\n    \n    unordered_map<string, int> next_index_;\n    \n    bool contain(const string& fn) {\n        return next_index_.find(fn) != next_index_.end();\n    }\n    \n    string get_name(string fn) {\n        if (!contain(fn)) {\n            next_index_.insert({fn, 1});\n            return fn;\n        }\n        \n        int idx = next_index_[fn];\n        auto cur = fn;\n        while (contain(cur)) {\n            next_index_.insert({cur, 1});\n            cur = fn + \"(\" + to_string(idx) + \")\";\n            ++idx;\n        }\n        next_index_.insert({cur, 1});\n        next_index_[fn] = idx;\n        return cur;\n    }\n    \npublic:\n    vector<string> getFolderNames(vector<string>& names) {\n        vector<string> res;\n        for (auto& n : names) {\n            res.push_back(get_name(n));\n        }\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Subdomain Visit Count",
        "algo_input": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\"&nbsp;and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly.\n\nA count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.\n\n\n\tFor example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.\n\n\nGiven an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput: [\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation: We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.\n\n\nExample 2:\n\nInput: cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput: [\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation: We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= cpdomain.length &lt;= 100\n\t1 &lt;= cpdomain[i].length &lt;= 100\n\tcpdomain[i] follows either the \"repi d1i.d2i.d3i\" format or the \"repi d1i.d2i\" format.\n\trepi is an integer in the range [1, 104].\n\td1i, d2i, and d3i consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n        output, ans = {}, []\n        for domain in cpdomains : \n            number, domain = domain.split(' ')\n            sub_domain = domain.split('.')\n            pair = ''\n            print(sub_domain)\n            for i in reversed(range(len(sub_domain))) :\n                if i == len(sub_domain)-1 : \n                    pair += sub_domain[i]\n                else : \n                    pair = sub_domain[i] +'.'+ pair \n                print(pair)\n                \n                # output.append(str(number) + ' '+pair)\n                if pair not in output.keys() : \n                    output[pair] = int(number)\n                else : \n                    output[pair] += int(number)\n                    \n        for key in output.keys() : \n            ans.append(str(output[key]) + ' '+key)\n                \n        return ans",
        "solution_js": "/**\n * @param {string[]} cpdomains\n * @return {string[]}\n */\nvar subdomainVisits = function(cpdomains) {\n    let map = {}\n    cpdomains.forEach(d => {\n        let data = d.split(\" \");\n        let arr = data[1].split(\".\")\n        while(arr.length > 0) {\n            if(arr.join(\".\") in map) map[arr.join(\".\")]+=+data[0]\n            else map[arr.join(\".\")] = +data[0]\n            arr.shift()\n        }\n    })\n    let result = []\n    for(let key in map) result.push(map[key] + \" \"+ key)\n    return result\n};",
        "solution_java": "class Solution {\n    public List<String> subdomainVisits(String[] cpdomains) {\n        List<String> result = new LinkedList<>();\n        HashMap<String, Integer> hmap = new HashMap<>();\n        \n        for(int i = 0; i < cpdomains.length; i++){\n            String[] stringData = cpdomains[i].split(\" \");\n            String[] str = stringData[1].split(\"\\\\.\");\n            String subDomains = \"\";\n            \n            for(int j = str.length-1; j >= 0; j--){\n                subDomains = str[j] + subDomains;\n                    \n                if(!hmap.containsKey(subDomains))\n                    hmap.put(subDomains, Integer.parseInt(stringData[0]));\n                else\n                    hmap.put(subDomains, hmap.get(subDomains) + Integer.parseInt(stringData[0]));\n                subDomains = \".\" + subDomains;\n            }\n            \n        }\n        \n        for(Map.Entry<String, Integer> entry: hmap.entrySet()){\n            result.add(entry.getValue() + \" \" + entry.getKey());\n        }\n        \n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> subdomainVisits(vector<string>& cpdomains) {\n        vector<string> v;\n        unordered_map<string,int> m;\n        for(auto it : cpdomains){\n            string rep=\"\";\n            int i=0;\n            while(it[i]!=' '){\n                  rep+=(it[i]);\n                    i++;\n            }\n            int r=stoi(rep);\n            m[it.substr(i+1,it.size())]+=r;\n\n            while(it[i]!='.'){\n                i++;\n            }\n            m[it.substr(i+1,it.size())]+=r;\n            i++;\n            while(i<it.size() and it[i]!='.'){\n                i++;\n            }\n            if(i!=it.size()){\n            m[it.substr(i+1,it.size())]+=r;\n            }\n\n        }\n\n        for(auto it : m){\n            string a=it.first;\n            string b=to_string(it.second);\n            a=b+\" \"+a;\n            v.push_back(a);\n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Evaluate Reverse Polish Notation",
        "algo_input": "Evaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are +, -, *, and /. Each operand may be an integer or another expression.\n\nNote that division between two integers should truncate toward zero.\n\nIt is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.\n\n&nbsp;\nExample 1:\n\nInput: tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\n\n\nExample 2:\n\nInput: tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\n\n\nExample 3:\n\nInput: tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\nOutput: 22\nExplanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tokens.length &lt;= 104\n\ttokens[i] is either an operator: \"+\", \"-\", \"*\", or \"/\", or an integer in the range [-200, 200].\n\n",
        "solution_py": "class Solution:\n    def evalRPN(self, tokens: List[str]) -> int:\n        stack = []      \n        for i in tokens:\n            if i == \"+\":\n                stack[-1] = stack[-2] + stack.pop()\n            elif i == \"-\":\n                stack[-1] = stack[-2] - stack.pop()\n            elif i == \"*\":\n                stack[-1] = stack[-2] * stack.pop()\n            elif i == \"/\":\n                stack[-1] = int(stack[-2] / stack.pop())\n            else:\n                stack.append(int(i))\n                \n        return stack.pop()\n                    ",
        "solution_js": "const ops = new Set(['+', '-', '*', '/']);\n\n/**\n * @param {string[]} tokens\n * @return {number}\n */\nvar evalRPN = function(tokens) {\n    const stack = [];\n\n    for (const token of tokens) {\n        if (!ops.has(token)) {\n            stack.push(Number(token));\n            continue;\n        }\n\n        const val1 = stack.pop();\n        const val2 = stack.pop();\n        let toPush;\n\n        if (token === '+') {\n            toPush = val1 + val2;\n        }\n\n        if (token === '-') {\n            toPush = val2 - val1;\n        }\n\n        if (token === '*') {\n            toPush = val1 * val2;\n        }\n\n        if (token === '/') {\n            toPush = Math.trunc(val2 / val1);\n        }\n\n        stack.push(toPush);\n    }\n\n    return stack[0] || 0;\n};",
        "solution_java": "class Solution {\n    public int evalRPN(String[] tokens) {\n        Stack<Integer> stack = new Stack();\n        for(String i: tokens){\n            if(i.equals(\"+\") || i.equals(\"-\") || i.equals(\"*\") || i.equals(\"/\")){\n                int a = stack.pop();\n                int b = stack.pop();\n                int temp = 0;\n                if(i.equals(\"+\"))\n                    temp = a+b;\n                else if(i.equals(\"-\"))\n                    temp = b-a;\n                else if(i.equals(\"*\"))\n                    temp = a*b;\n                else if(i.equals(\"/\"))\n                    temp = b/a;\n                stack.push(temp);\n            }\n            else\n                stack.push(Integer.parseInt(i));\n        }\n        return stack.pop();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int stoi(string s){\n        int n = 0;\n        int i = 0;\n        bool neg = false;\n        if(s[0] == '-'){\n            i++;\n            neg = true;\n        }\n        for(; i < s.size(); i++){\n            n = n*10 + (s[i]-'0');\n        }\n        if(neg) n = -n;\n        return n;\n    }\n    int evalRPN(vector<string>& tokens) {\n        stack<int>s;\n        int n = tokens.size();\n        for(int i = 0; i < n; i++){\n            string str = tokens[i];\n            if(str == \"*\"){\n                int n1 = s.top();\n                s.pop();\n                int n2 = s.top();\n                s.pop();\n                int res = n2*n1;\n                s.push(res);\n            }\n            else if(str == \"+\") {\n                int n1 = s.top();\n                s.pop();\n                int n2 = s.top();\n                s.pop();\n                int res = n2+n1;\n                s.push(res);\n            }\n            else if(str == \"/\"){\n                int n1 = s.top();\n                s.pop();\n                int n2 = s.top();\n                s.pop();\n                int res = n2/n1;\n                s.push(res);\n            }\n            else if(str == \"-\"){\n                int n1 = s.top();\n                s.pop();\n                int n2 = s.top();\n                s.pop();\n                int res = n2-n1;\n                s.push(res);\n            }\n            else{\n                int num = stoi(str);\n                s.push(num);\n            }\n        }\n        return s.top();\n    }\n};"
    },
    {
        "title": "Find Minimum Time to Finish All Jobs",
        "algo_input": "You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.\n\nThere are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\n\nReturn the minimum possible maximum working time of any assignment. \n\n&nbsp;\nExample 1:\n\nInput: jobs = [3,2,3], k = 3\nOutput: 3\nExplanation: By assigning each person one job, the maximum time is 3.\n\n\nExample 2:\n\nInput: jobs = [1,2,4,7,8], k = 2\nOutput: 11\nExplanation: Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= jobs.length &lt;= 12\n\t1 &lt;= jobs[i] &lt;= 107\n\n",
        "solution_py": "class Solution:\n    \n    def dfs(self, pos: int, jobs: List[int], workers: List[int]) -> int:\n        if pos >= len(jobs):\n            return max(workers)\n        \n        mn = float(\"inf\")\n        # we keep track of visited here to skip workers\n        # with the same current value of assigned work\n\t\t# this is an important step in pruning the number\n\t\t# of workers to explore\n        visited = set()\n        for widx in range(len(workers)):\n            \n            if workers[widx] in visited:\n                continue\n            visited.add(workers[widx])\n            \n            # try this worker\n            workers[widx] += jobs[pos]\n            \n            if max(workers) < mn:\n                # if it's better than our previous proceed\n                res = self.dfs(pos+1, jobs, workers)\n                mn = min(mn, res)\n            \n            # backtrack\n            workers[widx] -= jobs[pos]\n        \n        return mn\n        \n    \n    def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n\t    # sorting the jobs means that highest value jobs are assigned first\n\t\t# and more computations can be skipped by pruning\n        jobs.sort(reverse=True)\n        return self.dfs(0, jobs, [0] * k)",
        "solution_js": "var minimumTimeRequired = function(jobs, k) {\n    let n=jobs.length, maskSum=[...Array(1<<n)].map(d=>0)\n    for(let mask=0;mask<(1<<n);mask++) //pre-store the sums of every mask\n        for(let i=0;i<n;i++)\n            maskSum[mask]+=Number(((1<<i) & mask)!=0)*jobs[i]\n    let dp=[...Array(k+1)].map(d=>[...Array(1<<n)].map(d=>Infinity))\n    dp[0][0]=0\n    for(let i=1;i<=k;i++) //for each new person\n        for(let curmask=0;curmask<(1<<n);curmask++) //guess what his mask can be, what items can he select\n            for(let prevmask=0;prevmask<(1<<n);prevmask++) // but also, guess what the previous i-1 persons took already\n                if((curmask&prevmask)===0) //obviously, 2 people can't take the same job\n                    dp[i][curmask|prevmask]=Math.min(dp[i][curmask|prevmask],Math.max(dp[i-1][prevmask],maskSum[curmask]))\n    return dp[k][(1<<n) -1]\n};",
        "solution_java": "class Solution {\n    int result = Integer.MAX_VALUE;\n    public int minimumTimeRequired(int[] jobs, int k) {\n        int length = jobs.length;\n        Arrays.sort(jobs);\n        backtrack(jobs, length - 1, new int [k]);\n        return result;\n    }\n    \n    public void backtrack(int [] jobs, int current, int [] workers) {\n        if (current < 0) {\n            result = Math.min(result, Arrays.stream(workers).max().getAsInt());\n            return;\n        }\n        \n        if (Arrays.stream(workers).max().getAsInt() >=  result)\n            return;\n        for (int i=0; i<workers.length; i++) {\n            if (i > 0 && workers[i] == workers[i-1])\n                continue;\n            // make choice\n            workers[i] += jobs[current];\n            // backtrack\n            backtrack(jobs, current-1, workers);\n            // undo the choice\n            workers[i] -= jobs[current];\n        }\n    }\n    \n    \n}",
        "solution_c": "class Solution {\npublic:\n    int minimumTimeRequired(vector<int>& jobs, int k) {\n        int sum = 0;\n        for(int j:jobs)\n            sum += j;\n        sort(jobs.begin(),jobs.end(),greater<int>());\n        int l = jobs[0], r = sum;\n        while(l<r){\n            int mid = (l+r)>>1;\n            vector<int> worker(k,0);\n            if(dfs(jobs,worker,0,mid))\n                r = mid;\n            else\n                l = mid + 1;\n        }\n        return l;\n    }\n    bool dfs(vector<int>& jobs, vector<int>& worker, int step, int target){\n        if(step>=jobs.size())\n            return true;\n        int cur = jobs[step];\n        // assign cur to worker i\n        for(int i=0;i<worker.size();i++){\n            if(worker[i] + cur <= target){\n                worker[i] += cur;\n                if(dfs(jobs,worker,step+1,target))\n                    return true;\n                worker[i] -= cur;\n            }\n            if(worker[i]==0)\n                break;\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Binary Tree Inorder Traversal",
        "algo_input": "Given the root of a binary tree, return the inorder traversal of its nodes' values.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,2,3]\nOutput: [1,3,2]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [1]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 100].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow up: Recursive solution is trivial, could you do it iteratively?",
        "solution_py": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime:   O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tinorder = []\n\t\tstack = []\n\n\t\twhile stack or root is not None:\n\t\t\tif root:\n\t\t\t\tstack.append(root)\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\tnode = stack.pop()\n\t\t\t\tinorder.append(node.val)\n\t\t\t\troot = node.right\n\n\t\treturn inorder\n\n\nclass Solution:\n\t\"\"\"\n\tTime:   O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.inorder_generator(root))\n\n\t@classmethod\n\tdef inorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.inorder_generator(tree.left)\n\t\t\tyield tree.val\n\t\t\tyield from cls.inorder_generator(tree.right)",
        "solution_js": "var inorderTraversal = function(root) {\n    let result = [];\n    function traverse(node) {\n        if(!node) {\n            return;\n        }\n        traverse(node.left);\n        result.push(node.val);\n        traverse(node.right);\n    }\n    traverse(root);\n    return result;\n};",
        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    List<Integer> li = new LinkedList<Integer>();\n    public List<Integer> inorderTraversal(TreeNode root) {\n     if(root == null){\n         List<Integer> li = new LinkedList<Integer>();\n         return li ;\n     }\n     inorderTraversal(root.left);     \n     li.add(root.val);     \n     inorderTraversal(root.right);\n     return li;\n\n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> v;\n    vector<int> inorderTraversal(TreeNode* root) {\n        if(root!=NULL){\n            inorderTraversal(root->left);\n            v.push_back(root->val);\n            inorderTraversal(root->right);            \n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Implement Trie (Prefix Tree)",
        "algo_input": "A trie (pronounced as \"try\") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.\n\nImplement the Trie class:\n\n\n\tTrie() Initializes the trie object.\n\tvoid insert(String word) Inserts the string word into the trie.\n\tboolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.\n\tboolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]\nOutput\n[null, null, true, false, true, null, true]\n\nExplanation\nTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\");   // return True\ntrie.search(\"app\");     // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\");     // return True\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length, prefix.length &lt;= 2000\n\tword and prefix consist only of lowercase English letters.\n\tAt most 3 * 104 calls in total will be made to insert, search, and startsWith.\n\n",
        "solution_py": "class Node : \n    def __init__(self ):\n        self.child = {} # to hold the nodes.\n        self.end = False # to mark a node if it is the end node or not.\n\nclass Trie:\n    \n    def __init__(self):\n        self.root = Node()\n\n    def insert(self, word:str) -> None:\n        # time compl len(word)\n        \n        sz = len(word) \n        temp = self.root # to hold the root node.\n        \n        for ind , i in enumerate( word ) :\n            if i in temp.child.keys() : # if this curr char in the current node.\n                temp = temp.child[i] #another node.\n                \n            else:\n                temp.child[i] = Node()\n                temp = temp.child[i]\n\n                \n            if ind  == sz - 1 :\n                temp.end = True \n                \n                \n\n    def search(self, word: str) -> bool:\n        \n        temp = self.root \n        for i in word : \n            if i in temp.child.keys():\n                temp = temp.child[i]\n            else:\n                return 0\n            \n        return temp.end == True  \n         \n    def startsWith(self, prefix: str) -> bool:\n        temp  = self.root \n        for i in prefix :\n            if i in temp.child.keys():\n                temp = temp.child[i]\n            else:\n                return 0\n        return 1 ",
        "solution_js": "var Trie = function() {\n    this.children = {};\n    this.word = false;\n};\n\n/**\n * @param {string} word\n * @return {void}\n */\nTrie.prototype.insert = function(word) {\n    if (!word) {\n        this.word = true;\n        return null;\n    }\n    let head = word[0];\n    let tail = word.substring(1);\n\n    if (!this.children[head]) {\n        this.children[head] = new Trie();\n    }\n    this.children[head].insert(tail);\n};\n\n/**\n * @param {string} word\n * @return {boolean}\n */\nTrie.prototype._search = function(word, method) {\n    if (!word) {\n        if (method === 'search') {\n            return this.word;\n        } else {\n            return true;\n        }\n    }\n    let head = word[0];\n    let tail = word.substring(1);\n\n    if (!this.children[head]) {\n        return false;\n    }\n\n    return this.children[head][method](tail);\n};\n\n/**\n * @param {string} word\n * @return {boolean}\n */\nTrie.prototype.search = function(word) {\n    return this._search(word, 'search');\n};\n\n/**\n * @param {string} prefix\n * @return {boolean}\n */\nTrie.prototype.startsWith = function(prefix) {\n    return this._search(prefix, 'startsWith');\n};\n\n/**\n * Your Trie object will be instantiated and called as such:\n * var obj = new Trie()\n * obj.insert(word)\n * var param_2 = obj.search(word)\n * var param_3 = obj.startsWith(prefix)\n */",
        "solution_java": "class Trie {\n    private class Node{\n        char character;\n        Node[] sub;\n        Node(char c){\n            this.character = c;\n            sub = new Node[26];\n        }\n    }\n    Node root;\n    HashMap<String, Boolean> map;\n    public Trie() {\n        root = new Node('\\0');\n        map = new HashMap<>();\n    }\n\n    public void insert(String word) {\n        Node temp = root;\n        for(char c : word.toCharArray()){\n            int index = c-'a';\n            if(temp.sub[index] == null)\n                temp.sub[index] = new Node(c);\n\n            temp = temp.sub[index];\n        }\n        map.put(word, true);\n    }\n\n    public boolean search(String word) {\n        return map.containsKey(word);\n    }\n\n    public boolean startsWith(String prefix) {\n        Node temp = root;\n        for(char c : prefix.toCharArray()){\n            int index = c-'a';\n            if(temp.sub[index] == null)\n                return false;\n            temp = temp.sub[index];\n        }\n        return true;\n    }\n}",
        "solution_c": "class Trie {\npublic:\n    struct tr {\n        bool isword;\n        vector<tr*> next;\n        tr() {\n            next.resize(26, NULL); // one pointer for each character\n            isword = false;\n        }\n    };\n    \n    tr *root;\n    Trie() {\n        root = new tr();\n    }\n    \n    void insert(string word) {\n        tr *cur = root;\n        \n        for(auto c: word) {\n\t\t\t// if pointer to char doesn't exist create one\n            if(cur->next[c-'a'] == NULL) {\n                cur->next[c-'a'] = new tr();\n            }\n            cur = cur->next[c-'a'];\n        }\n        \n\t\t// set as end or valid word\n        cur->isword = true;\n    }\n    \n    bool search(string word) {\n        tr *cur = root;\n        \n        for(auto c: word) {\n\t\t\t// if pointer to char doesn't exist then word is not present\n            if(cur->next[c-'a'] == NULL) {\n                return false;\n            }\n            \n            cur = cur->next[c-'a'];\n        }\n        \n\t\t// check if it is prefix or a word\n        if(cur->isword){\n            return true;\n        }\n        return false;\n    }\n    \n\t// similar to search \n\t// here we don't check if it is end or not\n    bool startsWith(string prefix) {\n        tr *cur = root;\n        \n        for(auto c: prefix) {\n            if(cur->next[c-'a'] == NULL) {\n                return false;\n            }\n            \n            cur = cur->next[c-'a'];\n        }\n\n        return true;\n    }\n};\n\n/**\n * Your Trie object will be instantiated and called as such:\n * Trie* obj = new Trie();\n * obj->insert(word);\n * bool param_2 = obj->search(word);\n * bool param_3 = obj->startsWith(prefix);\n */"
    },
    {
        "title": "Minimum Degree of a Connected Trio in a Graph",
        "algo_input": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.\n\nA connected trio is a set of three nodes where there is an edge between every pair of them.\n\nThe degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\n\nReturn the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput: 3\nExplanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n\n\nExample 2:\n\nInput: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput: 0\nExplanation: There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 400\n\tedges[i].length == 2\n\t1 &lt;= edges.length &lt;= n * (n-1) / 2\n\t1 &lt;= ui, vi &lt;= n\n\tui != vi\n\tThere are no repeated edges.\n\n",
        "solution_py": "class Solution:\n    def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n        result = n ** 2 # placeholder value\n        adj = [set() for _ in range(n + 1)]\n        visited = set()\n        for edge in edges:\n            adj[edge[0]].add(edge[1])\n            adj[edge[1]].add(edge[0])\n        for first in range(1, n + 1): # iterate through every node\n            for second in adj[first]: # iterate through every neighbor of the first node\n                e1 = tuple(sorted((first, second)))\n                if e1 in visited:\n                    continue\n                visited.add(e1) # mark e1 (first -> second) as visited because we don't want to visit (second -> first) again\n                for third in adj[second]:\n                    if third == first: # skip if the third node is the first node (we need the first node to be its neighbor rather than itself!)\n                        continue\n                    e2 = tuple(sorted((first, third)))\n                    if first in adj[third]: # we don't check if e2 is in visited because the third node is not the current node being explored\n                        visited.add(e2) # we need to mark e2 as visited because one end of e2 is the first node and if we have checked (third -> first), we don't need to check (first -> third) again\n                        degree = len(adj[first]) - 2 + len(adj[second]) - 2 + len(adj[third]) - 2\n                        result = min(result, degree)\n        return -1 if result == n ** 2 else result",
        "solution_js": "var minTrioDegree = function(n, edges) {\n    // create an adjacency list of all the edges;\n    const adjacencyList = new Array(n + 1).fill(0).map(() => new Set());\n    for (const [x, y] of edges) {\n        adjacencyList[x].add(y);\n        adjacencyList[y].add(x);\n    }\n\n    let minimumDegree = Infinity;\n\n    // Find all the combinations of 3 vertices that connect\n    // and if they connect calculate the degree\n    for (let i = 1; i <= n; i++) {\n        for (let j = i + 1; j <= n; j++) {\n            for (let k = j + 1; k <= n; k++) {\n                if (adjacencyList[i].has(j) && adjacencyList[i].has(k) && adjacencyList[j].has(k)) {\n                    // We minus 6 because we have 3 vertices and each vertices has 2 edges\n                    // going out to the 3 connecting nodes\n                    const degree = adjacencyList[i].size + adjacencyList[j].size + adjacencyList[k].size - 6;\n                    minimumDegree =\n                        Math.min(minimumDegree, degree);\n                }\n            }\n        }\n    }\n\n    return minimumDegree === Infinity ? -1 : minimumDegree;\n};",
        "solution_java": "class Solution {\npublic int minTrioDegree(int n, int[][] edges) {\n\t// to store edge information\n    boolean[][] graph = new boolean[n+1][n+1];\n\t//to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph)\n    int[] inDegree = new int[n+1];\n    \n    for(int[] edge : edges) {\n        graph[edge[0]][edge[1]] = true;\n        graph[edge[1]][edge[0]] = true;\n        \n        inDegree[edge[0]]++;\n        inDegree[edge[1]]++;\n    }\n    \n    int result = Integer.MAX_VALUE;\n    for(int i=1; i<=n; i++) {\n        for(int j=i+1; j<=n; j++) {\n            if(graph[i][j]) {\n                for(int k=j+1; k<=n; k++) {\n                    if(graph[i][k] && graph[j][k]) {\n                        result = Math.min(result, inDegree[i] + inDegree[j] + inDegree[k] - 6);\n                    }\n                }\n            }\n        }\n    }\n    \n    \n    return result == Integer.MAX_VALUE ? -1 : result;\n}\n}",
        "solution_c": "class Solution {\npublic:\n    int minTrioDegree(int n, vector<vector<int>>& edges) {\n        vector<unordered_set<int>> adj(n+1);\n        int res = INT_MAX;\n        for (vector<int>& edge : edges) {\n            adj[edge[0]].insert(edge[1]);\n            adj[edge[1]].insert(edge[0]);\n        }\n\n        for (int i = 1; i < n; ++i) {\n            for (auto iter1 = adj[i].begin(); iter1 != adj[i].end(); ++iter1) {\n                if (*iter1 <= i) continue;\n                for (auto iter2 = adj[i].begin(); iter2 != adj[i].end(); ++iter2) {\n                    int u = *iter1, v = *iter2;\n                    if (v <= u) continue;\n                    if (adj[u].count(v)) {\n                        int cur = adj[i].size() + adj[u].size() + adj[v].size() - 6;\n                        res = min(res, cur);\n                    }\n                }\n            }\n        }\n\n        return res == INT_MAX ? -1 : res;\n    }\n};"
    },
    {
        "title": "Remove Stones to Minimize the Total",
        "algo_input": "You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:\n\n\n\tChoose any piles[i] and remove floor(piles[i] / 2) stones from it.\n\n\nNotice that you can apply the operation on the same pile more than once.\n\nReturn the minimum possible total number of stones remaining after applying the k operations.\n\nfloor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).\n\n&nbsp;\nExample 1:\n\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation:&nbsp;Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\n\n\nExample 2:\n\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation:&nbsp;Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= piles.length &lt;= 105\n\t1 &lt;= piles[i] &lt;= 104\n\t1 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minStoneSum(self, piles: List[int], k: int) -> int:\n        heap = [-p for p in piles]\n        heapq.heapify(heap)\n        for _ in range(k):\n            cur = -heapq.heappop(heap)\n            heapq.heappush(heap, -(cur-cur//2))\n        return -sum(heap)            ",
        "solution_js": "/**\n * @param {number[]} piles\n * @param {number} k\n * @return {number}\n */\n\nvar minStoneSum = function(piles, k) {\n    var heapArr = [];\n    for (let i=0; i<piles.length; i++){\n        heapArr.push(piles[i]);\n        heapifyUp();\n    }\n\n    function heapifyUp(){\n        let currIndex = heapArr.length-1;\n        while (heapArr[currIndex] > heapArr[Math.floor((currIndex-1)/2)]){\n            swap(currIndex, Math.floor((currIndex-1)/2));\n            currIndex = Math.floor((currIndex-1)/2);\n        }\n    }\n    \n    function heapifyDown(){\n        let currIndex = 0;\n        let bigger = currIndex;\n        while (heapArr[currIndex*2+1]){\n            if (heapArr[currIndex] < heapArr[currIndex*2+1]){\n                bigger = currIndex * 2 + 1;\n            }\n            \n            if (heapArr[bigger] < heapArr[currIndex*2+2]){\n                bigger = currIndex * 2 + 2;\n            }\n            \n            if (bigger === currIndex){\n                break;\n            }\n            swap(currIndex, bigger);\n            currIndex = bigger;\n        }\n    }\n    \n    function swap(currIndex, otherIndex){\n        let temp = heapArr[currIndex];\n        heapArr[currIndex] = heapArr[otherIndex];\n        heapArr[otherIndex] = temp;\n    }\n    \n    while (k > 0){\n        heapArr[0] -= Math.floor(heapArr[0]/2);\n        heapifyDown();\n        k--;\n    }\n    \n    return heapArr.reduce((a,num) => a+num, 0);\n};",
        "solution_java": "class Solution {\n        public int minStoneSum(int[] A, int k) {\n        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b)->b - a);\n        int res = 0;\n        for (int a : A) {\n            pq.add(a);\n            res += a;\n        }\n        while (k-- > 0) {\n            int a = pq.poll();\n            pq.add(a - a / 2);\n            res -= a / 2;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minStoneSum(vector<int>& piles, int k) {\n        priority_queue<int> pq;\n        int sum = 0, curr;\n\n        for (auto pile : piles) {\n            pq.push(pile);\n            sum += pile;\n        }\n\n        while (k--) {\n            curr = pq.top();\n            pq.pop();\n            sum -= curr/2;\n            pq.push(curr - curr/2);\n        }\n\n        return sum;\n    }\n};"
    },
    {
        "title": "Next Greater Element II",
        "algo_input": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.\n\nThe next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,1]\nOutput: [2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,3]\nOutput: [2,3,4,-1,4]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def nextGreaterElements(self, nums: List[int]) -> List[int]:\n        t=len(nums)\n        nums+=nums\n        l=[-1]*len(nums)\n        d={}\n        stack=[0]\n        for x in range(1,len(nums)):\n            #print(x)\n            if nums[x]>nums[stack[-1]]:\n                while nums[x]>nums[stack[-1]] :\n                    l[stack[-1]]=nums[x]\n                    stack.pop()\n                    if stack==[]:\n                        break\n                    #print(l)\n                stack.append(x)\n                    \n            else:\n                stack.append(x)\n        return l[:t]\n            \n        ",
        "solution_js": "var nextGreaterElements = function(nums) {\n    const len = nums.length;\n    const ans = new Array(len).fill(-1);\n    const stack = [];\n    for(let i = 0; i < len; i++) {\n        if(i == 0) stack.push([i, nums[i]]);\n        else {\n            while(stack.length && stack.at(-1)[1] < nums[i]) {\n                ans[stack.pop()[0]] = nums[i];\n            }\n            stack.push([i, nums[i]]);\n        }\n    }\n    for(let num of nums) {\n        while(stack.length && stack.at(-1)[1] < num) {\n            ans[stack.pop()[0]] = num;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int[] nextGreaterElements(int[] nums) {\n        Stack<Integer>s=new Stack<>();\n        for(int i=nums.length-1;i>=0;i--){\n            s.push(nums[i]);\n        }\n        for(int i=nums.length-1;i>=0;i--){\n            int num=nums[i];\n            while(!s.isEmpty() && s.peek()<=nums[i]){\n                s.pop();\n            }\n            nums[i]=s.empty()?-1:s.peek();\n            s.push(num);\n        }\n        return nums;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> res;\n        \n        for(int i = 0; i < n; i++){\n            int j = i + 1;\n            if(j == n) j = 0;\n            int next = -1;\n            \n            while(j != i){\n                if(nums[j] > nums[i]){\n                    next = nums[j];\n                    break;\n                }\n                j++;\n                if(j == n) j = 0;\n            }\n            res.push_back(next);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Mean of Array After Removing Some Elements",
        "algo_input": "Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.\n\nAnswers within 10-5 of the actual answer will be considered accepted.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput: 2.00000\nExplanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\n\n\nExample 2:\n\nInput: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput: 4.00000\n\n\nExample 3:\n\nInput: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput: 4.77778\n\n\n&nbsp;\nConstraints:\n\n\n\t20 &lt;= arr.length &lt;= 1000\n\tarr.length is a multiple of 20.\n\t0 &lt;= arr[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def trimMean(self, arr: List[int]) -> float:\n        arr.sort()\n\n        return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])",
        "solution_js": "var trimMean = function(arr) {\n    arr.sort((a,b) => a - b);\n    let toDelete = arr.length / 20;\n    let sum = 0;\n    for (let i = toDelete; i < arr.length - toDelete; i++) {\n        sum += arr[i];\n    }\n    return sum / (arr.length - (2 * toDelete));\n};",
        "solution_java": "class Solution {\n    public double trimMean(int[] arr) {\n        Arrays.sort(arr);\n        int length = arr.length;\n        int toRemove = length * 5 / 100;\n        int total = 0;\n        for (int number: arr) {\n            total += number;\n        }\n        for (int i=0; i<toRemove; i++)\n            total -= arr[i];\n        for (int i=length-1; i>= length-toRemove; i--)\n            total -= arr[i];\n        length -= (2 * toRemove);\n        return (double) ((double)total / (double)length);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double trimMean(vector<int>& arr) {\n        auto first = arr.begin() + arr.size() / 20;\n        auto second = arr.end() - arr.size() / 20;\n        nth_element(arr.begin(), first, arr.end());\n        nth_element(first, second, arr.end());\n        return accumulate(first, second, 0.0) / distance(first, second);\n    }\n};"
    },
    {
        "title": "Maximum Number of Balls in a Box",
        "algo_input": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.\n\nYour job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.\n\nGiven two integers lowLimit and highLimit, return the number of balls in the box with the most balls.\n\n&nbsp;\nExample 1:\n\nInput: lowLimit = 1, highLimit = 10\nOutput: 2\nExplanation:\nBox Number:  1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count:  2 1 1 1 1 1 1 1 1 0  0  ...\nBox 1 has the most number of balls with 2 balls.\n\nExample 2:\n\nInput: lowLimit = 5, highLimit = 15\nOutput: 2\nExplanation:\nBox Number:  1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count:  1 1 1 1 2 2 1 1 1 0  0  ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.\n\n\nExample 3:\n\nInput: lowLimit = 19, highLimit = 28\nOutput: 2\nExplanation:\nBox Number:  1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count:  0 1 1 1 1 1 1 1 1 2  0  0  ...\nBox 10 has the most number of balls with 2 balls.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= lowLimit &lt;= highLimit &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def countBalls(self, lowLimit: int, highLimit: int) -> int:\n        boxes = [0] * 100\n        \n        for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number \"i\", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n            boxes[sum([int(j) for j in str(i)])] += 1\n        \n        return max(boxes)",
        "solution_js": "var countBalls = function(lowLimit, highLimit) {\n    let obj={};\n    for(let i=lowLimit; i<=highLimit; i++){\n        i+=''; let sum=0;\n        for(let j=0; j<i.length; j++){ sum+=i[j]*1; }\n        obj[sum]?obj[sum]+=1:obj[sum]=1\n    }\n    return Math.max(...Object.values(obj));\n};",
        "solution_java": "class Solution {\n    public int countBalls(int lowLimit, int highLimit) {\n        Map<Integer,Integer> map = new HashMap<>();\n        int count = Integer.MIN_VALUE;\n        for(int i = lowLimit;i<=highLimit;i++){\n            int value = 0;\n            int temp = i;\n            while (temp!=0){\n                value += temp%10;\n                temp/=10;\n            }\n            map.put(value,map.getOrDefault(value,0)+1);\n            count = map.get(value) > count ? map.get(value) : count;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countBalls(int lowLimit, int highLimit) {\n\n        vector<int> box (46,0);\n        for(int i = lowLimit;i<=highLimit;i++)\n        {\n            int sum = 0;\n            int temp = i;\n            while(temp)\n            {\n                sum = sum + temp%10;\n                temp = temp/10;\n            }\n            box[sum]++;\n        }\n\n        return *max_element(box.begin(),box.end());\n    }\n};"
    },
    {
        "title": "Check if There is a Valid Partition For The Array",
        "algo_input": "You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.\n\nWe call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:\n\n\n\tThe subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.\n\tThe subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.\n\tThe subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.\n\n\nReturn true if the array has at least one valid partition. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,4,4,5,6]\nOutput: true\nExplanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.\n\n\nExample 2:\n\nInput: nums = [1,1,1,2]\nOutput: false\nExplanation: There is no valid partition for this array.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def validPartition(self, nums: List[int]) -> bool:\n        n = len(nums)\n        \n        dp = [False] * 3\n        dp[0] = True  # An empty partition is always valid\n\n        for i in range(2, n + 1):\n            ans = False\n\n            if nums[i - 1] == nums[i - 2]:\n                ans = ans or dp[(i - 2) % 3]\n            if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]:\n                ans = ans or dp[(i - 3) % 3]\n            if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2:\n                ans = ans or dp[(i - 3) % 3]\n\n            dp[i % 3] = ans\n\n        return dp[n % 3]",
        "solution_js": "var validPartition = function(nums) {\n  let n = nums.length, memo = Array(n).fill(-1);\n  return dp(0);\n\n  function dp(i) {\n    if (i === n) return true;\n    if (i === n - 1) return false;\n    if (memo[i] !== -1) return memo[i];\n\n    if (nums[i] === nums[i + 1] && dp(i + 2)) return memo[i] = true;\n    if (i < n - 2) {\n      if (!dp(i + 3)) return memo[i] = false;\n      let hasThreeEqual = nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2];\n      let hasThreeConsecutive = nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2];\n      if (hasThreeEqual || hasThreeConsecutive) return memo[i] = true;\n    }\n    return memo[i] = false;\n  }\n};",
        "solution_java": "// Time O(n)\n// Space O(n)\nclass Solution {\n    public boolean validPartition(int[] nums) {\n        boolean[] dp = new boolean[nums.length+1];\n        dp[0]=true; // base case\n        for (int i = 2; i <= nums.length; i++){\n            dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1\n            dp[i]|= i>2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] && dp[i-3]; // cond 2\n            dp[i]|= i>2 && nums[i-1]-nums[i-2]==1 && nums[i-2]-nums[i-3]==1 && dp[i-3]; // cond 3\n        }\n        return dp[nums.length];\n    }\n}",
        "solution_c": "class Solution {\n    \npublic:\n    int solve(int i, vector<int> &nums, vector<int> &dp)\n    {\n        if (i == nums.size()) return 1;\n        if (dp[i] != -1) return dp[i];\n        \n        int ans = 0;\n        if (i+1 < nums.size() and nums[i] == nums[i+1])\n            ans = max(ans, solve(i+2, nums, dp));\n        if (i+2 < nums.size())\n        {\n            if (nums[i] == nums[i+1] && nums[i+1] == nums[i+2])\n                ans = max(ans, solve(i+3, nums, dp));\n            else if (abs(nums[i]-nums[i+1]) == 1 and abs(nums[i+1]-nums[i+2]) == 1)\n                ans = max(ans, solve(i+3, nums, dp));\n            \n        }\n        \n        return dp[i] = ans;\n    }\n    bool validPartition(vector<int>& nums) {\n        vector<int> dp(nums.size()+1, -1);\n        return solve(0, nums, dp);\n    }\n};"
    },
    {
        "title": "Number of Ways to Stay in the Same Place After Some Steps",
        "algo_input": "You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).\n\nGiven two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: steps = 3, arrLen = 2\nOutput: 4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay\n\n\nExample 2:\n\nInput: steps = 2, arrLen = 4\nOutput: 2\nExplanation: There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay\n\n\nExample 3:\n\nInput: steps = 4, arrLen = 2\nOutput: 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= steps &lt;= 500\n\t1 &lt;= arrLen &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def numWays(self, steps: int, arrLen: int) -> int:\n        \n        # obtain maximum index we can reach\n        maxLen = min(steps+1, arrLen)\n        dp = [0]*maxLen\n        dp[0] = 1\n        \n        for step in range(1, steps+1):\n            dp2 = [0]*maxLen\n            for pos in range(maxLen):\n                # dp[step][pos] = dp[step-1][pos] + dp[step-1][pos-1] + dp[step-1][pos+1] \n                temp1 = 0 if pos == 0 else dp[pos-1]\n                temp2 = 0 if pos == maxLen-1 else dp[pos+1]\n                dp2[pos] = (dp[pos] + temp1 + temp2)%(10**9+7)\n                \n            dp = dp2\n        return dp[0]",
        "solution_js": "var numWays = function(steps, arrLen) {\n  let memo = Array(steps + 1).fill(0).map(() => Array(steps + 1).fill(-1)), mod = 10 ** 9 + 7;\n  return dp(0, steps);\n  \n  function dp(i, steps) {\n    if (steps === 0) return i === 0 ? 1 : 0; // found a way\n    if (i > steps || i < 0 || i >= arrLen) return 0; // out of bounds\n    if (memo[i][steps] !== -1) return memo[i][steps]; // memoized\n    \n    let moveLeft = dp(i - 1, steps - 1);\n    let moveRight = dp(i + 1, steps - 1);\n    let stay = dp(i, steps - 1);\n    return memo[i][steps] = (moveLeft + moveRight + stay) % mod;\n  }\n};",
        "solution_java": "class Solution {\n    \n    HashMap<String,Long> map = new HashMap();\n    \n    public int numWays(int steps, int arrLen) {\n        \n        return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7));\n    }\n    \n    public long ways(int steps,int arrLen,int index){\n        String curr = index + \"->\" + steps;\n        \n        if(index == 0 && steps == 0){\n            return 1;\n        }else if(index < 0 || (index >= arrLen) || steps == 0){\n            return 0;\n        }\n        \n        if(map.containsKey(curr)){\n            return map.get(curr);\n        }\n        long stay = ways(steps-1,arrLen,index);\n        long right = ways(steps-1,arrLen,index+1);\n        long left = ways(steps-1,arrLen,index-1);\n        \n        map.put(curr , (stay+right+left) % 1000000007);\n        \n        return (right + left + stay) % 1000000007;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int n, MOD = 1e9 + 7;\n    int numWays(int steps, int arrLen) {\n        n = arrLen;\n        vector<vector<int>> memo(steps / 2 + 1, vector<int>(steps + 1, -1));\n        return dp(memo, 0, steps) % MOD;\n    }\n    long dp(vector<vector<int>>& memo, int i, int steps){\n        if(steps == 0)\n            return i == 0;\n        if(i < 0 || i == n || i > steps)\n            return 0;\n        if(memo[i][steps] != -1)\n            return memo[i][steps];\n        return memo[i][steps] = (dp(memo, i, steps - 1) + dp(memo, i - 1, steps - 1) + dp(memo, i + 1, steps - 1)) % MOD;\n    }\n};"
    },
    {
        "title": "Daily Temperatures",
        "algo_input": "Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.\n\n&nbsp;\nExample 1:\nInput: temperatures = [73,74,75,71,69,72,76,73]\nOutput: [1,1,4,2,1,1,0,0]\nExample 2:\nInput: temperatures = [30,40,50,60]\nOutput: [1,1,1,0]\nExample 3:\nInput: temperatures = [30,60,90]\nOutput: [1,1,0]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;temperatures.length &lt;= 105\n\t30 &lt;=&nbsp;temperatures[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def dailyTemperatures(self, T):\n        ans, s = [0]*len(T), deque()\n        for cur, cur_tmp in enumerate(T):\n            while s and cur_tmp > T[s[-1]]:\n                ans[s[-1]] = cur - s[-1]\n                s.pop()\n            s.append(cur)\n        return ans",
        "solution_js": "var dailyTemperatures = function(temperatures) {\n    const len = temperatures.length;\n    const res = new Array(len).fill(0);\n    const stack = [];\n    \n    for (let i = 0; i < len; i++) {\n        const temp = temperatures[i];\n        \n        while (temp > (stack[stack.length - 1] || [Infinity])[0]) {\n            const [_, j]  = stack.pop();\n            res[j] = i - j;\n        }\n        \n        stack.push([temp, i]);\n    }\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    public int[] dailyTemperatures(int[] temperatures) {\n        HashMap<Integer,Integer>hm=new HashMap<>();\n        Stack<Integer>st=new Stack<>();\n        for(int i=0;i<temperatures.length;i++){\n            while(st.size()>0&&temperatures[i]>temperatures[st.peek()]){\n                hm.put(st.pop(),i);\n            }\n            st.push(i);\n        }\n        int []ans=new int[temperatures.length];\n        for(int i=0;i<temperatures.length;i++){\n            if(hm.containsKey(i)){\n                ans[i]=hm.get(i)-i;\n            }else{\n                ans[i]=0;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> dailyTemperatures(vector<int>& temperatures) {\n        int n = temperatures.size();\n        stack<int> st;\n        vector<int> result(n, 0);\n        for(int i = 0; i<n; i++){\n            while(!st.empty() && temperatures[i]>temperatures[st.top()]){\n                result[st.top()] = i-st.top();\n                st.pop();\n            }\n            st.push(i);\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Construct Binary Tree from Preorder and Postorder Traversal",
        "algo_input": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.\n\nIf there exist multiple answers, you can return any of them.\n\n&nbsp;\nExample 1:\n\nInput: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\n\n\nExample 2:\n\nInput: preorder = [1], postorder = [1]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= preorder.length &lt;= 30\n\t1 &lt;= preorder[i] &lt;= preorder.length\n\tAll the values of preorder are unique.\n\tpostorder.length == preorder.length\n\t1 &lt;= postorder[i] &lt;= postorder.length\n\tAll the values of postorder are unique.\n\tIt is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.\n\n",
        "solution_py": "class Solution:\n    def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n\n        def build(preorder, preStart, preEnd, postorder, postStart, postEnd):\n            if preStart > preEnd:\n                return\n            elif preStart == preEnd:\n                return TreeNode(preorder[preStart])\n            \n            rootVal = preorder[preStart]\n            leftRootVal = preorder[preStart + 1]\n            index = valToIndex[leftRootVal]\n            root = TreeNode(rootVal)\n            leftSize = index - postStart + 1\n            \n            root.left = build(preorder, preStart + 1, preStart + leftSize,\npostorder, postStart, index)\n            root.right = build(preorder, preStart + leftSize + 1, preEnd,\npostorder, index + 1, postEnd - 1)\n            \n            return root\n        \n        valToIndex = {}\n        for i in range(len(postorder)):\n            valToIndex[postorder[i]] = i\n        \n        return build(preorder, 0, len(preorder) - 1, postorder, 0, len(postorder) - 1)",
        "solution_js": "var constructFromPrePost = function(preorder, postorder) {\n    let preIndex = 0\n\n    const dfs = (postArr) => {\n        if (postArr.length === 0) return null\n\n        const val = preorder[preIndex]\n        const nextVal = preorder[++preIndex]\n        const mid = postArr.indexOf(nextVal)\n\n        const root = new TreeNode(val)\n        root.left = dfs(postArr.slice(0, mid + 1))\n        root.right = dfs(postArr.slice(mid + 1, postArr.indexOf(val)))\n\n        return root\n    }\n\n    return dfs(postorder)\n};",
        "solution_java": "class Solution\n{\n    public TreeNode constructFromPrePost(int[] preorder, int[] postorder)\n    {\n        // O(n) time | O(h) space\n        if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null;\n\n        TreeNode root = new TreeNode(preorder[0]);\n        int mid = 0;\n\n        if(preorder.length == 1) return root;\n\n        // update mid\n        for(int i = 0; i < postorder.length; i++)\n        {\n            if(preorder[1] == postorder[i])\n            {\n                mid = i;\n                break;\n            }\n        }\n\n        root.left = constructFromPrePost(\n                                            Arrays.copyOfRange(preorder, 1, 1 + mid + 1),\n                                            Arrays.copyOfRange(postorder, 0, mid + 1));\n\n        root.right = constructFromPrePost(\n                                            Arrays.copyOfRange(preorder, 1 + mid + 1, preorder.length),\n                                            Arrays.copyOfRange(postorder, mid + 1, postorder.length - 1));\n        return root;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    bool vis[40];\n    \n    TreeNode* solve(vector<int>& pre,int p, vector<int>& pos,int q){\n        TreeNode* root=new TreeNode(pre[p]);\n        vis[pre[p]]=true;\n        p++;\n        q--;\n        \n        if(p>=pre.size() || q<0){\n            return root;\n        }\n        if(!vis[pre[p]]){\n            \n            int x=q;\n            while(x>0 and pos[x]!=pre[p])x--;\n            if(pos[x]==pre[p]){\n                root->left=solve(pre,p,pos,x);\n            }\n            \n        }\n        if(!vis[pos[q]]){\n            int x=p;\n            while(x<pre.size()-1 and pos[q]!=pre[x])x++;\n            if(pos[q]==pre[x]){\n                root->right=solve(pre,x,pos,q);\n            }\n        }\n        return root;\n    }\n        \n    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {\n        int n=postorder.size();\n        return solve(preorder,0,postorder,n-1);\n    }\n};"
    },
    {
        "title": "Destination City",
        "algo_input": "You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.\n\nIt is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.\n\n&nbsp;\nExample 1:\n\nInput: paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput: \"Sao Paulo\" \nExplanation: Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -&gt; \"New York\" -&gt; \"Lima\" -&gt; \"Sao Paulo\".\n\n\nExample 2:\n\nInput: paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput: \"A\"\nExplanation: All possible trips are:&nbsp;\n\"D\" -&gt; \"B\" -&gt; \"C\" -&gt; \"A\".&nbsp;\n\"B\" -&gt; \"C\" -&gt; \"A\".&nbsp;\n\"C\" -&gt; \"A\".&nbsp;\n\"A\".&nbsp;\nClearly the destination city is \"A\".\n\n\nExample 3:\n\nInput: paths = [[\"A\",\"Z\"]]\nOutput: \"Z\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= paths.length &lt;= 100\n\tpaths[i].length == 2\n\t1 &lt;= cityAi.length, cityBi.length &lt;= 10\n\tcityAi != cityBi\n\tAll strings consist of lowercase and uppercase English letters and the space character.\n\n",
        "solution_py": "from collections import defaultdict\nclass Solution:\n    def destCity(self, paths: List[List[str]]) -> str:\n        deg = defaultdict(int)\n        for v, w in paths:\n            deg[v] += 1\n            deg[w]\n        for v in deg:\n            if not deg[v]: return v",
        "solution_js": " * @param {string[][]} paths\n * @return {string}\n */\nvar destCity = function(paths) {\n    \n    \n    let map={}\n    \n    for(let city of paths){\n        map[city[0]]=map[city[0]]?map[city[0]]+1:1\n    }\n    for(let city of paths){\n        if(!map[city[1]]) return city[1]\n    }\n};```",
        "solution_java": "class Solution {\n    public String destCity(List<List<String>> paths) {\n        HashSet<String> set1 = new HashSet<>();\n\n        for (int i = 0; i < paths.size(); ++i) {\n            set1.add(paths.get(i).get(0));\n        }\n        for (int i = 0; i < paths.size(); ++i) {\n            if (!set1.contains(paths.get(i).get(1))) return paths.get(i).get(1);\n        }\n        return \"placeholder\";\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string destCity(vector<vector<string>>& paths) {\n        string ans;\n        unordered_map<string, int> m;\n        for(int i=0; i<paths.size(); i++){\n            m[paths[i][0]]++;\n            m[paths[i][1]]--;\n        }\n        for(auto city : m){\n            if(city.second == -1) ans = city.first;\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Number of Increments on Subarrays to Form a Target Array",
        "algo_input": "You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.\n\nIn one operation you can choose any subarray from initial and increment each value by one.\n\nReturn the minimum number of operations to form a target array from initial.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: target = [1,2,3,2,1]\nOutput: 3\nExplanation: We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.\n\n\nExample 2:\n\nInput: target = [3,1,1,2]\nOutput: 4\nExplanation: [0,0,0,0] -&gt; [1,1,1,1] -&gt; [1,1,1,2] -&gt; [2,1,1,2] -&gt; [3,1,1,2]\n\n\nExample 3:\n\nInput: target = [3,1,5,4,2]\nOutput: 7\nExplanation: [0,0,0,0,0] -&gt; [1,1,1,1,1] -&gt; [2,1,1,1,1] -&gt; [3,1,1,1,1] -&gt; [3,1,2,2,2] -&gt; [3,1,3,3,2] -&gt; [3,1,4,4,2] -&gt; [3,1,5,4,2].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target.length &lt;= 105\n\t1 &lt;= target[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minNumberOperations(self, nums: List[int]) -> int:\n        res=nums[0]\n        prev=nums[0]\n        for i in range(1,len(nums)):\n            res += max(0,nums[i]-prev)\n            prev=nums[i]\n        return res",
        "solution_js": "var minNumberOperations = function(target) {\n    let res = target[0];\n    for(let g=1; g<target.length; g++){\n        if(target[g] > target[g-1]){\n            res = res + (target[g] - target[g-1]);\n        }\n        // for target[g] < target[g-1] we need not worry as its already been taken care by previous iterations\n    }\n    return res;\n};",
        "solution_java": "// Imagine 3 cases\n// Case 1. [3,2,1], we need 3 operations.\n// Case 2. [1,2,3], we need 3 operations.\n// Case 3. [3,2,1,2,3], we need 5 operations.\n// What we need to add is actually the diff (cur - prev)\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n    public int minNumberOperations(int[] target) {\n        int res = 0;\n        int prev = 0;\n        for (int cur : target) {\n            if (cur > prev) {\n                res += cur - prev;\n            }\n            prev = cur;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minNumberOperations(vector<int>& target) {\n        int n=target.size();\n        int pre=0, cnt=0;\n        for(int i=0;i<n;i++)\n        {\n            if(target[i]>pre)\n            cnt+=target[i]-pre;\n            pre=target[i];\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Open the Lock",
        "algo_input": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.\n\nThe lock initially starts at '0000', a string representing the state of the 4 wheels.\n\nYou are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.\n\nGiven a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.\n\n&nbsp;\nExample 1:\n\nInput: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput: 6\nExplanation: \nA sequence of valid moves would be \"0000\" -&gt; \"1000\" -&gt; \"1100\" -&gt; \"1200\" -&gt; \"1201\" -&gt; \"1202\" -&gt; \"0202\".\nNote that a sequence like \"0000\" -&gt; \"0001\" -&gt; \"0002\" -&gt; \"0102\" -&gt; \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".\n\n\nExample 2:\n\nInput: deadends = [\"8888\"], target = \"0009\"\nOutput: 1\nExplanation: We can turn the last wheel in reverse to move from \"0000\" -&gt; \"0009\".\n\n\nExample 3:\n\nInput: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput: -1\nExplanation: We cannot reach the target without getting stuck.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= deadends.length &lt;= 500\n\tdeadends[i].length == 4\n\ttarget.length == 4\n\ttarget will not be in the list deadends.\n\ttarget and deadends[i] consist of digits only.\n\n",
        "solution_py": "class Solution:\n    def openLock(self, deadends: List[str], target: str) -> int:\n        def neighbor(s):\n            res = []\n            for i, c in enumerate(s):\n                res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:])\n                res.append(s[:i] + chr((ord(c) - ord('0') + 1) % 10 + ord('0')) + s[i + 1:])\n            return res\n        \n        deadends = set(deadends)\n        if \"0000\" in deadends:\n            return -1\n        ans = 0\n        queue = deque([\"0000\"])\n        vis = set()\n        while queue:\n            l = len(queue)\n            for _ in range(l):\n                cur = queue.popleft()\n                if cur == target:\n                    return ans\n                for nxt in neighbor(cur):\n                    if nxt not in vis and nxt not in deadends:\n                        queue.append(nxt)\n                        vis.add(nxt)\n            ans += 1\n        return -1",
        "solution_js": "var openLock = function(deadends, target) {\n    if(deadends.includes('0000')) {\n        return -1\n    }\n    // treat deadends like visited\n    // if a number is in visited/deadends, simply ignore it\n    const visited = new Set(deadends)\n    \n    \n    const queue = [['0000', 0]];\n    visited.add('0000')\n\n    while(queue.length) {\n        const [cur, count] = queue.shift()\n        if(cur === target) {\n            return count\n        }\n        \n        // each number will create 8 more different paths to check\n        \n        // e.g. if cur = 0000. 8 next/prev numbers to check are\n        // 1000, 9000, 0100, 0900, 0010, 0090, 0001, 0009\n        for(let i=0; i<4; i++) {\n            const c = cur[i]\n           \n            let up = Number(c) + 1;\n            let down = Number(c) - 1;\n            // if up is 9, then up + 1 = 10 -> set it  to 0\n            if(up === 10) {\n                up = '0';\n            }\n            // if down is 0. then down - 1 = -1 -> set to 9\n            if(down === -1) {\n                down = '9'\n            }\n            \n            const next =  cur.substring(0, i) + up  + cur.substring(i+1)\n            const prev =  cur.substring(0, i) + down + cur.substring(i + 1)\n            \n            // if not visited, push to queue\n            if(!visited.has(next)) {\n                visited.add(next)\n                queue.push([next, count + 1])   \n            }\n\n            if(!visited.has(prev)) {\n                visited.add(prev)\n                queue.push([prev, count + 1])   \n            }\n        }\n    }\n    \n    return -1;\n};",
        "solution_java": "class Solution {\n    public int openLock(String[] deadends, String target) {\n// Converted target to Integer type.\n        int t = Integer.parseInt(target);\n        HashSet<Integer> visited = new HashSet<>();\n\n// Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited.\n        for(String str: deadends){\n            visited.add(Integer.parseInt(str));\n        }\n// BFS\n        Queue<Integer> q = new ArrayDeque<>();\n// We make sure that 0 itself isn't a deadend\n        if(visited.contains(0)){\n            return -1;\n        }\n        q.add(0);\n        visited.add(0);\n        int level = 0;\n        while(q.size() > 0){\n            int size = q.size();\n            while(size-->0){\n                int elem = q.remove();\n                if(t == elem){\n                    return level;\n                }\n// Will help check 4 digits of the element. From digit with low precendence(ones place) to high precedence(thousands place)\n                for(int i = 1; i < 10000; i= i*10){\n// The wheel can be rotated in two directions. Hence two numbers.\n                    int num1;\n                    int num2;\n// The wheel at 0 can become 1 or 9 due to wrapping.\n                    if(elem / i % 10 == 0){\n                        num1=elem + i;\n                        num2 = elem+ i * 9;\n                    }\n// The wheel at 9 can become 0 or 8 due to wrapping.\n                    else if(elem / i % 10 == 9){\n                        num1 = elem - i * 9;\n                        num2 = elem -i;\n                    }\n                    else{\n                        num1 = elem -i;\n                        num2 = elem + i;\n                    }\n// Checking if numbers have already been visited.\n                    if(!(visited.contains(num1))){\n                            visited.add(num1);\n                            q.add(num1);\n                        }\n                    if(!(visited.contains(num2))){\n                        visited.add(num2);\n                        q.add(num2);\n                    }\n                }\n            }\n            level++;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void setPermutations(const string& s, queue<pair<string, int>>& q, int count) {\n        for (int i=0; i<4; i++) {\n            int j = s[i]-'0';\n            char b = (10+j-1)%10 + '0', n = (10+j+1)%10 + '0';\n            auto tmp = s; tmp[i]=b;\n            q.push({tmp, count+1});\n            tmp = s; tmp[i]=n;\n            q.push({tmp, count+1});\n        }\n    }\n    int openLock(vector<string>& deadends, string target) {\n        unordered_set<string> deadies(deadends.begin(), deadends.end());\n        queue<pair<string, int>> q({{\"0000\", 0}});\n        while (!q.empty()) {\n            auto t = q.front();\n            q.pop();\n            if (deadies.count(t.first))\n                continue;\n            if (t.first==target)\n                return t.second;\n            deadies.insert(t.first);\n            setPermutations(t.first, q, t.second);\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Three Consecutive Odds",
        "algo_input": "Given an integer array arr, return true&nbsp;if there are three consecutive odd numbers in the array. Otherwise, return&nbsp;false.\n&nbsp;\nExample 1:\n\nInput: arr = [2,6,4,1]\nOutput: false\nExplanation: There are no three consecutive odds.\n\n\nExample 2:\n\nInput: arr = [1,2,34,3,4,5,7,23,12]\nOutput: true\nExplanation: [5,7,23] are three consecutive odds.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 1000\n\t1 &lt;= arr[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n        c=0\n        for i in arr:\n            if i%2==0:\n                c=0\n            else:\n                c+=1\n                if c==3:\n                    return True\n        return False",
        "solution_js": "var threeConsecutiveOdds = function(arr) {\n    let c = 0;\n\n    for(let val of arr){\n        if(val % 2 === 1){\n            c++;\n            if(c === 3) {\n                return true;\n            }\n        } else {\n            c=0;\n        }\n    }\n\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean threeConsecutiveOdds(int[] arr) {\n        int count = 0,n = arr.length;\n        for(int i=0;i<n;i++)\n        {\n            if((arr[i] & 1) > 0)\n            {\n                count++;\n                if(count == 3) return true;\n            }\n            else\n            {\n                count = 0;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool threeConsecutiveOdds(vector<int>& arr) {\n        int k = 0;\n        for(int i=0;i<arr.size();i++){\n            if(arr[i] % 2 != 0){\n                k++;\n                if(k == 3){\n                    return true;\n                }\n            }else{\n                k = 0;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Count All Possible Routes",
        "algo_input": "You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.\n\nAt each step, if you are at city i, you can pick any city j such that j != i and 0 &lt;= j &lt; locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.\n\nNotice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).\n\nReturn the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\nOutput: 4\nExplanation: The following are all possible routes, each uses 5 units of fuel:\n1 -&gt; 3\n1 -&gt; 2 -&gt; 3\n1 -&gt; 4 -&gt; 3\n1 -&gt; 4 -&gt; 2 -&gt; 3\n\n\nExample 2:\n\nInput: locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput: 5\nExplanation: The following are all possible routes:\n1 -&gt; 0, used fuel = 1\n1 -&gt; 2 -&gt; 0, used fuel = 5\n1 -&gt; 2 -&gt; 1 -&gt; 0, used fuel = 5\n1 -&gt; 0 -&gt; 1 -&gt; 0, used fuel = 3\n1 -&gt; 0 -&gt; 1 -&gt; 0 -&gt; 1 -&gt; 0, used fuel = 5\n\n\nExample 3:\n\nInput: locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput: 0\nExplanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= locations.length &lt;= 100\n\t1 &lt;= locations[i] &lt;= 109\n\tAll integers in locations are distinct.\n\t0 &lt;= start, finish &lt; locations.length\n\t1 &lt;= fuel &lt;= 200\n\n",
        "solution_py": "from bisect import bisect_left\nfrom functools import lru_cache\nclass Solution:\n    def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n        start = locations[start]\n        end = locations[finish]\n        locations.sort()\n        start = bisect_left(locations, start)\n        end = bisect_left(locations, end)\n        @lru_cache(None)\n        def dfs(i, fuel):\n            if fuel == 0 and i == end: return 1\n            res = 0\n            if i == end: res += 1\n            j = i-1\n            while j>=0 and abs(locations[j]-locations[i]) <= fuel:\n                res += dfs(j, fuel-abs(locations[j]-locations[i]))\n                j -= 1\n            j = i+1\n            while j<len(locations) and abs(locations[j]-locations[i]) <= fuel:\n                res += dfs(j, fuel-abs(locations[j]-locations[i]))\n                j += 1\n            return res\n        return dfs(start, fuel) % (10**9+7)",
        "solution_js": "var countRoutes = function(locations, start, finish, fuel) {\n    const memo = new Array(locations.length+1).fill(0).map(()=>new Array(201).fill(-1));\n    \n    const dfs = function(cur, f){\n        if(f<0) return 0;\n        if(memo[cur][f]!=-1) return memo[cur][f];\n        let res = (cur==finish);\n        for(let i in locations){\n            if(i==cur) continue;\n            res = (res + dfs(i, f-Math.abs(locations[i]-locations[cur])))%1000000007;\n        }\n        return memo[cur][f]=res;\n    }\n    \n    return dfs(start, fuel);\n};",
        "solution_java": "/*\n\nUsing DFS and Memo :\n\n1. We will start from start pos provided and will dfs travel to each other location .\n2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling\n3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path\n4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing .\n\n*/\n\nclass Solution {\n\n    int mod = (int)Math.pow(10,9) + 7 ;\n    int[][] dp ;\n\n    public int countRoutes(int[] locations, int start, int finish, int fuel) {\n\n        dp = new int[locations.length][fuel+1] ;\n\n        for(int[] row : dp){\n            Arrays.fill(row , -1) ;\n        }\n\n        return dfs(locations , start , finish , fuel);\n    }\n\n    public int dfs(int[] locations , int cur_location , int finish , int fuel){\n\n        if(fuel < 0){\n            return 0 ;\n        }\n\n        if(dp[cur_location][fuel] != -1){\n            return dp[cur_location][fuel] ;\n        }\n\n        int result = 0 ;\n\n        if(cur_location == finish){\n            result++ ;\n        }\n\n        for(int i=0 ; i<locations.length ; i++){\n\n            if(i == cur_location) continue ;\n\n            int fuel_cost = Math.abs(locations[i] - locations[cur_location]);\n            int next_trip = dfs(locations , i , finish , fuel-fuel_cost);\n            result += next_trip ;\n            result %= mod ;\n        }\n\n        dp[cur_location][fuel] = result ;\n\n        return dp[cur_location][fuel] ;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int fun(vector<int> &arr , int s , int f , int k , vector<vector<int>> &dp){\n        if(k<0) return 0 ;\n        if(dp[s][k]!=-1) return dp[s][k] ;\n        int ans=0 ;\n        if(s==f) ans=1 ;\n        for(int i=0 ; i<arr.size() ; i++){\n            if(i!=s) ans=(ans+fun(arr,i,f,k-abs(arr[s]-arr[i]),dp))%1000000007;\n        }\n     return dp[s][k]=ans ;   \n    }\n    \n    int countRoutes(vector<int>& locations, int start, int finish, int fuel) {\n        vector<vector<int>> dp(locations.size()+1,vector<int>(fuel+1,-1)) ;\n        int ans=fun(locations,start,finish,fuel,dp) ;\n        return ans ;\n    }\n};"
    },
    {
        "title": "Minimum Falling Path Sum II",
        "algo_input": "Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.\n\nA falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.\n\n&nbsp;\nExample 1:\n\nInput: arr = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is&nbsp;[1,5,7], so the answer is&nbsp;13.\n\n\nExample 2:\n\nInput: grid = [[7]]\nOutput: 7\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 200\n\t-99 &lt;= grid[i][j] &lt;= 99\n\n",
        "solution_py": "class Solution:\n    def minFallingPathSum(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        if m == 1 and n == 1:\n            return grid[0][0]\n        min_arr = [0 for _ in range(n)]\n        for i in range(m):\n            prefix = [float('inf') for _ in range(n)]\n            suffix = [float('inf') for _ in range(n)]\n            current_row = [elem1+elem2 for elem1, elem2 in zip(grid[i], min_arr)]\n            for i in range(1, n):\n                prefix[i] = min(prefix[i-1], current_row[i-1])\n            for i in range(n-2, -1, -1):\n                suffix[i] = min(suffix[i+1], current_row[i+1])\n            min_arr = [min(pre, suff) for pre, suff in zip(prefix, suffix)]\n        return min(min_arr)",
        "solution_js": "var minFallingPathSum = function(grid) {\nif(grid.length===1){\n    return grid[0][0];\n}\nlet sums = [];//find first, second and third minimum values in the grid as these are only possible values for path\n//store the index for fast lookup in a 3D array\nfor(let i=0; i<grid.length; i++){\n    let min = Math.min(...grid[i]);\n    let idx = grid[i].indexOf(min);\n    grid[i].splice(idx, 1, Infinity);\n    let min2 = Math.min(...grid[i]);\n    let idx2 = grid[i].indexOf(min2);\n    grid[i].splice(idx2, 1, Infinity);\n    let min3 = Math.min(...grid[i]);\n    let idx3 = grid[i].indexOf(min3);\n    sums.push([[min,idx],[min2,idx2],[min3,idx3]]);\n}\n// sums contains 1st , 2nd and 3rd min value and index\nlet memo = {}; // for memoization\nlet recur = (r,li) => {//recursive call to decide which path to choose from r=row, li=lastIndex\n    if(memo[r+','+li] !== undefined){// memoized\n        return memo[r+','+li];\n    }\n    if(r===grid.length-1){// last and first choice for path can only be from 1st and 2nd minimum, as there is only one other row to occupy these columns\n        if(li===sums[r][0][1]){\n            memo[r+','+li] = sums[r][1][0];\n        }\n        else{\n            memo[r+','+li] = sums[r][0][0];\n        }\n        return memo[r+','+li];\n    }\n    else{\n        switch (li) {// pick the minimum value path where index is not equal to last index\n            case sums[r][0][1]:\n                memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n                break;\n            case sums[r][1][1]:\n                memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n                break;\n            case sums[r][2][1]:\n                memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][0][0]+recur(r+1,sums[r][0][1]));\n                break;\n            default:\n                memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n        }\n        return memo[r+','+li];\n    }\n}\nreturn recur(0,sums[0][2][1]);//since first and last can only be picked from 1st and 2nd min values\n};",
        "solution_java": "class Solution {\n    // Recursion\n   /* public int minFallingPathSum(int[][] grid) {\n        int n=grid.length;\n        if(n==1) return grid[0][0];\n        int ans = 10000000;\n        for(int i=0 ; i<n ; i++){\n            ans = Math.min(ans , grid[0][i] + helper(grid , n , 1 , i));\n        }\n        return ans;\n    }\n    \n    private int helper(int[][] grid , int n , int i , int last){\n        if( i == n-1 ){\n            int min = 100;\n            for(int k=0 ; k<n ; k++){\n                if(k!=last){\n                    min = Math.min( grid[n-1][k] , min);\n                }\n            }\n            return min;\n        }\n        \n        int min = 100000000;\n        for(int k=0 ; k<n ; k++){\n            if(k != last){\n                min = Math.min( min ,grid[i][k] +  helper(grid , n , i+1 , k) );\n            }\n        }\n        \n        return min;\n    }\n    */\n    \n    // DP MEMOIZATION\n    public int minFallingPathSum(int[][] grid) {\n        int n=grid.length;\n        if(n==1) return grid[0][0];\n        int[][] dp = new int[n][n];\n        for(int i=0 ; i<n ; i++){\n            for(int j=0 ; j<n ; j++){\n                dp[i][j] = -1;\n            }\n        }\n        \n        int ans = 10000000;\n        for(int i=0 ; i<n ; i++){\n            ans = Math.min(ans , grid[0][i] + helper(grid , n , 1 , i , dp));\n        }\n        return ans;\n    }\n    \n    private int helper(int[][] grid , int n , int i , int last , int[][] dp){\n        if( i == n-1 ){\n            int min = 100;\n            for(int k=0 ; k<n ; k++){\n                if(k!=last){\n                    min = Math.min( grid[n-1][k] , min);\n                }\n            }\n            return min;\n        }\n        if(dp[i][last] != -1) return dp[i][last];\n        int min = 100000000;\n        for(int k=0 ; k<n ; k++){\n            if(k != last){\n                min = Math.min( min ,grid[i][k] +  helper(grid , n , i+1 , k , dp) );\n            }\n        }\n        \n        dp[i][last] = min;\n        return dp[i][last];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int f(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &dp){\n\n        //to handle edge cases if the j index is less than 0 or greater than size of the array.\n        if(j<0 or j>=matrix[0].size()) return 1e8;\n\n        //base case\n        if(i==0) return dp[0][j] = matrix[0][j];\n\n        if(dp[i][j]!=-1) return dp[i][j];\n\n        int ans = INT_MAX;\n\n         //Here we have to iterate through all the possiblities in the entire upper row for each\n         //element except for the element which is directly above the current element in the\n         //matrix, and then we have to find the minimum.\n        for(int k=0;k<matrix[0].size();k++){\n            if(k==j) continue;\n            ans = min(ans, matrix[i][j] + f(i-1, k, matrix, dp));\n        }\n\n        return dp[i][j] = ans;\n\n    }\n\n    int minFallingPathSum(vector<vector<int>>& grid) {\n\n        int mini = INT_MAX;\n        int n = grid.size();\n\n        vector<vector<int>> dp(n, vector<int>(n,-1));\n\n        for(int j=0;j<n;j++){\n\n            mini = min(mini, f(n-1, j, grid, dp));\n\n        }\n\n        return mini;\n\n    }\n};"
    },
    {
        "title": "Largest 3-Same-Digit Number in String",
        "algo_input": "You are given a string num representing a large integer. An integer is good if it meets the following conditions:\n\n\n\tIt is a substring of num with length 3.\n\tIt consists of only one unique digit.\n\n\nReturn the maximum good integer as a string or an empty string \"\" if no such integer exists.\n\nNote:\n\n\n\tA substring is a contiguous sequence of characters within a string.\n\tThere may be leading zeroes in num or a good integer.\n\n\n&nbsp;\nExample 1:\n\nInput: num = \"6777133339\"\nOutput: \"777\"\nExplanation: There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".\n\n\nExample 2:\n\nInput: num = \"2300019\"\nOutput: \"000\"\nExplanation: \"000\" is the only good integer.\n\n\nExample 3:\n\nInput: num = \"42352338\"\nOutput: \"\"\nExplanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= num.length &lt;= 1000\n\tnum only consists of digits.\n\n",
        "solution_py": "class Solution:\n    def largestGoodInteger(self, n: str) -> str:\n        return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else \"\" for i in range(2, len(n)))",
        "solution_js": "var largestGoodInteger = function(num) {\n    let maxGoodInt = '';\n    for (let i = 0; i <= num.length - 3; i++) {\n        if (num[i] === num[i+1] && num[i+1] === num[i+2]) {\n            if (num[i] >= maxGoodInt) {\n                maxGoodInt = num[i];\n            }\n        }\n    }\n    return maxGoodInt + maxGoodInt + maxGoodInt;\n};",
        "solution_java": "class Solution\n{\n    public String largestGoodInteger(String num)\n    {\n        String ans = \"\";\n        for(int i = 2; i < num.length(); i++)\n            if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2))\n                if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is larger\n                    ans = num.substring(i-2,i+1);\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string largestGoodInteger(string num) {\n        string ans = \"\";\n        for(int i=1; i<num.size()-1; i++) {\n            if(num[i-1] == num[i] && num[i] == num[i+1]) {\n\t\t\t\tstring temp = {num[i-1], num[i], num[i+1]};\n                ans = max(ans, temp);\n            }\n        }\n        return ans;    \n    }\n};"
    },
    {
        "title": "Find the Longest Valid Obstacle Course at Each Position",
        "algo_input": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.\n\nFor every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:\n\n\n\tYou choose any number of obstacles between 0 and i inclusive.\n\tYou must include the ith obstacle in the course.\n\tYou must put the chosen obstacles in the same order as they appear in obstacles.\n\tEvery obstacle (except the first) is taller than or the same height as the obstacle immediately before it.\n\n\nReturn an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.\n\n&nbsp;\nExample 1:\n\nInput: obstacles = [1,2,3,2]\nOutput: [1,2,3,3]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.\n\n\nExample 2:\n\nInput: obstacles = [2,2,1]\nOutput: [1,2,1]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.\n\n\nExample 3:\n\nInput: obstacles = [3,1,5,6,4,2]\nOutput: [1,1,2,3,2,2]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == obstacles.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= obstacles[i] &lt;= 107\n\n",
        "solution_py": "from bisect import bisect_right\nclass Solution:\n    def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n        longest, res = [], []\n        for i in range(len(obstacles)):\n            idx = bisect_right(longest, obstacles[i])\n            if idx == len(longest):\n                longest.append(obstacles[i])\n            else:\n                longest[idx] = obstacles[i]\n            res.append(idx+1)\n        return res",
        "solution_js": "var longestObstacleCourseAtEachPosition = function(obstacles) {\n    var n = obstacles.length;\n    var lis = [];\n    var res = new Array(n).fill(0);\n    for(var i = 0; i<n; i++)\n    {\n        if(lis.length>0 && obstacles[i] >= lis[lis.length-1])\n        {\n            lis.push(obstacles[i]);\n            res[i] = lis.length;\n        }\n        else\n        {\n            // find the upper bound\n            var l = 0;\n            var r = lis.length;\n            while(l<=r)\n            {\n                var mid = Math.floor((l+r)/2);\n                if(lis[mid]<=obstacles[i])\n                {\n                    l = mid+1;\n                }\n                else\n                {\n                    r = mid-1;\n                }\n            }\n            lis[l] = obstacles[i];\n            res[i] = l+1;\n        }\n    }\n    return res;\n}",
        "solution_java": "class Solution {\n    public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {\n        int i = -1, cur = 0, lisSize = -1;\n        int[] lis = new int[obstacles.length];\n        int[] ans = new int[obstacles.length];\n        \n        for (int curHeight: obstacles) {\n            if (i == -1 || lis[i] <= curHeight) {\n                lis[++i] = curHeight;\n                lisSize = i;\n            } else {\n                lisSize = search(lis, 0, i, curHeight);\n                lis[lisSize] = curHeight;\n            }\n            \n            ans[cur++] = lisSize + 1;\n        }\n        \n        return ans;      \n    }\n    \n    private int search(int[] nums, int start, int end, int target) {\n        int left = start, right = end;\n        int boundary = 0;\n        while (left <= right) {\n            int mid = left + (right - left) / 2;\n            if (nums[mid] > target) {\n                boundary = mid;\n                right = mid - 1;\n            } else left = mid + 1;\n        }\n        return boundary;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\t// ranking each element to make segment tree of small size\n    void compress(vector<int>& a){\n        vector<int> b=a;\n        sort(b.begin(),b.end());\n        map<int,int> mp;\n        int prev=b[0],rnk=0,n=a.size();\n        for(int i=0;i<n;i++){\n            if(b[i]!=prev){\n                prev=b[i];\n                rnk++;\n            }\n            mp[b[i]]=rnk;\n        }\n        for(int i=0;i<n;i++)\n            a[i]=mp[a[i]];\n    }\n    \n    void update(int st[],int tind,int ind,int val,int tl,int tr){\n        if(tl>tr)\n            return;\n        if(tl==tr){\n            st[tind]=val;\n            return;\n        }\n        int m=tl+(tr-tl)/2,left=tind<<1;\n        if(ind<=m)\n            update(st,left,ind,val,tl,m);\n        else\n            update(st,left+1,ind,val,m+1,tr);\n        st[tind]=max(st[left],st[left+1]);\n    }\n    \n    int query(int st[],int tind,int tl,int tr,int ql,int qr){\n        if(tl>tr or ql>tr or qr<tl)\n            return 0;\n        if(ql<=tl and tr<=qr)\n            return st[tind];\n        int m=tl+(tr-tl)/2,left=tind<<1;\n        return max(query(st,left,tl,m,ql,qr),query(st,left+1,m+1,tr,ql,qr));\n    }\n\n    vector<int> longestObstacleCourseAtEachPosition(vector<int>& a) {\n        compress(a);\n        int i,n=a.size();\n        int st[4*n+10];\n        memset(st,0,sizeof(st));\n        update(st,1,a[0],1,0,n-1);\n        vector<int> dp(n);\n        dp[0]=1;\n        \n        for(i=1;i<n;i++){\n            int mx=query(st,1,0,n-1,0,a[i]);\n            dp[i]=1+mx;\n            update(st,1,a[i],dp[i],0,n-1);\n        }\n        \n        return dp;\n    }\n};"
    },
    {
        "title": "Binary Gap",
        "algo_input": "Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.\n\nTwo 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in \"1001\" have a distance of 3.\n\n&nbsp;\nExample 1:\n\nInput: n = 22\nOutput: 2\nExplanation: 22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.\n\n\nExample 2:\n\nInput: n = 8\nOutput: 0\nExplanation: 8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.\n\n\nExample 3:\n\nInput: n = 5\nOutput: 2\nExplanation: 5 in binary is \"101\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def binaryGap(self, n: int) -> int:\n        prev = 0\n        res = 0\n        for i, d in enumerate(bin(n)[3:]):\n            if d == \"1\":\n                res = max(res, i-prev+1)\n                prev = i + 1\n        return res",
        "solution_js": "var binaryGap = function(n) {\n    var str = (n >>> 0).toString(2), start = 0, end = 0, diff = 0;\n    for(var i=0;i<str.length;i++) {\n    \tif(str[i] === '1') {\n      \tend = i;\n        diff = Math.max(diff, end - start);\n        start = i;\n      } \n    }\n    return diff;\n};",
        "solution_java": "class Solution {\n    public int binaryGap(int n) {\n      char[] arr = Integer.toBinaryString(n).toCharArray();\n        List<Integer> ans = new ArrayList();\n        for(int i = 0; i < arr.length ; i++){\n            if(arr[i] == '1')\n                ans.add(i);\n        }\n        int res = 0;\n        for ( int i = 0 ; i < ans.size() -1 ; i++){\n            res =Math.max(res,ans.get(i+1) - ans.get(i));\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int binaryGap(int n) {\n        int res=0;\n        int s=0,i=0;\n        while(n){\n            if(n&1){\n                s=i;break;\n            }\n            i++;\n            n=n>>1;\n        }\n        while(n){\n            if(n&1){\n                res=max(res,(i-s));\n                s=i;\n            }\n            i++;\n            n=n>>1;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "K Divisible Elements Subarrays",
        "algo_input": "Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p.\n\nTwo arrays nums1 and nums2 are said to be distinct if:\n\n\n\tThey are of different lengths, or\n\tThere exists at least one index i where nums1[i] != nums2[i].\n\n\nA subarray is defined as a non-empty contiguous sequence of elements in an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,3,2,2], k = 2, p = 2\nOutput: 11\nExplanation:\nThe elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4], k = 4, p = 1\nOutput: 10\nExplanation:\nAll element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t1 &lt;= nums[i], p &lt;= 200\n\t1 &lt;= k &lt;= nums.length\n\n\n&nbsp;\nFollow up:\n\nCan you solve this problem in O(n2) time complexity?\n",
        "solution_py": "class Solution:\n    def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n        n = len(nums)                        \n        sub_arrays = set()\n        \n\t\t# generate all combinations of subarray\n        for start in range(n):\n            cnt = 0\n            temp = ''\n            for i in range(start, n):\n                if nums[i]%p == 0:\n                    cnt+=1                 \n                temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format          \n                if cnt>k: # check for termination \n                    break\n                sub_arrays.add(temp)                                    \n                \n        return len(sub_arrays)",
        "solution_js": "var countDistinct = function(nums, k, p) {\n    let ans = [];\n\n    let rec = (index,k,p,nums,ans,curr) => {\n        let val = nums[index];\n        let check = val%p;\n        let isdiv = false;\n        if(check == 0) isdiv=true;\n\n        if(index == nums.length) {\n            if(curr.length>0){\n                ans.push(curr.join(\",\"));\n            }\n            return;\n        }\n\n        //take conditions\n        if(isdiv && k==0){\n          ans.push(curr.join(\",\"));\n        } else if(isdiv){\n             curr.push(val)\n             rec(index+1,k-1,p,nums,ans,curr);\n             curr.pop()\n        } else {\n             curr.push(val)\n             rec(index+1,k,p,nums,ans,curr);\n             curr.pop()\n        }\n\n        //non take conditions\n        if(curr.length == 0){\n             rec(index+1,k,p,nums,ans,curr);\n        } else {\n            ans.push(curr.join(\",\"));\n        }\n\n    }\n    rec(0,k,p,nums,ans,[]);\n    let set = new Set(ans);\n\n    return set.size\n};",
        "solution_java": "class Solution {\n    public int countDistinct(int[] nums, int k, int p) {\n        int n = nums.length;\n        // we are storing hashcode for all the substrings so that we can compare them faster.\n        // main goal is to avoid entire sub array comparision using hashcode.\n        Set<Long> ways = new HashSet<>();\n        for(int i = 0; i < n; i++) {\n            int cnt = 0;\n            long hc = 1; // this is the running hashcode for sub array [i...j]\n            for(int j = i; j < n; j++) {\n                hc = 199L * hc + nums[j]; // updating running hashcode, since we nums are <=200, we shall consider a prime near 200 to avoid collision\n                if(nums[j] % p == 0)\n                    cnt++;\n                if(cnt <= k) { // if current subarray [i...j] is valid, add its hashcode in our storage.\n                    ways.add(hc);\n                }\n            }\n        }\n        return ways.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int countDistinct(vector<int>& nums, int k, int p) {\n        \n        int n=nums.size();\n        set<vector<int>>ans;\n        \n        int i,j;\n        for(i=0;i<n;i++)\n        {\n            vector<int>tt;\n            int ct=0;\n            for(j=i;j<n;j++)\n            {\n                tt.push_back(nums[j]);\n                if(nums[j]%p==0)\n                    ++ct;\n                if(ct>k)\n                    break;\n                ans.insert(tt);\n                    \n            }\n        }\n        return ans.size();\n    }\n    \n};"
    },
    {
        "title": "Minimum Space Wasted From Packaging",
        "algo_input": "You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.\n\nThe package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.\n\nYou want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.\n\n\n\tFor example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.\n\n\nReturn the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput: 6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.\n\n\nExample 2:\n\nInput: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput: -1\nExplanation: There is no box that the package of size 5 can fit in.\n\n\nExample 3:\n\nInput: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput: 9\nExplanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == packages.length\n\tm == boxes.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= m &lt;= 105\n\t1 &lt;= packages[i] &lt;= 105\n\t1 &lt;= boxes[j].length &lt;= 105\n\t1 &lt;= boxes[j][k] &lt;= 105\n\tsum(boxes[j].length) &lt;= 105\n\tThe elements in boxes[j] are distinct.\n\n",
        "solution_py": "class Solution:\n    def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n        # prefix sum to save time\n        acc = [0] + [*accumulate(packages)]\n        packages.sort()\n\n        ans = float('inf')\n        for box in boxes:\n            tmp = 0\n            # deal with smallest box first\n            box.sort()\n\n            # record number of packages already dealt with\n            start = 0\n\n            for b in box:\n                loc = bisect.bisect(packages, b)\n                if loc == 0: continue\n                tmp += b * (loc - start) - (acc[loc] - acc[start])\n\n                # all are packaged\n                if loc == len(packages):\n                    ans = min(ans, tmp)\n                    break\n\n                start = loc\n\n        return ans % (10 **9+7) if ans != float('inf') else -1",
        "solution_js": "/**\n * @param {number[]} packages\n * @param {number[][]} boxes\n * @return {number}\n */\nvar minWastedSpace = function(packages, boxes) {\n    let count=0,b,minWastage,totalPackagesSize=0n,minBoxesAreaForAnySupplier=BigInt(Number.MAX_SAFE_INTEGER),boxesArea=0n,p,coverdPackagesIndex,totalBoxesAreaForSupplier;\n    packages.sort(function(a,b){return a-b});\n    for(let i=0;i<packages.length;i++){\n        totalPackagesSize+=BigInt(packages[i]);\n    }\n\n    for(let i=0;i<boxes.length;i++){\n        boxes[i].sort(function(a,b){return a-b});\n        p=0;\n        totalBoxesAreaForSupplier=0n;\n        if(boxes[i][boxes[i].length-1]<packages[packages.length-1]){//This supplier is not big enough box for the largest package, hence this supplier can't be used.\n            continue;\n        }\n        for(let b=0;b<boxes[i].length;b++){\n            coverdPackagesIndex = binaryLowerBound(packages,p,packages.length-1,boxes[i][b]);\n            if(coverdPackagesIndex!==-1){\n                totalBoxesAreaForSupplier+=BigInt(boxes[i][b])*BigInt(coverdPackagesIndex-p+1);\n                p=coverdPackagesIndex+1;\n                if(p===packages.length){\n                    break;\n                }\n            }\n        }\n        if(p===packages.length){//Check if the current supplier was able to pack all the packages.\n            if(totalBoxesAreaForSupplier<minBoxesAreaForAnySupplier){\n                minBoxesAreaForAnySupplier = totalBoxesAreaForSupplier;\n            }\n        }\n    }\n    if(minBoxesAreaForAnySupplier!==BigInt(Number.MAX_SAFE_INTEGER)){\n        return (minBoxesAreaForAnySupplier-totalPackagesSize)%1000000007n;\n    }else{\n        return -1;\n    }\n\n    function binaryLowerBound(arr,left,right,key){\n        let mid,ans=-1;\n        while(left<=right){\n            mid = left + Math.floor((right-left)/2);\n            if(arr[mid]<=key){\n                ans=mid;\n                left=mid+1;\n            }else{\n                right=mid-1;\n            }\n        }\n        return ans;\n    }\n};",
        "solution_java": "class Solution {\n    public int minWastedSpace(int[] packages, int[][] boxes) {\n        Arrays.sort(packages);\n        int n = packages.length, k = -1;\n        long sum = 0, ans = Long.MAX_VALUE;\n        int[] pos = new int[100001];\n        for (int i = 0; i < 100001; i++){ // precompute jump position.\n            while(k < n - 1 && packages[k+1] == i){\n                sum += packages[++k];\n            }\n            pos[i] = k;\n        }\n        for (int[] b : boxes){\n            Arrays.sort(b);\n            long cost = -sum;\n            k=-1;\n            for (int i = 0; i < b.length; i++){\n                if (pos[b[i]] >= 0){\n                    int cnt = pos[b[i]]-k;\n                    cost += 1L * cnt * b[i];\n                    k=pos[b[i]];\n                }\n            }\n            ans = k == n-1? Math.min(cost, ans) : ans;\n        }\n\n        return ans == Long.MAX_VALUE? -1 : (int)(ans % (int)(1e9+7));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    #define MOD 1000000007\n    #define ll long long\n    int minWastedSpace(vector<int>& packages, vector<vector<int>>& boxes) {\n        \n        int n = packages.size();\n        int m = boxes.size();\n        sort(packages.begin(), packages.end());\n        vector<ll> pack(n + 1);\n        pack[0] = 0;\n        for(int i = 0;i<n; i++){\n            pack[i + 1] = packages[i];\n            pack[i + 1] += pack[i];\n        }\n        ll ans = 1e18;\n        bool mf = false;\n        for(int i = 0; i<m; i++){\n            vector<int> opt = boxes[i];\n            sort(opt.begin(), opt.end());\n            int back = 0;\n            ll temp = 0;\n            bool flag = false;\n            ll bag ;\n            for(int j = 0; j<(int)opt.size(); j++){\n                \n                bag = opt[j];\n                auto it = upper_bound(packages.begin(), packages.end(), bag);\n                auto it1 = it;\n                int idx ;\n                if(it != packages.begin()){\n                    it--;\n                    idx = it - packages.begin();\n                    ll num_packs = idx + 1 - back;\n                    \n                    ll pack_sum = pack[idx + 1] - pack[back];\n                    back = idx + 1;\n                    temp += (num_packs*bag - pack_sum);\n                }\n                if(it1 == packages.end()){\n                    flag = true;\n                    break;\n                }  \n            }\n            if(flag){\n                ans = min(ans, temp);\n                mf = true;\n            }\n                 \n        }\n        if(!mf) return -1;\n        \n        if(ans == 1e18) return -1;\n        ans = ans % MOD;\n        return ans;\n    }\n};"
    },
    {
        "title": "Cinema Seat Allocation",
        "algo_input": "\n\nA cinema&nbsp;has n&nbsp;rows of seats, numbered from 1 to n&nbsp;and there are ten&nbsp;seats in each row, labelled from 1&nbsp;to 10&nbsp;as shown in the figure above.\n\nGiven the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8]&nbsp;means the seat located in row 3 and labelled with 8&nbsp;is already reserved.\n\nReturn the maximum number of four-person groups&nbsp;you can assign on the cinema&nbsp;seats. A four-person group&nbsp;occupies four&nbsp;adjacent seats in one single row. Seats across an aisle (such as [3,3]&nbsp;and [3,4]) are not considered to be adjacent, but there is an exceptional case&nbsp;on which an aisle split&nbsp;a four-person group, in that case, the aisle split&nbsp;a four-person group in the middle,&nbsp;which means to have two people on each side.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput: 4\nExplanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\n\n\nExample 2:\n\nInput: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput: 2\n\n\nExample 3:\n\nInput: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 10^9\n\t1 &lt;=&nbsp;reservedSeats.length &lt;= min(10*n, 10^4)\n\treservedSeats[i].length == 2\n\t1&nbsp;&lt;=&nbsp;reservedSeats[i][0] &lt;= n\n\t1 &lt;=&nbsp;reservedSeats[i][1] &lt;= 10\n\tAll reservedSeats[i] are distinct.\n\n",
        "solution_py": "class Solution(object):\n    def maxNumberOfFamilies(self, n, reservedSeats):\n        \"\"\"\n        :type n: int\n        :type reservedSeats: List[List[int]]\n        :rtype: int\n        \"\"\"\n        d = defaultdict(set)\n        for row,seat in reservedSeats:\n            d[row].add(seat)\n        \n        def row(i):\n            a1 = not set((2,3,4,5)).intersection(d[i])\n            a2 = not set((6,7,8,9)).intersection(d[i])\n            if  a1 and a2:\n                return 2\n            if  a1 or a2:\n                return 1\n            return 1 if not set((4,5,6,7)).intersection(d[i]) else 0\n        \n        return sum((row(i) for i in d.keys())) + (n-len(d)) * 2",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} reservedSeats\n * @return {number}\n */\nvar maxNumberOfFamilies = function(n, reservedSeats) {\n    let a,b,c,reservedMap={},ans=n*2,takenB={};\n    for(let i=0;i<reservedSeats.length;i++){\n        let resverd = reservedSeats[i];\n        let row = resverd[0];\n        if(reservedMap[row]===undefined){\n            reservedMap[row]={}\n        }\n        if(2<=resverd[1] && resverd[1]<=3 && reservedMap[row]['a']===undefined){//a is blocked now\n            ans--;\n            reservedMap[row]['a']=true;\n            if(reservedMap[row]['c']===true && reservedMap[row]['b']===undefined){\n                takenB[resverd[0]]=true;\n                ans++;//add for b\n            }\n        }else if(8<=resverd[1] && resverd[1]<=9 && reservedMap[row]['c']===undefined){//c is blocked now\n            ans--;\n            reservedMap[row]['c']=true;\n            if(reservedMap[row]['a']===true && reservedMap[row]['b']===undefined){\n                takenB[resverd[0]]=true;\n                ans++;//add for b\n            }\n        }else if(4<=resverd[1] && resverd[1]<=5){//b is blocked now\n            if(reservedMap[row]['a']===undefined){\n                ans--;\n                reservedMap[row]['a']=true;\n            }\n            if(takenB[resverd[0]]===true){\n                ans--;//substract for b\n                takenB[resverd[0]]=false;\n            }\n            reservedMap[row]['b']=true;\n        }else if(6<=resverd[1] && resverd[1]<=7){//b is blocked now\n            if(reservedMap[row]['c']===undefined){\n                ans--;\n                reservedMap[row]['c']=true;\n            }\n            if(takenB[resverd[0]]===true){\n                ans--;//substract for b\n                takenB[resverd[0]]=false;\n            }\n            reservedMap[row]['b']=true;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxNumberOfFamilies(int n, int[][] reservedSeats) {\n        Map<Integer, int[]> seats = new HashMap<>();\n        int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots\n\n        for (int[] seat: reservedSeats) {\n            int row = seat[0];\n            int col = seat[1];\n            int[] slots = seats.getOrDefault(row, new int[3]);\n\n            if (col >= 2 && col <= 5) { // left slot\n                slots[0] = 1;\n            }\n            if (col >= 4 && col <= 7) { // middle slot\n                slots[1] = 1;\n            }\n            if (col >= 6 && col <= 9) { // right slot\n                slots[2] = 1;\n            }\n\n            seats.put(seat[0], slots);\n        }\n\n        for (int[] slots: seats.values()) {\n            int taken = slots[0] + slots[2];\n\n            if (taken == 2) { // both slots at either ends are taken\n                if (slots[1] == 0) { // check if middle slot not taken\n                    availableSlots--; // reduce availableslots by 1 since middle slot is available\n                } else {\n                    availableSlots -= 2; // entire row not available - reduce by 2\n                }\n            } else if (taken == 1) { // one of the slots at either ends are taken\n                availableSlots--; // reduce by 1 since either side of the slots not available\n            } else {\n                continue; // entire row is available - no need to reduce the available slots\n            }\n        }\n\n        return availableSlots;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) {\n        unordered_map<int, vector<int>> o;\n        \n        for (auto r : reservedSeats) {\n            \n            o[r[0]].push_back(r[1]);\n        }\n        \n        int ans = 2 * (n - o.size()); // seats with no occupancy directly adding 2\n        \n\t\t// if we iterate from 1 to n (10 ^ 9) we cross time limit\n        for (auto p : o) {\n            \n            // get reserved seats\n            vector<int> seats = p.second;\n            \n            \n            int occupied_mask = 0;\n            \n            // representing occupied seats as bits\n            for (int s : seats) {\n                if (s > 1 && s < 10) {\n                    occupied_mask += (int)pow(2, 10 - s);\n                }\n            }\n            \n            // checking 3 seating configurations\n            int masks[3] = {480, 120, 30};\n            \n            int row_ans = 0;\n            bool res1 = (masks[0] & occupied_mask) == 0;\n            bool res2 = (masks[1] & occupied_mask) == 0;\n            bool res3 = (masks[2] & occupied_mask) == 0;\n           \n\t\t\t// if all 3 configurations are empty, 2 families\n\t\t\t// if either one of them are empty, 1 family\n            if (res1 && res2 && res3) row_ans += 2;\n            else if (res1 || res2 || res3) row_ans += 1;\n            \n            \n            ans += row_ans;\n            \n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Compatibility Score Sum",
        "algo_input": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).\n\nThe survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).\n\nEach student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.\n\n\n\tFor example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same.\n\n\nYou are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.\n\nGiven students and mentors, return the maximum compatibility score sum that can be achieved.\n\n&nbsp;\nExample 1:\n\nInput: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput: 8\nExplanation:&nbsp;We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.\n\n\nExample 2:\n\nInput: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput: 0\nExplanation: The compatibility score of any student-mentor pair is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == students.length == mentors.length\n\tn == students[i].length == mentors[j].length\n\t1 &lt;= m, n &lt;= 8\n\tstudents[i][k] is either 0 or 1.\n\tmentors[j][k] is either 0 or 1.\n\n",
        "solution_py": "import heapq\nfrom collections import defaultdict\n\nclass Solution:\n    def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n        m, n = len(students), len(students[0])\n        def hamming(student, mentor):\n            return sum([int(student[i] != mentor[i]) for i in range(n)])\n\n        pq = [(0, 0, '0'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)\n        optimal = defaultdict(lambda:float('inf'))\n\n        while pq: # O(V)\n            cost, i, mentor_status = heapq.heappop(pq) # O(logV)\n\n            # early stopping with termination condition\n            if i == m:\n                return m * n - cost\n\n            # generate successors. The next student to be assigned is at index i\n            for j, mentor in enumerate(mentors): # O(m)\n                if mentor_status[j] != '1':\n                    new_cost = cost + hamming(students[i], mentor)\n                    new_mentor_status = mentor_status[:j] + '1' + mentor_status[j+1:]\n\n                    # update optimal cost if a new successor appears with lower cost to the same node\n                    if new_cost < optimal[(i+1, new_mentor_status)]:\n                        optimal[(i+1, new_mentor_status)] = new_cost\n                        heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV)\n\n        return 0",
        "solution_js": "var maxCompatibilitySum = function(students, mentors) {\n    const m = students.length;\n    const n = students[0].length;\n\n    let max = 0;\n\n    dfs(0, (1 << m) - 1, 0);\n\n    return max;\n\n    function dfs(studentIdx, bitmask, scoreTally) {\n        if (studentIdx === m) {\n            max = Math.max(max, scoreTally);\n\n            return;\n        }\n\n        for (let mentorIdx = 0; mentorIdx < m; ++mentorIdx) {\n            if (bitmask & (1 << mentorIdx)) {\n                const matchScore = hammingDistance(students[studentIdx], mentors[mentorIdx]);\n                const setMask = bitmask ^ (1 << mentorIdx);\n\n                dfs(studentIdx + 1, setMask, scoreTally + matchScore);\n            }\n        }\n\n        return;\n    }\n\n    function hammingDistance(studentsAnswers, mentorsAnswers) {\n        let matches = 0;\n\n        for (let j = 0; j < n; ++j) {\n            if (studentsAnswers[j] === mentorsAnswers[j]) ++matches;\n        }\n\n        return matches;\n    }\n};",
        "solution_java": "class Solution {\n    int max;\n    public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n        boolean[] visited = new boolean[students.length];\n        helper(visited, students, mentors, 0, 0);\n        return max;\n    }\n    public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos, int score){\n        if(pos >= students.length){\n            max = Math.max(max, score);\n            return;\n        }\n        for(int i = 0; i < mentors.length; i++)\n            if(!visited[i]){\n                visited[i] = true;\n                helper(visited, students, mentors, pos + 1, score + score(students[pos], mentors[i]));\n                visited[i] = false;\n            }\n    }\n    public int score(int[] a, int[] b){\n        int count = 0;\n\n        for(int i = 0; i < b.length; i++)\n            if(a[i] == b[i]) count += 1;\n        return count;\n    }\n}",
        "solution_c": "class Solution {\n    // Calculating compatibility scores of ith student and jth mentor\n    int cal(int i,int j,vector<vector<int>>& arr1,vector<vector<int>>& arr2){\n        int cnt=0;\n        for(int k=0;k<arr1[0].size();k++){\n            if(arr1[i][k]==arr2[j][k]){\n                cnt++;\n            }\n        }\n        return cnt;\n    }\n\n    int helper(int i,int m,vector<vector<int>>& arr1,vector<vector<int>>& arr2,vector<bool>& vis){\n        if(i==m){\n            return 0;\n        }\n        int ans = 0;\n        for(int j=0;j<m;j++){\n            if(!vis[j]){\n                vis[j]=1;\n                ans = max(ans,cal(i,j,arr1,arr2) + helper(i+1,m,arr1,arr2,vis));\n                vis[j]=0; // Backtracking\n            }\n        }\n        return ans;\n    }\n\npublic:\n    int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n        int m = students.size();\n        vector<bool> vis(m,0); // To keep track of which mentor is already paired up\n        return helper(0,m,students,mentors,vis);\n    }\n};"
    },
    {
        "title": "Sum of Unique Elements",
        "algo_input": "You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.\n\nReturn the sum of all the unique elements of nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,2]\nOutput: 4\nExplanation: The unique elements are [1,3], and the sum is 4.\n\n\nExample 2:\n\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: There are no unique elements, and the sum is 0.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5]\nOutput: 15\nExplanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def sumOfUnique(self, nums: List[int]) -> int:\n        hashmap = {}\n        for i in nums:\n            if i in hashmap.keys():\n                hashmap[i] += 1\n            else:\n                hashmap[i] = 1\n        sum = 0\n        for k, v in hashmap.items():\n            if v == 1: sum += k\n        return sum",
        "solution_js": "var sumOfUnique = function(nums) {\n  let obj = {}\n  let sum = 0\n  // count frequency of each number\n  for(let num of nums){\n    if(obj[num] === undefined){\n      sum += num\n      obj[num] = 1\n    }else if(obj[num] === 1){\n      sum -= num\n      obj[num] = -1\n    }\n  }\n\n  return sum\n};",
        "solution_java": "class Solution {\n    public int sumOfUnique(int[] nums) {\n        int res = 0;\n        Map<Integer,Integer> map = new HashMap<>();\n        for(int i = 0;i<nums.length;i++){\n            map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n            if(map.get(nums[i]) == 1)res+=nums[i];\n            else if(map.get(nums[i]) == 2)res-=nums[i];\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int sumOfUnique(vector<int>& nums)\n    {\n       int sum=0;\n       map<int,int>mp;\n\n       for(auto x:nums)\n       mp[x]++;\n\n       for(auto m:mp)\n       {\n           if(m.second==1)\n               sum+=m.first;\n       }\n        return sum;\n    }\n};"
    },
    {
        "title": "Dinner Plate Stacks",
        "algo_input": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.\n\nImplement the DinnerPlates class:\n\n\n\tDinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity.\n\tvoid push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity.\n\tint pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.\n\tint popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]\nOutput\n[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\n\nExplanation: \nDinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5);         // The stacks are now:  2  4\n                                           1  3  5\n                                           ﹈ ﹈ ﹈\nD.popAtStack(0);   // Returns 2.  The stacks are now:     4\n                                                       1  3  5\n                                                       ﹈ ﹈ ﹈\nD.push(20);        // The stacks are now: 20  4\n                                           1  3  5\n                                           ﹈ ﹈ ﹈\nD.push(21);        // The stacks are now: 20  4 21\n                                           1  3  5\n                                           ﹈ ﹈ ﹈\nD.popAtStack(0);   // Returns 20.  The stacks are now:     4 21\n                                                        1  3  5\n                                                        ﹈ ﹈ ﹈\nD.popAtStack(2);   // Returns 21.  The stacks are now:     4\n                                                        1  3  5\n                                                        ﹈ ﹈ ﹈ \nD.pop()            // Returns 5.  The stacks are now:      4\n                                                        1  3 \n                                                        ﹈ ﹈  \nD.pop()            // Returns 4.  The stacks are now:   1  3 \n                                                        ﹈ ﹈   \nD.pop()            // Returns 3.  The stacks are now:   1 \n                                                        ﹈   \nD.pop()            // Returns 1.  There are no stacks.\nD.pop()            // Returns -1.  There are still no stacks.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= capacity &lt;= 2 * 104\n\t1 &lt;= val &lt;= 2 * 104\n\t0 &lt;= index &lt;= 105\n\tAt most 2 * 105 calls will be made to push, pop, and popAtStack.\n\n",
        "solution_py": "class DinnerPlates:\n\n    def __init__(self, capacity: int):\n        self.heap = []\n        self.stacks = []\n        self.capacity = capacity\n\n    def push(self, val: int) -> None:\n        if self.heap:\n            index = heapq.heappop(self.heap)\n            if index < len(self.stacks):\n                self.stacks[index].append(val)\n            else:\n                self.push(val)\n        elif self.stacks:\n            lastStack = self.stacks[-1]\n            if len(lastStack) != self.capacity:\n                lastStack.append(val)\n            else:\n                stack = deque()\n                stack.append(val)\n                self.stacks.append(stack)\n        else:\n            stack = deque()\n            stack.append(val)\n            self.stacks.append(stack)\n            \n    def pop(self) -> int:\n        while self.stacks:\n            lastStack = self.stacks[-1]\n            if lastStack:\n                val = lastStack.pop()\n                if not lastStack:\n                    self.stacks.pop()\n                return val\n            else:\n                self.stacks.pop()\n        return -1\n\n    def popAtStack(self, index: int) -> int:\n        if index == len(self.stacks) - 1:\n            return self.pop()\n        if index < len(self.stacks):\n            stack = self.stacks[index]\n            if stack:\n                val = stack.pop()\n                heapq.heappush(self.heap, index)\n                return val\n        return -1\n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)",
        "solution_js": "/**\n * @param {number} capacity\n */\nvar DinnerPlates = function(capacity) {\n    this.capacity = capacity;\n    this.stacks = [];\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nDinnerPlates.prototype.push = function(val) {\n    var needNewStack = true\n    for (var i = 0; i < this.stacks.length; i++) {\n        if (this.stacks[i].length < this.capacity) {\n            this.stacks[i].push(val);\n            needNewStack = false;\n            break;\n        }\n    }\n    \n    if (needNewStack) {\n        this.stacks.push([val]);\n    }\n    \n};\n\n/**\n * @return {number}\n */\nDinnerPlates.prototype.pop = function() {\n    var val = -1;\n    for (var i = this.stacks.length - 1; i >= 0; i--) {\n        if (this.stacks[i].length > 0) {\n            val = this.stacks[i].pop();\n            break;\n        }\n    }\n    return val;\n};\n\n/** \n * @param {number} index\n * @return {number}\n */\nDinnerPlates.prototype.popAtStack = function(index) {\n    // console.log(index, this.stacks, ...this.stacks[index])\n    var val = -1;\n    if (this.stacks[index] && this.stacks[index].length > 0) {\n        val = this.stacks[index].pop()\n    }\n    return val;\n};\n\n/** \n * Your DinnerPlates object will be instantiated and called as such:\n * var obj = new DinnerPlates(capacity)\n * obj.push(val)\n * var param_2 = obj.pop()\n * var param_3 = obj.popAtStack(index)\n */",
        "solution_java": "class DinnerPlates {\n    \n    List<Stack<Integer>> stack;\n    PriorityQueue<Integer> leftEmpty;\n    PriorityQueue<Integer> rightNonEmpty;\n    int cap;\n    public DinnerPlates(int capacity) {\n        this.cap = capacity;\n        this.stack = new ArrayList<>();\n        this.leftEmpty = new PriorityQueue<>();\n        this.rightNonEmpty = new PriorityQueue<>(Collections.reverseOrder());\n        stack.add(new Stack<>());\n        leftEmpty.offer(0);\n    }\n    \n    public void push(int val) {\n        while(!leftEmpty.isEmpty() && stack.get(leftEmpty.peek()).size() == cap) leftEmpty.poll();\n        if(leftEmpty.isEmpty()) {\n            stack.add(new Stack<>());\n            leftEmpty.offer(stack.size() - 1);\n        }\n        Stack<Integer> s = stack.get(leftEmpty.peek());\n        if(s.isEmpty()) rightNonEmpty.offer(leftEmpty.peek());\n        s.push(val);\n    }\n    \n    public int pop() {\n        while(!rightNonEmpty.isEmpty() && stack.get(rightNonEmpty.peek()).isEmpty()) rightNonEmpty.poll();\n        if(rightNonEmpty.isEmpty()) {\n            return -1;\n        }        \n        Stack<Integer> s = stack.get(rightNonEmpty.peek());\n        if(s.size() == cap) leftEmpty.offer(rightNonEmpty.peek());\n        return s.pop();\n    }\n    \n    public int popAtStack(int index) {\n        if(index >= stack.size()) return -1;\n        Stack<Integer> s = stack.get(index);\n        if(s.isEmpty()) return -1;\n        if(s.size() == cap) leftEmpty.offer(index);\n        return s.pop();\n    }\n}\n\n/**\n * Your DinnerPlates object will be instantiated and called as such:\n * DinnerPlates obj = new DinnerPlates(capacity);\n * obj.push(val);\n * int param_2 = obj.pop();\n * int param_3 = obj.popAtStack(index);\n */",
        "solution_c": "class DinnerPlates {\npublic:\n    map<int,stack<int>>mp;\n    set<int>empty;\n    int cap;\n    DinnerPlates(int capacity) \n    {\n        this->cap=capacity;\n    }\n    \n    void push(int val) \n    {\n        if(empty.size()==0)\n        {\n            empty.insert(mp.size());\n        }\n        mp[*empty.begin()].push(val);\n        if(mp[*empty.begin()].size()==cap)\n        {\n            empty.erase(empty.begin());\n        }\n    }\n    int pop() \n    {\n        if(mp.size()==0)\n        {\n            return -1;\n        }\n        int index=mp.rbegin()->first;\n        int val=mp[index].top();\n        mp[index].pop();\n        empty.insert(index);\n        if(mp[index].size()==0)\n        {\n            mp.erase(index);\n        }\n        return val;\n    }\n    \n    int popAtStack(int index) \n    {\n        if(mp.size()==0||mp.find(index)==mp.end())\n        {\n            return -1;\n        }\n        int val=mp[index].top();\n        mp[index].pop();\n        empty.insert(index);\n        if(mp[index].size()==0)\n        {\n            mp.erase(index);\n        }\n        return val;\n    }\n};"
    },
    {
        "title": "Split Linked List in Parts",
        "algo_input": "Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.\n\nThe length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.\n\nThe parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.\n\nReturn an array of the k parts.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3], k = 5\nOutput: [[1],[2],[3],[],[]]\nExplanation:\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput: [[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation:\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 1000].\n\t0 &lt;= Node.val &lt;= 1000\n\t1 &lt;= k &lt;= 50\n\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n        length = 0\n        cur = head\n        while cur:\n            length += 1\n            cur = cur.next\n        # DON'T do following since this makes head become null\n        # while head:\n        # length += 1\n        # head = head.next\n\n        # calculate the base size and the number of parts contain extra number\n        size, extra = length // k, length % k\n\n        # create empty list to store split parts\n        res = [[] for _ in range(k)]\n\n        # use two ptrs to split parts\n        prev, cur = None, head\n\n        for i in range(k):\n            res[i] = cur\n            # if this part contains extra number, it has (size+1) number\n            for j in range(size + (1 if extra > 0 else 0)):\n                prev, cur = cur, cur.next\n            if prev: prev.next = None\n            extra -= 1\n\n        return res",
        "solution_js": "var splitListToParts = function(head, k) {\n    let length = 0, current = head, parts = [];\n\n    while (current) {\n        length++;\n        current = current.next;\n    }\n\n    let base_size = Math.floor(length / k), extra = length % k;\n    current = head;\n\n    for (let i = 0; i < k; i++) {\n        let part_size = base_size + (extra > 0 ? 1 : 0);\n        let part_head = null, part_tail = null;\n\n        for (let j = 0; j < part_size; j++) {\n            if (!part_head) {\n                part_head = part_tail = current;\n            } else {\n                part_tail.next = current;\n                part_tail = part_tail.next;\n            }\n\n            if (current) {\n                current = current.next;\n            }\n        }\n\n        if (part_tail) {\n            part_tail.next = null;\n        }\n\n        parts.push(part_head);\n        extra = Math.max(extra - 1, 0);\n    }\n\n    return parts;\n};",
        "solution_java": "class Solution {\n    public ListNode[] splitListToParts(ListNode head, int k) {\n        ListNode[] arr=new ListNode[k];\n\n        if(k<2 || head==null || head.next==null){\n            arr[0]=head;\n            return arr;\n        }\n\n        ListNode temp=head;\n        int len=1;\n        while(temp.next!=null){\n            len++;\n            temp=temp.next;\n        }\n\n        int partition= len/k; //no of part 3\n        int extra=len%k; //extra node 1 0\n\n        ListNode curr=head;\n        ListNode prev=null;\n        int index=0;\n        while(head!=null){\n            arr[index++]=curr;\n            for(int i=0; i<partition && curr!=null ; i++){\n                prev=curr;\n                curr=curr.next;\n            }\n            if(extra>0){\n                prev=curr;\n                curr=curr.next;\n                extra--;\n            }\n            head=curr;\n            prev.next=null;\n\n        }\n     return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<ListNode*> splitListToParts(ListNode* head, int k)\n    {\n       vector<ListNode*>ans;\n       int len=0;\n        ListNode*temp=head;\n       while(temp!=NULL)\n           len++,temp=temp->next;\n\n       int y=len/k , z=len%k;\n\n       while(head !=NULL)\n       {\n           ans.push_back(head);\n           int count=1;\n           while(head!=NULL && count<y)\n                 head=head->next,count++;\n\n           if(z && y)\n           {\n               head=head->next;z--;\n           }\n           if(head==NULL) continue;\n           ListNode*temp=head->next;\n           head->next=NULL;\n           head=temp;\n       }\n       while(ans.size()<k)\n       {\n           ans.push_back(NULL);\n       }\n\n       return ans;\n    }\n};"
    },
    {
        "title": "Maximum Number of Occurrences of a Substring",
        "algo_input": "Given a string s, return the maximum number of ocurrences of any substring under the following rules:\n\n\n\tThe number of unique characters in the substring must be less than or equal to maxLetters.\n\tThe substring size must be between minSize and maxSize inclusive.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4\nOutput: 2\nExplanation: Substring \"aab\" has 2 ocurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).\n\n\nExample 2:\n\nInput: s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3\nOutput: 2\nExplanation: Substring \"aaa\" occur 2 times in the string. It can overlap.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\t1 &lt;= maxLetters &lt;= 26\n\t1 &lt;= minSize &lt;= maxSize &lt;= min(26, s.length)\n\ts consists of only lowercase English letters.\n\n",
        "solution_py": "#   0   1   2   3\n#   a   a   a   a\n#   l\n#   r\n\n#ref: https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/457577/C%2B%2B-Greedy-approach-%2B-Sliding-window-O(n).\n\n#Intuition\n#if a string have occurrences x times, any of its substring must also appear at least x times\n#there must be a substring of length minSize, that has the most occurrences\n#so that we just need to count the occurrences of all substring with length minSize\n\n#Explanation\n#find the maximum occurrences of all substrings with length = minSize\nclass Solution:\n    #T=O(n), S=O(n)\n    #use sliding window to lock down substrings to minSize limit (greedy approach)\n    #then use a counter to count the occurences of valid substrings\n    def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n        #dict to store valid substrings and their respective occurences count\n        d = defaultdict(int)\n        #find longest substrings that has k unique chars\n        #counter dict for char count and make sure unique char count is not exceeded\n        counter = defaultdict(int)\n        #init left and right pointers of sliding window\n        r = l = 0\n        #iterate right pointer\n        while r < len(s):\n            counter[s[r]] += 1\n            \n            #invalid window found, so make it valid again\n            #len of window is greater than minSize\n            while (r - l + 1) > minSize:\n                counter[s[l]] -= 1\n                #remove the key from dict for unique char count if it becomes zero\n                if counter[s[l]] == 0:\n                    del counter[s[l]]\n                #increment the left pointer to make it a valid window\n                l += 1\n\n            #valid window size (minSize) and unique char count is lesser than or equal to maxLetters\n            if r - l + 1 == minSize and len(counter) <= maxLetters:\n                #increment count of the occurence of the substring\n                d[s[l:r+1]] += 1\n            \n            #make sure to update right pointer only after an iteration\n            r += 1\n        \n        #return the count of substring with max occurence\n        #edge case with no substring\n        return max(d.values()) if d else 0",
        "solution_js": "var maxFreq = function(s, maxLetters, minSize, maxSize) {\n\n    let output = 0;\n\n    let left = 0, right = 0;\n\n    let map = {};\n\n    let map2 = {};\n\n    let count = 0;\n\n    while(right < s.length){\n\n        if(map[s[right]] === undefined){ // adding letters to map to keep track of occurences (count)\n            map[s[right]] = 1;\n            count++;\n\n        } else {\n            if(map[s[right]] === 0){\n                count++;\n            }\n            map[s[right]]++;\n        }\n\n        if(right - left + 1 > minSize) { // once over minSize removing occurence of left most letter from map and adjusting count\n\n            map[s[left]]--;\n            if(map[s[left]] < 1){\n                count--;\n            }\n            left++;\n        }\n\n        if(right - left + 1 >= minSize && count <= maxLetters){\n            map2[s.substring(left, right + 1)] = (map2[s.substring(left, right + 1)] || 0) + 1; // if subsitrng meets constraints of size and count add to map2;\n        }\n\n        right++;\n    }\n\n    Object.entries(map2).map(([key, val]) => output = Math.max(output, val)); // get largest value in map2\n\n    return output;\n\n};",
        "solution_java": "class Solution {\n    public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {\n        Map<String,Integer> count = new HashMap<>();\n        int ans = 0;\n        int n = s.length();\n        \n        for(int i=0;i+minSize-1<n;i++){\n            String y = s.substring(i,i+minSize);\n            count.put(y,count.getOrDefault(y,0)+1);\n\n            int unique = uniqueCharactersInString(y);\n            if(unique<=maxLetters){\n                ans = Math.max(ans,count.get(y));\n            }\n        }\n        //System.out.println(count);\n        return ans;\n    }\n    int uniqueCharactersInString(String y){\n        Set<Character> hs = new HashSet<>();\n        for(int j=0;j<y.length();j++) \n            hs.add(y.charAt(j));\n        return hs.size();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxFreq(string s, int maxLetters, int minSize, int maxSize) {\n        \n        int i, j, k, ans = 0, res, n = s.length();\n        \n        string temp;\n        unordered_map<char, int> st;\n        unordered_map<string, int> mp;\n        \n        i = 0, j = 0;\n        while(i <= n - minSize && j < n)\n        {\n            temp += s[j];\n            st[s[j]] += 1;;\n            if(temp.length() == minSize)\n            {\n                if(st.size() <= maxLetters)\n                    mp[temp] += 1;\n                i += 1;\n                st[temp[0]] -= 1;\n                if(st[temp[0]] == 0)\n                    st.erase(temp[0]);\n                temp.erase(temp.begin());\n            }\n            j += 1;\n        }\n        for(auto el : mp)\n            ans = max(ans, el.second);\n        return ans;\n    }\n};"
    },
    {
        "title": "Text Justification",
        "algo_input": "Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.\n\nYou should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.\n\nExtra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n\nFor the last line of text, it should be left-justified, and no extra space is inserted between words.\n\nNote:\n\n\n\tA word is defined as a character sequence consisting of non-space characters only.\n\tEach word's length is guaranteed to be greater than 0 and not exceed maxWidth.\n\tThe input array words contains at least one word.\n\n\n&nbsp;\nExample 1:\n\nInput: words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\nOutput:\n[\n&nbsp; &nbsp;\"This &nbsp; &nbsp;is &nbsp; &nbsp;an\",\n&nbsp; &nbsp;\"example &nbsp;of text\",\n&nbsp; &nbsp;\"justification. &nbsp;\"\n]\n\nExample 2:\n\nInput: words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\nOutput:\n[\n&nbsp; \"What &nbsp; must &nbsp; be\",\n&nbsp; \"acknowledgment &nbsp;\",\n&nbsp; \"shall be &nbsp; &nbsp; &nbsp; &nbsp;\"\n]\nExplanation: Note that the last line is \"shall be    \" instead of \"shall     be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.\n\nExample 3:\n\nInput: words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\nOutput:\n[\n&nbsp; \"Science &nbsp;is &nbsp;what we\",\n  \"understand &nbsp; &nbsp; &nbsp;well\",\n&nbsp; \"enough to explain to\",\n&nbsp; \"a &nbsp;computer. &nbsp;Art is\",\n&nbsp; \"everything &nbsp;else &nbsp;we\",\n&nbsp; \"do &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"\n]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 300\n\t1 &lt;= words[i].length &lt;= 20\n\twords[i] consists of only English letters and symbols.\n\t1 &lt;= maxWidth &lt;= 100\n\twords[i].length &lt;= maxWidth\n\n",
        "solution_py": "class Solution:\n    def fullJustify(self, words: List[str], maxwidth: int) -> List[str]:\n        curr = 0\n        last = []\n        res = []\n        for i in words:\n            if curr + len(i) + len(res) <= maxwidth:\n                curr += len(i)\n                res.append(i)\n            else:\n                last.append(res)\n                curr = len(i)\n                res = [i]\n        last.append(res)\n        ans = []\n        for idx ,row in enumerate(last):\n            x = maxwidth-len(\"\".join(row))\n            t = len(row)-1\n            if t == 0:\n                ans.append(row[0] + \" \"*(x))\n            elif idx != len(last)-1:\n                spaces = x//t\n                rem = x%t\n                res = row[0]\n                for i in row[1:]:\n                    temp = spaces\n                    if rem:\n                        temp += 1\n                        rem -= 1\n                    res = res + \" \"*temp + i\n                    # print(res, temp)\n                ans.append(res)\n            else:\n                res = row[0]\n                for i in row[1:]:\n                    res = res + ' '+i\n                res = res + \" \"*(maxwidth-len(res))\n                ans.append(res)\n\n        return ans",
        "solution_js": "/**\n * @param {string[]} words\n * @param {number} maxWidth\n * @return {string[]}\n */\nvar fullJustify = function(words, maxWidth) {\n    if (!words || !words.length) return;\n    \n    const wordRows = [];\n    let wordCols = [];\n    let count = 0;\n    words.forEach((word, i) => {\n        if ((count + word.length + wordCols.length) > maxWidth) {\n            wordRows.push(wordCols);\n            wordCols = [];\n            count = 0;\n        }\n        \n        wordCols.push(word);\n        count += word.length;\n\n        if (i === words.length - 1) {\n            wordRows.push(wordCols);\n        }        \n    });\n    \n    return wordRows.map((rowWords, i) => justifyText(rowWords, maxWidth, i === wordRows.length - 1));\n};\n\nconst justifyText = (rowWords, maxWidth, isLastLine) => {\n    let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0);\n    \n    if (rowWords.length === 1) {\n        return rowWords[0] + ' '.repeat(spaces);        \n    }\n    \n    if (isLastLine) {\n        spaces -= rowWords.length - 1\n        return rowWords.join(' ') + ' '.repeat(spaces);        \n    }\n    \n    let index = rowWords.length - 1;\n    let justifiedWord = '';\n    while (rowWords.length > 0) {\n        const repeater = Math.floor(spaces / (rowWords.length - 1));\n        const word = rowWords.pop();\n\n        if (index === 0) {\n            justifiedWord = word + justifiedWord;\n        } else if (index === 1) {\n            justifiedWord = ' '.repeat(spaces) + word + justifiedWord;\n        } else {\n            justifiedWord = ' '.repeat(repeater) + word + justifiedWord;\n        }\n        \n        index--;\n        spaces -= repeater;\n    }\n\n    return justifiedWord;\n}",
        "solution_java": "class Solution {\n    public List<String> fullJustify(String[] words, int maxWidth) {\n        List<String> unBalanced = new ArrayList<>();\n        List<String> balanced = new ArrayList<>();\n        int numSpaces = 0;\n\n        StringBuffer sb = new StringBuffer();\n        //Following code creates a list of unbalanced lines by appending words and 1 space between them\n        for(String word : words){\n\n            if(sb.length() == 0){\n                sb.append(word);\n            }else{\n                if(sb.length() + 1 + word.length() <= maxWidth){\n                    sb.append(\" \"+word);\n                }else{\n                    unBalanced.add(sb.toString());\n                    sb = new StringBuffer(word);\n                }\n            }\n\n        }\n\n        if(sb.length() >0){\n            unBalanced.add(sb.toString());\n        }\n\n        for(int j = 0; j < unBalanced.size(); j++){\n            String line = unBalanced.get(j);\n            numSpaces = maxWidth - line.length();\n            StringBuffer lineB = new StringBuffer(line);\n            //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces\n            if(j == unBalanced.size()-1 || !line.contains(\" \")){\n                int tempSpaces = maxWidth - lineB.length();\n                while(tempSpaces > 0){\n                    lineB.append(\" \");\n                    tempSpaces --;\n                }\n                balanced.add(lineB.toString());\n                continue;\n            };\n            // The following block checks for each character and appends 1 space during each loop\n            //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word\n            while(numSpaces > 0){\n                int i = 0;\n                while(i < lineB.length() - 1){\n                    if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){\n                        lineB.insert(i+1, ' ');\n                        i++;\n                        numSpaces --;\n                        if(numSpaces == 0) break;\n                    }\n                    i++;\n                }\n            }\n            balanced.add(lineB.toString());\n        }\n\n        return balanced;\n    }\n}",
        "solution_c": "class Solution {\n    string preprocessing(string &f, int space, int limit)\n    {\n        int noofspace = limit-f.size()+space;\n        int k = 0;\n        string r = \"\";\n        while(space)\n        {\n            int n = noofspace / space;\n            if((noofspace%space) != 0)\n                n += 1;\n            noofspace -= n;\n            while(f[k] != ' ')\n            {\n                r += f[k];\n                k++;\n            }\n            k++;\n            while(n--)\n            {\n                r += ' ';\n            }\n            space--;\n        }\n        while(k < f.size())\n        {\n            r += f[k];\n            k++;\n        }\n        while(noofspace--)\n            r += ' ';\n        return r;\n    }\npublic:\n    vector<string> fullJustify(vector<string>& words, int maxWidth) {\n        vector<string> ans;\n        string f = \"\";\n        int space = 0;\n        for(string &str : words)\n        {\n            if((f.size() + str.size() + 1) <= maxWidth && f.size() > 0)\n            {\n                f += ' ' + str;\n                space++;\n            }\n            else\n            {\n                if(f.size() > 0){\n                    f = preprocessing(f, space, maxWidth);\n                    ans.push_back(f);\n                    f = \"\";\n                }\n                f += str;\n                space = 0;\n            }\n        }\n        int sz = f.size();\n        while(sz < maxWidth)\n        {\n            f += ' ';\n            sz++;\n        }\n        ans.push_back(f);\n        return ans;\n    }\n};"
    },
    {
        "title": "Range Sum Query - Immutable",
        "algo_input": "Given an integer array nums, handle multiple queries of the following type:\n\n\n\tCalculate the sum of the elements of nums between indices left and right inclusive where left &lt;= right.\n\n\nImplement the NumArray class:\n\n\n\tNumArray(int[] nums) Initializes the object with the integer array nums.\n\tint sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"NumArray\", \"sumRange\", \"sumRange\", \"sumRange\"]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\nOutput\n[null, 1, -1, -3]\n\nExplanation\nNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-105 &lt;= nums[i] &lt;= 105\n\t0 &lt;= left &lt;= right &lt; nums.length\n\tAt most 104 calls will be made to sumRange.\n\n",
        "solution_py": "class NumArray:\n\n    def __init__(self, nums: List[int]):\n        self.nums, Sum = [], 0\n        for num in nums:\n            Sum += num\n            self.nums.append(Sum)\n\n    def sumRange(self, left: int, right: int) -> int:\n        return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]",
        "solution_js": "var NumArray = function(nums) {\n    this.nums = nums;\n};\n\nNumArray.prototype.sumRange = function(left, right) {\n    let sum = 0;\n    for(let i = left; i <= right; i++) sum += this.nums[i]\n    return sum\n};",
        "solution_java": "class NumArray {\n    int [] prefix;\n    public NumArray(int[] nums) {\n        int n = nums.length;\n        prefix = new int[n];\n        prefix[0] = nums[0];\n        for(int i = 1; i < n; i++){\n            prefix[i] = nums[i] + prefix[i - 1];\n        }\n    }\n\n    public int sumRange(int left, int right) {\n        if(left == 0){\n            return prefix[right];\n        }\n        return prefix[right] - prefix[left - 1];\n    }\n}",
        "solution_c": "class NumArray {\npublic:\n\tvector<int>arr;\n\tNumArray(vector<int>& nums) {\n\t\tarr=nums;\n\t}\n\n\tint sumRange(int left, int right) {\n\t\tint sum=0;\n\t\tfor(int i=left;i<=right;i++) sum+=arr[i];\n\t\treturn sum;\n\t}\n};"
    },
    {
        "title": "XOR Operation in an Array",
        "algo_input": "You are given an integer n and an integer start.\n\nDefine an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\n\nReturn the bitwise XOR of all elements of nums.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, start = 0\nOutput: 8\nExplanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.\n\n\nExample 2:\n\nInput: n = 4, start = 3\nOutput: 8\nExplanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\t0 &lt;= start &lt;= 1000\n\tn == nums.length\n\n",
        "solution_py": "class Solution:\n    def xorOperation(self, n: int, start: int) -> int:\n        nums = [start + 2*i for i in range(n)] #generate list of numbers\n        ans = nums[0]\n        for i in range(1,n):\n            ans = ans^nums[i] # XOR operation\n        return ans\n        \n        ",
        "solution_js": "var xorOperation = function(n, start) {\n    let arr = []\n    for(let i=0; i<n; i++){\n        arr.push(start+2*i)\n    }\n    return arr.reduce((a,c)=> a^c)\n};",
        "solution_java": "class Solution {\n    public int xorOperation(int n, int start) {\n        int nums[]=new int[n];\n        for(int i=0;i<n;i++)\n            nums[i] = start + 2 * i;\n        for(int i=1;i<n;i++)\n            nums[i] = nums[i-1]^nums[i];\n        return nums[n-1];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int xorOperation(int n, int start) {\n\n        int res = start;\n\n        for(int i=1 ; i<n ; i++){\n            res = res ^ (start + 2 * i);\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Removing Minimum Number of Magic Beans",
        "algo_input": "You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.\n\nRemove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.\n\nReturn the minimum number of magic beans that you have to remove.\n\n&nbsp;\nExample 1:\n\nInput: beans = [4,1,6,5]\nOutput: 4\nExplanation: \n- We remove 1 bean from the bag with only 1 bean.\n  This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n  This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n  This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer.\n\n\nExample 2:\n\nInput: beans = [2,10,3,2]\nOutput: 7\nExplanation:\n- We remove 2 beans from one of the bags with 2 beans.\n  This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n  This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n  This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= beans.length &lt;= 105\n\t1 &lt;= beans[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minimumRemoval(self, A: List[int]) -> int:\n        return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))",
        "solution_js": "/**\n * @param {number[]} beans\n * @return {number}\n */\n // time complexity -> O(NlogN) and Space is O(logN) due to sorting. \n var minimumRemoval = function(beans) {\n    beans.sort((a, b) => a - b);\n    let frontSum = beans.reduce((sum , a) => sum + a, 0);\n    let backSum = 0;\n    let done = 0;\n    let result = Number.MAX_SAFE_INTEGER;\n    for(let j = beans.length - 1; j >= 0; j--){\n        frontSum -= beans[j];\n        count = frontSum + (backSum - (beans[j] * done));\n        result = Math.min(result, count);\n        done++;\n        backSum += beans[j];\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public long minimumRemoval(int[] beans) {\n        Arrays.parallelSort(beans);\n        long sum=0,min=Long.MAX_VALUE;\n        int n=beans.length;\n        for(int i:beans)\n            sum+=i;\n        for(int i=0;i<n;i++)\n        {\n            long temp=sum-((n-i+0L)*beans[i]);\n            min=(long)Math.min(min,temp);\n           \n        }\n        return min;\n        \n        \n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long minimumRemoval(vector<int>& beans) {\n      long long n = beans.size();\n      sort(beans.begin(), beans.end());\n      long long sum = 0;\n            for(int i=0; i<n; i++)\n            {\n                    sum += beans[i];\n            }\n       long long ans = sum;\n       for(int i=0; i<n; i++)\n       {\n            long long curr = sum - (n-i)*beans[i];\n            if(ans > curr)\n            ans = curr;\n       }\n      return ans;      \n    }    \n};"
    },
    {
        "title": "Maximum Non Negative Product in a Matrix",
        "algo_input": "You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.\n\nAmong all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.\n\nReturn the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.\n\nNotice that the modulo is performed after getting the maximum product.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput: -1\nExplanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\n\n\nExample 2:\n\nInput: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput: 8\nExplanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\n\n\nExample 3:\n\nInput: grid = [[1,3],[0,-4]]\nOutput: 0\nExplanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 15\n\t-4 &lt;= grid[i][j] &lt;= 4\n\n",
        "solution_py": "class Solution:\n    def maxProductPath(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        \n        @lru_cache(None)\n        def fn(i, j): \n            \"\"\"Return maximum & minimum products ending at (i, j).\"\"\"\n            if i == 0 and j == 0: return grid[0][0], grid[0][0]\n            if i < 0 or j < 0: return -inf, inf\n            if grid[i][j] == 0: return 0, 0\n            mx1, mn1 = fn(i-1, j) # from top\n            mx2, mn2 = fn(i, j-1) # from left \n            mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n            return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n        \n        mx, _ = fn(m-1, n-1)\n        return -1 if mx < 0 else mx % 1_000_000_007",
        "solution_js": "var maxProductPath = function(grid) {\n    const R = grid.length, C = grid[0].length;\n    if (R === 0 || C === 0)\n        return -1;\n    \n    const mat = [...Array(R)].map(() => [...Array(C)].map(() => new Array(2)));\n    \n    mat[0][0] = [grid[0][0], grid[0][0]];\n    for (let i = 1; i < R; i++)\n        mat[i][0] = [mat[i-1][0][0]*grid[i][0], mat[i-1][0][1]*grid[i][0]];\n    \n    for (let i = 1; i < C; i++)\n        mat[0][i] = [mat[0][i-1][0]*grid[0][i], mat[0][i-1][1]*grid[0][i]];\n    \n    for (let i = 1; i < R; i++) {\n        for (let j = 1; j < C; j++) {\n            const max = Math.max(mat[i-1][j][0], mat[i][j-1][0]),\n                  min = Math.min(mat[i-1][j][1], mat[i][j-1][1]);\n            if (grid[i][j] >= 0)\n                mat[i][j] = [max*grid[i][j], min*grid[i][j]];\n            else\n                mat[i][j] = [min*grid[i][j], max*grid[i][j]];\n        }\n    }\n    \n    return mat[R-1][C-1][0] >= 0 ? mat[R-1][C-1][0] % (10**9+7) : -1;\n};",
        "solution_java": "class Solution {\n    public class Pair{\n        long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;\n        Pair(){\n\n        }\n        Pair(long min,long max){\n            this.min=min;\n            this.max=max;\n        }\n    }\n    public int maxProductPath(int[][] grid) {\n        Pair[][] dp=new Pair[grid.length][grid[0].length];\n        for(int r=grid.length-1;r>=0;r--){\n            for(int c=grid[0].length-1;c>=0;c--){\n                if(r==grid.length-1 && c==grid[0].length-1){\n                    dp[r][c]=new Pair(grid[r][c],grid[r][c]);\n                }else{\n                    Pair hor=(c==grid[0].length-1)?new Pair():dp[r][c+1];\n                    Pair ver=(r==grid.length-1)?new Pair():dp[r+1][c];\n                    long min,max;\n                    if(grid[r][c]>=0){\n                         max=Math.max(hor.max,ver.max);\n                         min=Math.min(hor.min,ver.min);\n                    }else{\n                         min=Math.max(hor.max,ver.max);\n                         max=Math.min(hor.min,ver.min);\n                    }\n                        dp[r][c]=new Pair(min*grid[r][c],max*grid[r][c]);\n                }\n            }\n        }\n        int mod=(int)1e9 +7;\n        return dp[0][0].max<0?-1:(int)(dp[0][0].max%mod);\n    }\n}",
        "solution_c": "const long long MOD = 1e9 + 7;\nclass Solution {\npublic:\n    int maxProductPath(vector<vector<int>>& grid) {\n        long long mx[20][20] = {0};\n        long long mn[20][20] = {0};\n        int row = grid.size(), col = grid[0].size();\n        \n        // Init\n        mx[0][0] = mn[0][0] = grid[0][0];\n        \n        // Init the row0 and col0 to be the continuous multiply of the elements.\n        for(int i = 1; i < row; i++){\n            mx[i][0] = mn[i][0] = mx[i - 1][0] * grid[i][0];\n        }\n        for(int j = 1; j < col; j++){\n            mx[0][j] = mn[0][j] = mx[0][j - 1] * grid[0][j];\n        }\n        \n        // DP as the explanation picture shows\n        for(int i = 1; i < row; i++){\n            for(int j = 1; j < col; j++){\n                mx[i][j] = max(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]);\n                mn[i][j] = min(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]);\n            }\n        }\n        \n        return mx[row - 1][col - 1] < 0 ? -1 : mx[row - 1][col - 1] % MOD;\n    }\n};"
    },
    {
        "title": "Expression Add Operators",
        "algo_input": "Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value.\n\nNote that operands in the returned expressions should not contain leading zeros.\n\n&nbsp;\nExample 1:\n\nInput: num = \"123\", target = 6\nOutput: [\"1*2*3\",\"1+2+3\"]\nExplanation: Both \"1*2*3\" and \"1+2+3\" evaluate to 6.\n\n\nExample 2:\n\nInput: num = \"232\", target = 8\nOutput: [\"2*3+2\",\"2+3*2\"]\nExplanation: Both \"2*3+2\" and \"2+3*2\" evaluate to 8.\n\n\nExample 3:\n\nInput: num = \"3456237490\", target = 9191\nOutput: []\nExplanation: There are no expressions that can be created from \"3456237490\" to evaluate to 9191.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num.length &lt;= 10\n\tnum consists of only digits.\n\t-231 &lt;= target &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def addOperators(self, num: str, target: int) -> List[str]:\n        s=num[0]\n        q=[\"+\",\"-\",\"*\",\"\"]\n        ans=[]\n        def cal(w):\n            i=1\n            while i<len(w)-1:\n                if w[i]=='*':\n                    q=int(w[i-1])*int(w[i+1])\n                    del w[i+1]\n                    del w[i]\n                    w[i-1]=q\n                    continue\n                i+=2\n            i=1 \n            while i<len(w)-1:\n                if w[i]=='+':\n                    q=int(w[i-1])+int(w[i+1])\n                    del w[i+1]\n                    del w[i]\n                    w[i-1]=q\n                    continue\n                elif w[i]=='-':\n                    q=int(w[i-1])-int(w[i+1])\n                    del w[i+1]\n                    del w[i]\n                    w[i-1]=q\n                    continue\n                i+=2\n            return w\n        def dfs(s,i):\n            nonlocal ans\n            if i==len(num):\n                x=''\n                myl=[]\n                for i in s:\n                    if i not in ['+','-','*']:\n                        x+=i\n                    else:\n                        myl.append(int(x))\n                        myl.append(i)\n                        x=''\n                myl.append(int(x))\n                print(myl)\n                a=cal(myl)\n                print(a)\n                if a[0]==target:\n                    ans.append(s)\n                return\n            for j in q:\n                dfs(s+j+num[i],i+1)\n        dfs(s,1)\n        return ans",
        "solution_js": "var addOperators = function(num, target) {\n    let res = [];\n\n    let i = 0;\n\n    const helper = (idx, sum, prev, path) => {\n        if(idx >= num.length) {\n            if(sum === target) {\n                res.push(path);\n            }\n            return null;\n        }\n\n        for(let j = idx; j < num.length; j++) {\n\n            if(j !== idx && num[idx] === \"0\")\n                break;\n\n            let n = Number(num.slice(idx, j+1));\n\n            if(idx === 0) {\n                helper(j + 1, sum + n, sum + n, path + n);\n            } else {\n                helper(j + 1, sum + n, n, path + \"+\" + n);\n\n                helper(j + 1, sum - n, 0 - n, path + \"-\" + n);\n\n                helper(j + 1, sum - prev + (prev * n), prev * n, path + \"*\" + n);\n            }\n        }\n\n    }\n\n    helper(i, 0, 0, \"\");\n\n    return res;\n};",
        "solution_java": "class Solution {\n    String s;\n    List<String>result;\n    int target;\n    public void operator(int i,int prev,long prod,long mid,String exp,List<Long>l){\n        if(i==l.size()){\n            if(mid+prod==target)\n                result.add(exp);\n            return;\n        }\n        if(prev==-1){\n            operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+\"*\"+l.get(i),l);\n        }else if(prev==1){\n            operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+\"*\"+l.get(i),l);\n        }else{\n            operator(i+1,0,prod*l.get(i),mid,exp+\"*\"+l.get(i),l);\n        }\n        operator(i+1,-1,0,mid+prod-l.get(i),exp+\"-\"+l.get(i),l);\n        operator(i+1,1,0,mid+prod+l.get(i),exp+\"+\"+l.get(i),l);\n    }\n    public void rec(int in,List<Long>l){\n        if(in==s.length()){\n            operator(1,1,0,l.get(0),l.get(0)+\"\",l);\n            return;\n        }\n        if(s.charAt(in)=='0'){\n            l.add(0L);\n            rec(in+1,l);\n            l.remove(l.size()-1);\n        }else{\n            for(int i=in;i<s.length();i++){\n                l.add(Long.parseLong(s.substring(in,i+1)));\n                rec(i+1,l);\n                l.remove(l.size()-1);\n            }\n        }\n    }\n    public List<String> addOperators(String num, int target) {\n        result=new ArrayList<>();\n        this.s=num;\n        this.target=target;\n        rec(0,new ArrayList<>(30));\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> res;\n    string s;\n    int target, n;\n    void solve(int it, string path, long long resSoFar, long long prev){\n        if(it == n){\n            if(resSoFar == target) res.push_back(path);\n            return;\n        }\n        long long num = 0;\n        string tmp;\n\n        for(auto j = it; j < n; j++){\n            if(j > it && s[it] == '0') break;\n\n            num = num * 10 + (s[j] - '0');\n            tmp.push_back(s[j]);\n\n            if(it == 0) solve(j + 1, tmp, num, num);\n            else{\n                solve(j + 1, path + \"+\" + tmp, resSoFar + num, num);\n                solve(j + 1, path + '-' + tmp, resSoFar - num, -num);\n                solve(j + 1, path + '*' + tmp, resSoFar - prev + prev * num, prev * num);\n            }\n        }\n\n    }\n    vector<string> addOperators(string num, int target) {\n        this -> target = target;\n        s = num, n = num.size();\n\n        solve(0, \"\", 0, 0);\n        return res;\n    }\n};"
    },
    {
        "title": "Eliminate Maximum Number of Monsters",
        "algo_input": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.\n\nThe monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.\n\nYou have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start.\n\nYou lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.\n\nReturn the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.\n\n&nbsp;\nExample 1:\n\nInput: dist = [1,3,4], speed = [1,1,1]\nOutput: 3\nExplanation:\nIn the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.\n\nExample 2:\n\nInput: dist = [1,1,2,3], speed = [1,1,1,1]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.\n\n\nExample 3:\n\nInput: dist = [3,2,4], speed = [5,3,2]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == dist.length == speed.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= dist[i], speed[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n        for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])):\n            if i > t:\n                return i\n        return len(dist)  ",
        "solution_js": "/**\n * @param {number[]} dist\n * @param {number[]} speed\n * @return {number}\n */\nvar eliminateMaximum = function(dist, speed) {\n    let res = 0;\n    let len = dist.length;\n    let map = new Map();\n    for(let i=0; i<len; i++){\n        // the last time to eliminate\n        let a = Math.ceil(dist[i] / speed[i]);\n        if(map.has(a)){\n            let c = map.get(a);\n            c ++;\n            map.set(a, c);\n        }else{\n            map.set(a, 1);\n        }\n    }\n\n    let keys = Array.from(map.keys());\n    keys.sort((a, b) => a-b);\n    // time to eliminate\n    let t = 0;\n    for(let i=0; i<keys.length; i++){\n        let c = map.get(keys[i]);\n        if(c > keys[i]-t){\n            res += keys[i]-t;\n            break;\n        }else{\n            res += c;\n            t += c;\n        }\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public int eliminateMaximum(int[] dist, int[] speed) {\n        \n        int n = dist.length;\n        \n        int[] time = new int[n];\n        \n        for(int i = 0; i < n; i++){\n            time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]);\n        }\n        \n        Arrays.sort(time);\n        \n        int eliminated = 0;\n\t\t\n\t\t// At i = 0, minute = 0 ( therefore, we can use i in place of minute )\n        \n        for(int i = 0; i < n; i++){\n\t\t\t \n            if(time[i] > i){  // At ith minute, eliminate the first monster arriving after ith minute\n                eliminated++;\n            }else{\n                break; // Monster reached the city\n            }\n        }\n        \n        return eliminated;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int eliminateMaximum(vector<int>& dist, vector<int>& speed) {\n        priority_queue<double, vector<double>, greater<double>> pq;\n        \n        for(int i = 0; i < dist.size(); ++i)\n            pq.push(ceil((double)dist[i] / speed[i] ));\n        \n        int t = 0;\n        while(pq.size() && pq.top() > t++) pq.pop();\n        return dist.size() - pq.size();\n    }\n};"
    },
    {
        "title": "Invert Binary Tree",
        "algo_input": "Given the root of a binary tree, invert the tree, and return its root.\n\n&nbsp;\nExample 1:\n\nInput: root = [4,2,7,1,3,6,9]\nOutput: [4,7,2,9,6,3,1]\n\n\nExample 2:\n\nInput: root = [2,1,3]\nOutput: [2,3,1]\n\n\nExample 3:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 100].\n\t-100 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution(object):\n    def invertTree(self, root):\n        # Base case...\n        if root == None:\n            return root\n        # swapping process...\n        root.left, root.right = root.right, root.left\n        # Call the function recursively for the left subtree...\n        self.invertTree(root.left)\n        # Call the function recursively for the right subtree...\n        self.invertTree(root.right)\n        return root     # Return the root...",
        "solution_js": "var invertTree = function(root) {\n  if (!root) return root;\n    [root.left, root.right] = [root.right, root.left];\n    invertTree(root.right)\n    invertTree(root.left)\n     return root\n};",
        "solution_java": "class Solution {\n    public TreeNode invertTree(TreeNode root) {\n\n        swap(root);\n        return root;\n    }\n\n    private static void swap(TreeNode current) {\n        if (current == null) {\n            return;\n        }\n\n        swap(current.left);\n        swap(current.right);\n\n        TreeNode temp = current.left;\n        current.left = current.right;\n        current.right = temp;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* invertTree(TreeNode* root) {\n        if(root == NULL) return root;\n        TreeNode* temp = root->left;\n        root->left = root->right;\n        root->right = temp;\n        invertTree(root->left);\n        invertTree(root->right);\n        return root;\n    }\n};"
    },
    {
        "title": "Number of Dice Rolls With Target Sum",
        "algo_input": "You have n dice and each die has k faces numbered from 1 to k.\n\nGiven three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 1, k = 6, target = 3\nOutput: 1\nExplanation: You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\n\n\nExample 2:\n\nInput: n = 2, k = 6, target = 7\nOutput: 6\nExplanation: You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\n\n\nExample 3:\n\nInput: n = 30, k = 30, target = 500\nOutput: 222616187\nExplanation: The answer must be returned modulo 109 + 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n, k &lt;= 30\n\t1 &lt;= target &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def numRollsToTarget(self, n, k, target):\n        \"\"\"\n        :type n: int\n        :type k: int\n        :type target: int\n        :rtype: int\n        \"\"\"\n\n        mem = {}\n\n        def dfs(i,currSum):\n\n            if currSum > target:\n                return 0\n\n            if i == n:\n                if currSum == target:\n                    return 1\n                return 0\n\n            if (i,currSum) in mem:\n                return mem[(i,currSum)]\n\n            ans = 0\n            for dicenumber in range(1,k+1):\n                ans += dfs(i+1,currSum+dicenumber)\n\n            mem[(i,currSum)] = ans\n\n            return mem[(i,currSum)]\n\n        return dfs(0,0) % (10**9 + 7)",
        "solution_js": "var numRollsToTarget = function(n, k, target) {\n    if (n > target || n * k < target) return 0 //target is impossible to reach\n    let arr = new Array(k).fill(1), depth = n //start the first layer of Pascal's N-ary Triangle.\n    while (depth > 1) { //more layers of Triangle to fill out\n        tempArr = [] //next layer of triangle. not done in place as previous layer's array values are needed\n        for (let i = 0; i < arr.length + k - 1 && i <= target - n; i++) { //looping is bounded by size of next layer AND how much data we actually need\n            let val = ((tempArr[i - 1] || 0) + (arr[i] || 0) - (arr[i - k] || 0)) % (1000000007) //current index value is the sum of K number of previous layer's values, once we hit K we add next and subtract last so we don't have to manually add all K values\n            tempArr.push(val)\n        }\n        arr = tempArr\n        depth -= 1\n    }\n    let ans = arr[target - n] //answer will be in target - nth index\n    return ans < 0 ? ans + 1000000007 : ans\n};",
        "solution_java": "class Solution {\n    public int numRollsToTarget(int n, int k, int target) {\n        if (target < n || target > n*k) return 0;\n        if (n == 1) return 1;\n\n        int[][] dp = new int[n+1][n*k+1];\n        for (int i = 1; i<= k; i++) {\n            dp[1][i] = 1;\n        }\n        int mod = 1000000007;\n        for (int i = 2; i <= n; i++) {\n            for (int j = i; j <= i*k && j <= target; j++) {\n                for (int x = 1; x <= k; x++) {\n                    if (j-x >= 1) {\n                        dp[i][j] += dp[i-1][j-x];\n                        if (dp[i][j] >= mod) {\n                            dp[i][j] %= mod;\n                        }\n                    }\n                }\n            }\n        }\n        return dp[n][target]%mod;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint dp[31][1001];\n\tSolution(){\n\t\tmemset(dp,-1,sizeof(dp));\n\t}\n\tint help(int dno,int &tdice,int &tf,int target){\n\t\tif(target<0 or dno>tdice) return 0;\n\t\tif(target==0 and dno==tdice) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(dp[dno][target]!=-1) return dp[dno][target];\n\t\tint ans=0;\n\t\tfor(int i=1;i<=tf;i++){\n\t\t\tans=(ans%1000000007+help(dno+1,tdice,tf,target-i)%1000000007)%1000000007;\n\n\t\t}\n\t\treturn dp[dno][target]=ans;\n\t}\n\tint numRollsToTarget(int n, int k, int target) {\n\t   return help(0,n,k,target);\n\n\t}\n};"
    },
    {
        "title": "Remove Covered Intervals",
        "algo_input": "Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.\n\nThe interval [a, b) is covered by the interval [c, d) if and only if c &lt;= a and b &lt;= d.\n\nReturn the number of remaining intervals.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\n\nExample 2:\n\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= intervals.length &lt;= 1000\n\tintervals[i].length == 2\n\t0 &lt;= li &lt; ri &lt;= 105\n\tAll the given intervals are unique.\n\n",
        "solution_py": "class Solution:\n    def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n\n        intervals.sort(key = lambda x: (x[0], -x[1]))\n        current, count = intervals[0], 1\n        for i in range(1, len(intervals)):\n            if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]:\n                continue\n            current = intervals[i]\n            count += 1\n        return count\n\n# time and space complexity\n# time: O(nlog(n))\n# space: O(1)",
        "solution_js": "var removeCoveredIntervals = function(intervals) {\n  intervals.sort((a,b)=> a[0]-b[0] || b[1]-a[1]);\n  let overlap=0;\n  for (i=1,prev=0; i<intervals.length; i++)\n//    if ((intervals[prev][0] <= intervals[i][0]) //no need to check, already done in sort\n//      && (intervals[prev][1] >= intervals[i][1]))\n\tif (intervals[prev][1] >= intervals[i][1]) // just look at 2nd index\n      overlap++  // add to skipped elements\n    else\n      prev=i; // didn't overlap, so we can advance our previous element\n  return intervals.length-overlap;\n};",
        "solution_java": "class Solution {\n    public int removeCoveredIntervals(int[][] intervals) {\n        if(intervals == null || intervals.length == 0) return 0;\n        Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0]));\n        int c = intervals[0][0], d = intervals[0][1];\n        int ans = intervals.length;\n        for(int i=1;i<intervals.length;i++){\n            int a = intervals[i][0], b = intervals[i][1];\n            if(c<=a && b<=d) ans--; \n            else {\n                c = a;\n                d = b;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int removeCoveredIntervals(vector<vector<int>>& intervals) \n    {\n        int cnt = 0, last = INT_MIN;\n        sort(intervals.begin(), intervals.end(), \n             [] (const vector<int>& v1, const vector<int>& v2) { \n                 if(v1[0] != v2[0]) return v1[0] < v2[0];\n                 else return v1[1] > v2[1];\n        });\n\n        for(int i=0; i<intervals.size(); i++)\n        {\n            if(intervals[i][1] <= last) ++cnt;\n            \n            if(intervals[i][1] > last) last = intervals[i][1];\n        }\n        \n        return intervals.size()-cnt;\n    }\n}; "
    },
    {
        "title": "Range Module",
        "algo_input": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.\n\nA half-open interval [left, right) denotes all the real numbers x where left &lt;= x &lt; right.\n\nImplement the RangeModule class:\n\n\n\tRangeModule() Initializes the object of the data structure.\n\tvoid addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.\n\tboolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.\n\tvoid removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\nOutput\n[null, null, null, true, false, true]\n\nExplanation\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= left &lt; right &lt;= 109\n\tAt most 104 calls will be made to addRange, queryRange, and removeRange.\n\n",
        "solution_py": "from bisect import bisect_left as bl, bisect_right as br\nclass RangeModule:\n\n    def __init__(self):\n        self._X = []\n\n    def addRange(self, left: int, right: int) -> None:\n        # Main Logic \n        #   If idx(left) or idx(right) is odd, it's in a interval. So don't add it. \n        #   If idx(left) or idx(right) is even, it's not in any interval. So add it as new interval \n        #   Slice array[idx(left) : idx(right)]\n        #       1) both odd: Nothing is added. Merge all middle intervals. \n        #       2) both even: Add new intervals. Merge all middle intervals\n        #       3) idx(left) is even: update start point of next interval with left\n        #       4) idx(right) is even: update end point of previous interval with right\n        # Bisect_left vs. Bisect_right\n        #   left need to proceed all interval closing at left, so use Bisect_left\n        #   right need to go after all interval openning at right, so use Bisect_right\n        i, j = bl(self._X, left), br(self._X, right)\n        self._X[i : j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0)\n        \n\n    def queryRange(self, left: int, right: int) -> bool:\n        # Main logic \n        #   If idx of left/right is odd, it's in a interval. Else it's not. \n        #   If idx of left&right is the same, they're in the same interval\n        # Bisect_left vs. Bisect_right\n        #   [start, end). Start is included. End is not. \n        #   so use bisect_right for left \n        #   so use bisect_left for right \n        i, j = br(self._X, left), bl(self._X, right)\n        return i == j and i % 2 == 1\n        \n\n    def removeRange(self, left: int, right: int) -> None:\n        # Main Logic \n        #   If idx(left) is odd, the interval that contains left need to change end point to left \n        #   If idx(right) is odd, the interval that contains right need to change start point to right\n        #   Else, everything from idx(left) to idx(right) is removed. Nothing is changed. \n        # Bisect_left vs. Bisect_right\n        #   Same as addRange\n        i, j = bl(self._X, left), br(self._X, right)\n        self._X[i : j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)",
        "solution_js": "var RangeModule = function() {\n    this.ranges = []\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {void}\n */\n//Time: O(logN)\nRangeModule.prototype.addRange = function(left, right) {\n    const lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n    if (lIdx === this.ranges.length) {\n        this.ranges.push(left)\n        this.ranges.push(-right)\n    } else if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n        this.ranges.splice(lIdx, rIdx - lIdx, -right)\n    } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) {\n        this.ranges.splice(lIdx, rIdx - lIdx)\n    } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n        this.ranges.splice(lIdx, rIdx - lIdx, left, -right)\n    } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) {\n        this.ranges.splice(lIdx, rIdx - lIdx, left)   \n    }\n    return null\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {boolean}\n */\n//Time: O(logN)\nRangeModule.prototype.queryRange = function(left, right) {\n    const lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n    if (lIdx === this.ranges.length) return false\n    if (lIdx + 2 < rIdx) return false\n    if (lIdx === rIdx) {\n        return this.ranges[lIdx] < 0\n    } else if (lIdx + 1 === rIdx) {\n        return this.ranges[lIdx] === left || this.ranges[lIdx] === -right\n    } {\n        return this.ranges[lIdx] === left && Math.abs(this.ranges[lIdx + 1]) === right\n    }\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {void}\n */\n//Time: O(logN)\nRangeModule.prototype.removeRange = function(left, right) {\n    let lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n    if (lIdx === this.ranges.length) return null\n    if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n        this.ranges.splice(lIdx, rIdx - lIdx, -left)\n    } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) {\n        this.ranges.splice(lIdx, rIdx - lIdx, -left, right)\n    } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n        this.ranges.splice(lIdx, rIdx - lIdx)\n    } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) {\n        this.ranges.splice(lIdx, rIdx - lIdx, right)   \n    }\n    // console.log(this.ranges)\n    return null\n};\n\nRangeModule.prototype.findIndex = function(number) {\n    let l = 0, r = this.ranges.length\n    while(l < r) {\n        const m = l + ((r - l) >> 1)\n        if (Math.abs(this.ranges[m]) > Math.abs(number)) {\n            r = m\n        } else if (Math.abs(this.ranges[m]) < Math.abs(number)) {\n            l = m + 1\n        } else {\n            if (number < 0) {\n                l = m + 1\n            } else {\n                r = m\n            }\n        }\n    }\n    return l\n}\n\n/** \n * Your RangeModule object will be instantiated and called as such:\n * var obj = new RangeModule()\n * obj.addRange(left,right)\n * var param_2 = obj.queryRange(left,right)\n * obj.removeRange(left,right)\n */",
        "solution_java": "class RangeModule {\n    TreeMap<Integer, Integer> map;\n\n    public RangeModule() {\n        map = new TreeMap<>();\n    }\n\n    public void addRange(int left, int right) {\n        // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of right. Like this:\n        // [left, right)\n        // [l1, r1) [l2, r2)\n        // Note: l2 could be the same as l1, so they are either both null or both non-null\n        Integer l1 = map.floorKey(left);\n        Integer l2 = map.floorKey(right);\n\n        // try to visualize each case, and what to do based on r1\n        if (l1 == null && l2 == null) {\n            map.put(left, right);\n        }\n        else if (l1 != null && map.get(l1) >= left) {\n            map.put(l1, Math.max(right, map.get(l2))); // r2 will always be greater than r1, so no need to check r1\n        }\n        else {\n            map.put(left, Math.max(right, map.get(l2)));\n        }\n\n        // we don't want to remove the range starts at left, so left should be exclusive.\n        // but we want to remove the one starts at right, so right should be inclusive.\n        map.subMap(left, false, right, true).clear();\n    }\n\n    public boolean queryRange(int left, int right) {\n        Integer l = map.floorKey(left);\n        if (l != null && map.get(l) >= right) {\n            return true;\n        }\n        return false;\n    }\n\n    public void removeRange(int left, int right) {\n        Integer l1 = map.lowerKey(left); // I used lowerKey here, since we don't care about the range starting at left, as it should be removed\n        Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right\n\n        // do this first, in case l1 == l2, the later one will change r1(or r2 in this case)\n        if (l2 != null && map.get(l2) > right) {\n            map.put(right, map.get(l2));\n        }\n\n        if (l1 != null && map.get(l1) > left) {\n            map.put(l1, left);\n        }\n\n        // range that starts at left should be removed, so left is inclusive\n        // range that starts at right should be kept, so right is exclusive\n        map.subMap(left, true, right, false).clear();\n    }\n}",
        "solution_c": "/*\n    https://leetcode.com/problems/range-module/\n\n    Idea is to use a height balanced tree to save the intervals. Intervals are kept\n    according to the start point.\n    We search for the position where the given range can lie, then check the previous if it overlaps\n    and keep iterating forward while the intervals are overlapping.\n\n    QueryRange:\n    We first find the range of values in [left, right). Then for each of the overlapping intervals,\n    we subtract the common range. Finally if the entire range is covered, then the range will become zero.\n*/\nclass RangeModule {\nprivate:\n    struct Interval {\n        const bool operator<(const Interval& b) const {\n            // Important to implement for == case, otherwise intervals\n            // with same start won't exist\n            // return start < b.start || (start == b.start && end < b.end);\n\n            // This is the best way to compare since tuple already have ordering implemented for\n            // fields\n            return tie(start, end) < tie(b.start, b.end);\n        }\n\n        int start = -1, end = -1;\n        Interval(int start, int end): start(start), end(end) {};\n    };\n\n    set<Interval> intervals;\npublic:\n    RangeModule() {\n\n    }\n\n    // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all, insertion would take O(1)\n    // SC: O(1)\n    void addRange(int left, int right) {\n        Interval interval(left, right);\n        // Find the position where interval should lie st the next interval's\n        // start >= left\n        auto it = intervals.lower_bound(interval);\n\n        // check if previous overlaps, move the iterator backwards\n        if(!intervals.empty() && it != intervals.begin() && prev(it)->end >= interval.start) {\n            --it;\n            interval.start = min(it->start, interval.start);\n        }\n\n        // merge while intervals overlap\n        while(it != intervals.end() && it->start <= interval.end) {\n            interval.end = max(it->end, interval.end);\n            intervals.erase(it++);\n        }\n        intervals.insert(interval);\n    }\n\n    // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all\n    // SC: O(1)\n    bool queryRange(int left, int right) {\n        Interval interval(left, right);\n        // Range of numbers that needs to be checked\n        int range = right - left;\n        // Find the position where interval should lie st the next interval's\n        // start >= left\n        auto it = intervals.lower_bound(interval);\n\n        // check if previous interval overlaps the range, previous only\n        // covers iff the open end > start of current. [prev.start, prev.end) [left, right)\n        if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start) {\n            // remove the common portion\n            int common = min(interval.end, prev(it)->end) - interval.start;\n            range -= common;\n        }\n        // for all the following overlapping intervals, remove the common portion\n        while(it != intervals.end() && it->start <= interval.end) {\n            int common = min(interval.end, it->end) - it->start;\n            range -= common;\n            ++it;\n        }\n        // Check if the entire range was covered or not\n        return range == 0;\n    }\n\n    // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all\n    // SC: O(1)\n    void removeRange(int left, int right) {\n        Interval interval(left, right);\n        // Find the position where interval should lie st the next interval's\n        // start >= left\n        auto it = intervals.lower_bound(interval);\n\n        // check if previous overlaps, then move the iterator position backwards\n        if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start)\n            --it;\n\n        // For each of the overlapping intervals, remove the common portions\n        while(it != intervals.end() && it->start < interval.end) {\n            // Start and End of common portion\n            int common_start = max(interval.start, it->start);\n            int common_end = min(interval.end, it->end);\n\n            // only a section of interval overlaps, remove that part\n            // an overlapping interval might have to be broken into two non-overlapping parts\n            // Eg [---------------------) Bigger interval\n            // [--------) Ongoing interval\n            // [------) [-----) Original interval broken into left and right parts\n\n            // check if there is some range left on the left side\n            if(it->start < common_start)\n                intervals.insert(Interval(it->start, common_start));\n\n            // check if there is some range left on the right side\n            if(it->end > common_end)\n                intervals.insert(Interval(common_end, it->end));\n\n            // Remove the original interval\n            intervals.erase(it++);\n        }\n    }\n};\n\n/**\n * Your RangeModule object will be instantiated and called as such:\n * RangeModule* obj = new RangeModule();\n * obj->addRange(left,right);\n * bool param_2 = obj->queryRange(left,right);\n * obj->removeRange(left,right);\n */"
    },
    {
        "title": "Asteroid Collision",
        "algo_input": "We are given an array asteroids of integers representing asteroids in a row.\n\nFor each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.\n\nFind out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.\n\n&nbsp;\nExample 1:\n\nInput: asteroids = [5,10,-5]\nOutput: [5,10]\nExplanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\n\n\nExample 2:\n\nInput: asteroids = [8,-8]\nOutput: []\nExplanation: The 8 and -8 collide exploding each other.\n\n\nExample 3:\n\nInput: asteroids = [10,2,-5]\nOutput: [10]\nExplanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= asteroids.length &lt;= 104\n\t-1000 &lt;= asteroids[i] &lt;= 1000\n\tasteroids[i] != 0\n\n",
        "solution_py": "class Solution:\n    def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n        stack = []\n        for a in asteroids:\n            while stack and stack[-1] > 0 > a:\n                if stack[-1] < abs(a):\n                    stack.pop()\n                    continue\n                elif stack[-1] == abs(a):\n                    stack.pop()\n                break # this means asteroid must be destroyed (not add to stack in else statement below)\n            else:\n                stack.append(a)\n        \n        return stack",
        "solution_js": "/**\n * @param {number[]} asteroids\n * @return {number[]}\n */\nvar asteroidCollision = function(asteroids) {\n\n    const s = [];\n    for (let i = 0; i < asteroids.length; i++) {\n        const a = asteroids[i];\n\n        // Negative asteroids to the left of the stack can be ignored.\n        // They'll never collide. Let's just add it to the answer stack and\n        // move on. I consider this a special case.\n        if ((s.length === 0 || s[s.length -1] < 0) && a < 0 ) {\n            s.push(a);\n\n        // If an asteroid a is positive (l to r), it may still collide with an\n        // a negative asteroid further on in the asteroids array\n        } else if (a > 0) {\n            s.push(a);\n\n        // a is negative. It can only collide with positive ones in\n        // the stack. The following will keep on iterating\n        // until it is dealt with.\n        } else {\n            const pop = s.pop();\n\n            // positive pop beats negative a, so pick up pop\n            // and re-add it to the stack.\n            if (Math.abs(pop) > Math.abs(a)) {\n                s.push(pop);\n\n            // a has larger size than pop, so pop will get dropped\n            // and we'll retry another iteration with the same\n            // negative a asteroid and whatever the stack's state is.\n            } else if (Math.abs(pop) < Math.abs(a)) {\n                i--;\n            // magnitude of positive pop and negative a are the same\n            // so we can drop both of them.\n            } else {\n                continue;\n            }\n        }\n    }\n\n    // The stack should be the answer\n    return s;\n\n};",
        "solution_java": "/*\n0. Start iterating over the asteroid one by one.\n1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n6. Convert the stack to an array in return it.\n\n*/\nclass Solution {\n    public int[] asteroidCollision(int[] asteroids) {\n        Stack<Integer> stack = new Stack<>();\n        //0. Start iterating over the asteroid one by one.\n        for(int a : asteroids) {\n\n            //1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n            //2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n            while(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() < Math.abs(a)) {\n                stack.pop();\n            }\n\n            //3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n            if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() == Math.abs(a)) {\n                stack.pop();\n                continue;\n            }\n\n            //4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n            if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() > Math.abs(a)) {\n                continue;\n            }\n\n            //5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n            stack.push(a);\n\n        }\n\n        //6. Convert the stack to an array in return it.\n        int[] ans = new int[stack.size()];\n        int i = stack.size() - 1;\n        while(!stack.isEmpty()) {\n            ans[i] = stack.pop();\n            i--;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> asteroidCollision(vector<int>& asteroids) {\n        \n        vector<int>v;\n        stack<int>s;\n        \n        for(auto x: asteroids){\n            \n            if(x > 0) s.push(x);\n            \n            else{\n                \n                // Case 1: whem top is less than x\n                \n                while(s.size() > 0 && s.top() > 0 && s.top() < -x){\n                    s.pop();\n                }\n                \n                // case 2 : when both of same size\n                if(  s.size() > 0 && s.top()==-x) {\n                    s.pop();\n                }\n                \n                // case 3: when top is greater\n                \n                else if( s.size() > 0 && s.top() > -x ){\n                   // do nothing\n                }\n                \n                // case 4: when same direction \n                \n                else{\n                    s.push(x);\n                }\n            }\n        }\n        \n        while(!s.empty()){\n            v.push_back(s.top());\n            s.pop();\n        }\n        \n        reverse(v.begin(),v.end());\n        \n        return v;\n    }\n};"
    },
    {
        "title": "3Sum With Multiplicity",
        "algo_input": "Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i &lt; j &lt; k and arr[i] + arr[j] + arr[k] == target.\n\nAs the answer can be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput: 20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.\n\n\nExample 2:\n\nInput: arr = [1,1,2,2,2,2], target = 5\nOutput: 12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.\n\n\nExample 3:\n\nInput: arr = [2,1,3], target = 6\nOutput: 1\nExplanation: (1, 2, 3) occured one time in the array so we return 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 3000\n\t0 &lt;= arr[i] &lt;= 100\n\t0 &lt;= target &lt;= 300\n\n",
        "solution_py": "class Solution:\n    def threeSumMulti(self, arr: List[int], target: int) -> int:\n        arr.sort()\n        count = 0\n        for i in range(0, len(arr)-2):\n            rem_sum = target - arr[i]\n            hash_map = {}\n            for j in range(i+1, len(arr)):\n                if arr[j] > rem_sum:\n                    break\n                if rem_sum - arr[j] in hash_map:\n                    count = count + hash_map[rem_sum-arr[j]]\n                # update the hash_map\n                hash_map[arr[j]] = hash_map.get(arr[j], 0) + 1\n        return count % 1000000007",
        "solution_js": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nvar threeSumMulti = function(arr, target) {\n    let count=0\n    arr.sort((a,b)=>a-b)\n    for(let i=0;i<arr.length-2;i++){\n        let j=i+1,k=arr.length-1\n        while(j<k){\n            let sum=arr[i]+arr[j]+arr[k]\n            if(sum<target){\n                j++\n            }\n            else if(sum>target){\n                k--\n            }\n            else{\n                if(arr[j]!==arr[k]){\n                    let j1=j,k1=k\n                    while(arr[j]===arr[j1]){\n                        j1++\n                    }\n                    while(arr[k]===arr[k1]){\n                        k1--\n                    }\n                    count+=((j1-j)*(k-k1))\n                    j=j1\n                    k=k1\n                }\n                else{\n                    for(let n=1;n<=k-j;n++){\n                        count+=n\n                    }\n                    break\n                }\n            }\n        }\n    }\n    return count% (10**9 + 7)\n};",
        "solution_java": "class Solution {\n    public int threeSumMulti(int[] arr, int target) {\n        long[] cnt = new long[101];\n        long res = 0;\n        for (int i : arr) {\n            cnt[i]++;\n        }\n        for (int i = 0; i < 101 && i <= target; i++) {\n            if (cnt[i] == 0) {\n                continue;\n            }\n            for (int j = i; j < 101 && i + j <= target; j++) {\n                int k = target - i - j;\n                if (k < j) {\n                    break;\n                }\n                if (cnt[j] == 0 || k >= 101 || cnt[k] == 0) {\n                    continue;\n                }\n                if (i == j && j == k) {\n                    res += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 3 / 2;\n                } else if (i == j) {\n                    res += cnt[k] * cnt[j] * (cnt[j] - 1) / 2;\n                } else if (j == k) {\n                    res += cnt[i] * cnt[j] * (cnt[j] - 1) / 2;\n                } else {\n                    res += cnt[i] * cnt[j] * cnt[target - i - j];\n                }\n            }\n        }\n        return (int) (res % (Math.pow(10, 9) + 7));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int threeSumMulti(vector<int>& arr, int target) {\n        long long ans = 0;\n        int MOD = pow(10, 9) + 7;\n        \n        // step 1: create a counting array;\n        vector<long long> counting(101); // create a vector with size == 101;\n        \n        for(auto &value : arr) counting[value]++; // count the number;\n        \n        // step 2: evaluate all cases: x, y, z;\n        // case 1: x != y != z;\n        for(int x_idx = 0; x_idx < counting.size() - 2; x_idx++){\n            if(counting[x_idx] < 1) continue;\n            \n            int target_tmp = target - x_idx;\n            for(int y_idx = x_idx + 1; y_idx < counting.size() - 1; y_idx++){\n                if(counting[y_idx] < 1) continue;\n                \n                if(target_tmp - y_idx <= 100 && target_tmp - y_idx > y_idx){\n                    ans += counting[x_idx] * counting[y_idx] * counting[target_tmp - y_idx];\n                    ans %= MOD;\n                }\n            }\n        }\n        \n        // case 2: x == y != z;\n        for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){\n            if(counting[x_idx] < 2) continue;\n            \n            int target_tmp = target - 2 * x_idx;\n            if(target_tmp <= 100 && target_tmp > x_idx){\n                ans += counting[x_idx] * (counting[x_idx] - 1) / 2 * counting[target_tmp];\n                ans %= MOD;\n            }\n        }\n        \n        // case 3: x != y == z;\n        for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){\n            if(counting[x_idx] < 1) continue;\n            \n            int target_tmp = target - x_idx;\n            if(target_tmp %2 != 0) continue;\n            \n            if(target_tmp/2 <= 100 && target_tmp/2 > x_idx && counting[target_tmp/2] > 1){\n                ans += counting[x_idx] * counting[target_tmp/2] * (counting[target_tmp/2] - 1) / 2;\n                ans %= MOD;\n            }\n        }\n        \n        // case 4: x == y == z;\n        for(int x_idx = 0; x_idx < counting.size(); x_idx++){\n            if(counting[x_idx] < 3) continue;\n            \n            if(x_idx * 3 == target){\n                ans += counting[x_idx] * (counting[x_idx] - 1) * (counting[x_idx] - 2) / 6;\n                ans %= MOD;\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Crawler Log Folder",
        "algo_input": "The Leetcode file system keeps a log each time some user performs a change folder operation.\n\nThe operations are described below:\n\n\n\t\"../\" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).\n\t\"./\" : Remain in the same folder.\n\t\"x/\" : Move to the child folder named x (This folder is guaranteed to always exist).\n\n\nYou are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.\n\nThe file system starts in the main folder, then the operations in logs are performed.\n\nReturn the minimum number of operations needed to go back to the main folder after the change folder operations.\n\n&nbsp;\nExample 1:\n\n\n\nInput: logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\nOutput: 2\nExplanation: Use this change folder operation \"../\" 2 times and go back to the main folder.\n\n\nExample 2:\n\n\n\nInput: logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\nOutput: 3\n\n\nExample 3:\n\nInput: logs = [\"d1/\",\"../\",\"../\",\"../\"]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= logs.length &lt;= 103\n\t2 &lt;= logs[i].length &lt;= 10\n\tlogs[i] contains lowercase English letters, digits, '.', and '/'.\n\tlogs[i] follows the format described in the statement.\n\tFolder names consist of lowercase English letters and digits.\n\n",
        "solution_py": "class Solution:\n    def minOperations(self, logs: List[str]) -> int:\n        m='../'\n        r='./'\n\t\t#create an empty stack\n        stk=[]\n\t\t#iterate through the list\n        for i in logs:\n\t\t\t#if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack\n            if(i==m):\n                if(len(stk)>0):\n                    stk.pop()\n\t\t\t#else if Remain in the same folder (./) operator occurs, do nothing and move to next element in list\n            elif(i==r):\n                continue\n\t\t\t#else add element to the stack\n            else:\n                stk.append(i)\n\t\t#now return the size of the stack which would be the minimum number of operations needed to go back to the main folder\n        return(len(stk))\n\t\t```",
        "solution_js": "var minOperations = function(logs) {\n    let count = 0;\n    for(i=0;i<logs.length;i++){\n        if(logs[i] === '../') {\n            if(count > 0)  count = count - 1;\n            continue\n        }\n        if(logs[i] === './') continue;\n        else count = count + 1;\n    }\n    return count\n};",
        "solution_java": "class Solution {\n    public int minOperations(String[] logs) {\n         var stack = new Stack<String>();\n        for(var log : logs){\n            if(log.equals(\"../\")){\n                if(!stack.empty())\n                    stack.pop();\n            }else if(log.equals(\"./\")){\n\n            }else{\n                stack.push(log);\n            }\n        }\n        return stack.size();\n    }\n}",
        "solution_c": "//1.using stack\nclass Solution {\npublic:\n    int minOperations(vector<string>& logs) {\n\t\n        if(logs.size()==0) return 0;\n\t\t\n        stack<string> st;\n        for(auto x: logs){\n            if (x[0] != '.')  //Move to the child folder so add children\n                st.push(x);\n            else if(x==\"../\"){ // Move to the parent folder of the current folder so pop\n                 if(!st.empty())  st.pop(); \n                 else continue; //don’t move the pointer beyond the main folder.\n            }\n        }\n        return st.size();\n    }\n};\n//2.\nclass Solution {\npublic:\n    int minOperations(vector<string>& logs) {\n         int ans = 0;\n        for (string log : logs) {\n            if (log == \"../\") { // go deeper\n                ans--; \n                ans = max(ans, 0);\n            } else if (log != \"./\") // one level up\n\t\t\t   ans++; \n        }\n        return ans;\n    }\n};\n//3.\nclass Solution {\npublic:\n    int minOperations(vector<string>& logs) {\n        int res = 0;\n        for (string s : logs) {\n            if (s==\"../\") res = max(0, --res);\n            else if (s==\"./\") continue;\n            else res++;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Single Number",
        "algo_input": "Given a non-empty&nbsp;array of integers nums, every element appears twice except for one. Find that single one.\n\nYou must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.\n\n&nbsp;\nExample 1:\nInput: nums = [2,2,1]\nOutput: 1\nExample 2:\nInput: nums = [4,1,2,1,2]\nOutput: 4\nExample 3:\nInput: nums = [1]\nOutput: 1\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-3 * 104 &lt;= nums[i] &lt;= 3 * 104\n\tEach element in the array appears twice except for one element which appears only once.\n\n",
        "solution_py": "class Solution:\n    def singleNumber(self, nums: List[int]) -> int:\n        nums.sort()\n        i=0\n        while i<len(nums)-1:\n            if nums[i]==nums[i+1]:\n                i+=2\n            else:\n                return nums[i]\n\n        return nums[-1]",
        "solution_js": "var singleNumber = function(nums) {\n    let s = 0; // Location of first possible suspect\n    for (let i = s + 1; i < nums.length; i++) {\n        if (nums[i] == nums[s]) { // If we found a duplicate\n            nums.splice(i, 1); // Remove duplicate so it won't confuse us next time we come across it\n            s++; // Next suspect's location\n            i = s; // Start of next search (i=s+1 in next loop iteration)\n        }\n    }\n    return nums[s];\n};",
        "solution_java": "class Solution {\n    public int singleNumber(int[] nums) {\n        Stack numStack = new Stack();\n        Arrays.sort(nums);\n        for (var i = 0; i < nums.length; ++i) {\n            numStack.push(nums[i]);\n            if (i < nums.length - 1 && nums[++i] != (int) numStack.peek()) break;\n        }\n        return (int) numStack.pop();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int singleNumber(vector<int>& nums) { \n       unordered_map<int,int> a;\n\t   for(auto x: nums)\n\t\t   a[x]++;\n\t   for(auto z:a)\n\t\t   if(z.second==1)\n\t\t\t   return z.first;\n\t   return -1;\n    }\n};"
    },
    {
        "title": "Find the Shortest Superstring",
        "algo_input": "Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.\n\nYou may assume that no string in words is a substring of another string in words.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"alex\",\"loves\",\"leetcode\"]\nOutput: \"alexlovesleetcode\"\nExplanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n\n\nExample 2:\n\nInput: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\nOutput: \"gctaagttcatgcatc\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 12\n\t1 &lt;= words[i].length &lt;= 20\n\twords[i] consists of lowercase English letters.\n\tAll the strings of words are unique.\n\n",
        "solution_py": "class Solution:\n    def shortestSuperstring(self, A):\n        @lru_cache(None)\n        def suffix(i,j):\n            for k in range(min(len(A[i]),len(A[j])),0,-1):\n                if A[j].startswith(A[i][-k:]):\n                    return A[j][k:]\n            return A[j]\n        n = len(A)\n        @lru_cache(None)\n        def dfs(bitmask, i):\n            if bitmask + 1 == 1 << n: return \"\"\n            return min([suffix(i, j)+dfs(bitmask | 1<<j, j) for j in range(n) if not(bitmask & 1<<j)], key = len)\n        return min([A[i]+dfs(1<<i,i) for i in range(n)], key = len)",
        "solution_js": "var shortestSuperstring = function(words) {\n    let N = words.length, suffixes = new Map(),\n        edges = Array.from({length: N}, () => new Uint8Array(N))\n\n    // Build the edge graph\n    for (let i = 0, word = words; i < N; i++) {\n        let word = words[i]\n        for (let k = 1; k < word.length; k++) {\n            let sub = word.slice(k)\n            if (suffixes.has(sub)) suffixes.get(sub).push(i)\n            else suffixes.set(sub, [i])\n        }\n    }\n    for (let j = 0; j < N; j++) {\n        let word = words[j]\n        for (let k = 1; k < word.length; k++) {\n            let sub = word.slice(0,k)\n            if (suffixes.has(sub))\n                for (let i of suffixes.get(sub))\n                    edges[i][j] = Math.max(edges[i][j], k)\n        }\n    }\n\n    // Initialize DP array\n    let M = N - 1,\n        dp = Array.from({length: M}, () => new Uint16Array(1 << M))\n\n    // Helper function to find the best value for dp[curr][currSet]\n    // Store the previous node with bit manipulation for backtracking\n    const solve = (curr, currSet) => {\n        let prevSet = currSet - (1 << curr), bestOverlap = 0, bestPrev\n        if (!prevSet) return (edges[M][curr] << 4) + M\n        for (let prev = 0; prev < M; prev++)\n            if (prevSet & 1 << prev) {\n                let overlap = edges[prev][curr] + (dp[prev][prevSet] >> 4)\n                if (overlap >= bestOverlap)\n                    bestOverlap = overlap, bestPrev = prev\n            }\n        return (bestOverlap << 4) + bestPrev\n    }\n\n    // Build DP using solve\n    for (let currSet = 1; currSet < 1 << M; currSet++)\n        for (let curr = 0; curr < N; curr++)\n            if (currSet & 1 << curr)\n                dp[curr][currSet] = solve(curr, currSet)\n\n    // Join the ends at index M\n    let curr = solve(M, (1 << N) - 1) & (1 << 4) - 1\n\n    // Build the circle by backtracking path info from dp\n    // and find the best place to cut the circle\n    let path = [curr], currSet = (1 << M) - 1,\n        bestStart = 0, lowOverlap = edges[curr][M], prev\n    while (curr !== M) {\n        prev = dp[curr][currSet] & (1 << 4) - 1, currSet -= 1 << curr\n        let overlap = edges[prev][curr]\n        if (overlap < lowOverlap)\n            lowOverlap = overlap, bestStart = N - path.length\n        curr = prev, path.unshift(curr)\n    }\n\n    // Build and return ans by cutting the circle at bestStart\n    let ans = []\n    for (let i = bestStart; i < bestStart + M; i++) {\n        let curr = path[i%N], next = path[(i+1)%N], word = words[curr]\n        ans.push(word.slice(0, word.length - edges[curr][next]))\n    }\n    ans.push(words[path[(bestStart+M)%N]])\n    return ans.join(\"\")\n};",
        "solution_java": "class Solution {\n    public String shortestSuperstring(String[] words) {\n        int n = words.length;\n        int[][] discount = new int[n][n];\n        for (int i = 0; i < n; i++){\n            for (int j = 0; j < n; j++){\n                for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->j and j->i\n                    if (words[j].startsWith(words[i].substring(k))){\n                        discount[i][j]=words[i].length()-k;\n                        break;\n                    }\n                }\n            }\n        }\n        int[][] dp = new int[1<<n][n];\n        int[][] path = new int[1<<n][n];\n        for (int i = 0; i < 1<<n; i++){ // find the max discount for mask (1<<n)-1 with dp\n            for (int j = 0; j < n; j++){\n                for (int k = 0; k < n && (i&1<<j)>0; k++){\n                    if ((i&1<<k)==0 && dp[i][j]+discount[j][k]>=dp[i|1<<k][k]){\n                        dp[i|1<<k][k]=dp[i][j]+discount[j][k];\n                        path[i|1<<k][k]=j;\n                    }\n                }\n            }\n        }\n        int m = (1<<n)-1, idx = n; // build the path from end to start\n        int end=IntStream.range(0,n).reduce((a,b)->dp[(1<<n)-1][a]>dp[(1<<n)-1][b]?a:b).getAsInt();\n        String[] ans = new String[n];\n        while(m>0){\n            ans[--idx]=words[end].substring((m&(m-1))==0?0:discount[path[m][end]][end]);\n            m^=1<<end;\n            end=path[m|1<<end][end];\n        }\n        return String.join(\"\",ans);\n    }\n}",
        "solution_c": "vector<vector<int> > dp,pre,par;\n\nbool startWith(string s, string t)\n{\n// returns true if string s starts with string t\n    int i;\n    for(i=0; i<s.length()&&i<t.length(); i++)\n    {\n        if(s[i]==t[i])\n            continue;\n        else\n            return false;\n    }\n    if(i==t.length())\n        return true;\n    else\n        return false;\n}\n\nint calc(string A, string B)\n{\n // calculate the number of extra characters required to be appended to A\n // if A is followed by B\n // for eg. calc(\"abcd\",\"cdef\") = 2\n \n    int a=A.length(),b=B.length();\n    for(int i=0; i<a; i++)\n    {\n        if(a-i<=b&&startWith(B,A.substr(i)))\n        {\n            return b-(a-i); \n        }\n    }\n    return b;\n}\n\nint finalMask,n;\n\nint helper(int mask, int last)\n{\n // returns the minimum length of string required if last string appended was A[last] \n // the sets bit in mask represents the strings that were already appended to the final string\n \n    if(mask==finalMask)  // all strings are appended in final string\n        return 0;\n\n    if(dp[mask][last]!=-1) // memoization\n        return dp[mask][last];\n        \n    int mn=INT_MAX;\n    int p;\n    for(int i=0; i<n; i++)\n    {\n        if(mask&(1<<i))\n            continue;\n        int cost=pre[last][i]+helper(mask|(1<<i),i);  // extra characters need to be appended\n        if(cost<mn)\n        {\n            mn=cost;\n            p=i;\n        }\n    }\n    par[mask][last]=p;  // store parent, so that it is easy to traceback and find the final result\n    return dp[mask][last]=mn; // store result in DP table\n}\n\n\n\nclass Solution {\npublic:\n    string shortestSuperstring(vector<string>& A) {\n    n=A.size();\n    pre.assign(n,vector<int>(n));  // for pre-computing calc(a,b) for all pairs of strings\n    par.assign(1<<n,vector<int>(n,-1));    \n    for(int i=0; i<n; i++)\n    {\n        for(int j=0; j<n; j++)\n        {\n            if(j==i)\n                continue;\n            pre[i][j]=calc(A[i],A[j]);\n        }\n    }\n    finalMask=(1<<n)-1;  \n    dp.assign(1<<n,vector<int>(n,-1));\n    int len=INT_MAX;  // len will contain minimum length of required string\n    int ind;\n    for(int i=0; i<n; i++)\n    {\n        int prev=len;\n        len=min(len, (int)A[i].length()+helper(1<<i,i));\n        if(len!=prev)\n        {\n            ind=i;\n        }\n    }\n\n // Now traceback to find the final answer\n    string ans=A[ind];\n    int msk=1<<ind;\n    int prev_ind=ind;\n    ind=par[msk][ind];\n    while(ind!=-1)\n    {\n        len=pre[prev_ind][ind];\n        int alen=A[ind].length();\n        ans+=A[ind].substr(alen-len,len);            \n        msk=msk^(1<<ind);\n        prev_ind=ind;\n        ind=par[msk][ind];  \n    }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Path Cost in a Grid",
        "algo_input": "You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x &lt; m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row.\n\nEach possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored.\n\nThe cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]\nOutput: 17\nExplanation: The path with the minimum possible cost is the path 5 -&gt; 0 -&gt; 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.\n\n\nExample 2:\n\nInput: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]\nOutput: 6\nExplanation: The path with the minimum possible cost is the path 2 -&gt; 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t2 &lt;= m, n &lt;= 50\n\tgrid consists of distinct integers from 0 to m * n - 1.\n\tmoveCost.length == m * n\n\tmoveCost[i].length == n\n\t1 &lt;= moveCost[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n        max_row, max_col = len(grid), len(grid[0])\n        dp = [[-1] * max_col for _ in range(max_row)] \n\n        def recursion(row, col):\n            if row == max_row - 1: # If last row then return nodes value\n                return grid[row][col]\n            if dp[row][col] == -1: # If DP for this node is not computed then we will do so now.\n                current = grid[row][col] # Current Node Value\n                res = float('inf') # To store best path from Current Node\n                for c in range(max_col): # Traverse all path from Current Node\n                    val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value\n                    res = min(res, val)\n                dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val\n            return dp[row][col]\n\n        for c in range(max_col):\n            recursion(0, c) # Start recursion from all nodes in 1st row\n        return min(dp[0]) # Return min value from 1st row",
        "solution_js": "var minPathCost = function(grid, moveCost) {\n    const rows = grid.length;\n    const cols = grid[0].length;\n\n    const cache = [];\n    \n    for (let i = 0; i < rows; i++) {\n        cache.push(Array(cols).fill(null));\n    }\n    \n    function move(row, col) {\n        const val = grid[row][col];\n        \n        if (cache[row][col] !== null) {\n            return cache[row][col];\n        }\n        \n        if (row === rows - 1) {\n            return val;\n        }\n        \n        let ans = Number.MAX_SAFE_INTEGER;\n\n        for (let i = 0; i < cols; i++) {\n            const addCost = moveCost[val][i];\n\n            ans = Math.min(ans, move(row + 1, i) + val + addCost);\n        }\n        \n        cache[row][col] = ans;\n        \n        return ans;\n    }\n\n    let ans = Number.MAX_SAFE_INTEGER;\n    \n    for (let i = 0; i < cols; i++) {\n        ans = Math.min(ans, move(0, i));\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    Integer dp[][];\n    public int minPathCost(int[][] grid, int[][] moveCost) \n    {\n        dp=new Integer[grid.length][grid[0].length];\n        int ans=Integer.MAX_VALUE;\n       \n        for(int i=0;i<grid[0].length;i++)\n        {\n            ans=Math.min(ans,grid[0][i]+helper(grid,moveCost,grid[0][i],1));\n        }\n        return ans;\n    }\n    public int helper(int[][] grid,int[][] moveCost,int cur,int i)\n    {\n        if(i==grid.length)\n        {\n            return 0;\n        }\n        int ans=Integer.MAX_VALUE;\n        for(int k=0;k<grid[0].length;k++)\n        {\n            int a=Integer.MAX_VALUE;\n            if(dp[i][k]!=null)\n            {\n                a=dp[i][k];\n            }\n            else\n            {\n                a=helper(grid,moveCost,grid[i][k],i+1);\n                dp[i][k]=a;\n            }\n            ans=Math.min(grid[i][k]+moveCost[cur][k]+a,ans);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(vector<vector<int>> &grid,vector<vector<int>>& moveCost,int i,int j,int n,int m){\n        if(i==n-1){\n            return grid[i][j];\n        }\n        int ans=INT_MAX;\n        for(int k=0;k<m;k++){\n            ans=min(ans,grid[i][j]+moveCost[grid[i][j]][k]+solve(grid,moveCost,i+1,k,n,m));\n        }\n        return ans;\n    }\n    int minPathCost(vector<vector<int>>& grid, vector<vector<int>>& moveCost) {\n        int ans=INT_MAX;\n        int n=grid.size();\n        int m=grid[0].size();\n        for(int i=0;i<m;i++){\n            ans=min(ans,solve(grid,moveCost,0,i,n,m));\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Prime Number of Set Bits in Binary Representation",
        "algo_input": "Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.\n\nRecall that the number of set bits an integer has is the number of 1's present when written in binary.\n\n\n\tFor example, 21 written in binary is 10101, which has 3 set bits.\n\n\n&nbsp;\nExample 1:\n\nInput: left = 6, right = 10\nOutput: 4\nExplanation:\n6  -&gt; 110 (2 set bits, 2 is prime)\n7  -&gt; 111 (3 set bits, 3 is prime)\n8  -&gt; 1000 (1 set bit, 1 is not prime)\n9  -&gt; 1001 (2 set bits, 2 is prime)\n10 -&gt; 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.\n\n\nExample 2:\n\nInput: left = 10, right = 15\nOutput: 5\nExplanation:\n10 -&gt; 1010 (2 set bits, 2 is prime)\n11 -&gt; 1011 (3 set bits, 3 is prime)\n12 -&gt; 1100 (2 set bits, 2 is prime)\n13 -&gt; 1101 (3 set bits, 3 is prime)\n14 -&gt; 1110 (3 set bits, 3 is prime)\n15 -&gt; 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= left &lt;= right &lt;= 106\n\t0 &lt;= right - left &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def countPrimeSetBits(self, left: int, right: int) -> int:\n        primes = {2, 3, 5, 7, 11, 13, 17, 19}\n        return sum(bin(n).count('1') in primes for n in range(left, right + 1))",
        "solution_js": "/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar countPrimeSetBits = function(L, R) {\n  let set = new Set([2, 3, 5, 7, 11, 13, 17, 19]);\n  let countPrime = 0;\n  \n  for (let i = L; i <= R; i++) {\n    if (set.has(i.toString(2).replace(/0/g, '').length)) countPrime++;\n  }\n\n  return countPrime;\n};",
        "solution_java": "class Solution {\n     public int calculateSetBits(String s){\n        int count=0;\n        for (int i = 0; i < s.length(); i++) {\n            if(s.charAt(i)=='1') count++;\n        }\n        return count;\n    }\n\n    public boolean isPrime(int n){\n        if (n==0 || n==1) return false;\n        for (int i = 2; i <= n/2; i++) {\n            if(n%i ==0 ) return false;\n        }\n// System.out.println(n+\" - \");\n        return true;\n    }\n\n    public int countPrimeSetBits(int left, int right) {\n        int count=0;\n        for(int i=left;i<=right;i++){\n            String b= Integer.toBinaryString(i);\n\n            int n=calculateSetBits(b);\n\n            if(isPrime(n)) count++;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPrimeSetBits(int left, int right) {\n        int ans=0;\n        while(left<=right) {\n            int cnt=__builtin_popcount(left);\n            if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n                ++ans;\n            ++left;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Partition Array Into Three Parts With Equal Sum",
        "algo_input": "Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.\n\nFormally, we can partition the array if we can find indexes i + 1 &lt; j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])\n\n&nbsp;\nExample 1:\n\nInput: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput: true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n\n\nExample 2:\n\nInput: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput: false\n\n\nExample 3:\n\nInput: arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput: true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 5 * 104\n\t-104 &lt;= arr[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def canThreePartsEqualSum(self, arr: List[int]) -> bool:\n        total = sum(arr)\n        if total % 3 != 0:\n            return False\n        ave = total // 3\n        stage = 0\n        add = 0\n        for i in arr[:-1]:\n            add += i\n            if add == ave:\n                stage +=1\n                add = 0\n            if stage == 2:\n                return True\n        return False",
        "solution_js": "var canThreePartsEqualSum = function(arr) {\n    const length = arr.length;\n    let sum =0, count = 0, partSum = 0;\n    for(let index = 0; index < length; index++) {\n        sum += arr[index];\n    }\n    if(sum%3 !== 0) return false;\n    partSum = sum/3;\n    sum = 0;\n    for(let index = 0; index < length; index++) {\n        sum += arr[index];\n        if(sum === partSum){\n            count++;\n            sum = 0;\n            if(count == 2 && index < length-1) return true;\n        }\n    }\n    return false;\n};",
        "solution_java": "class Solution { \n     public boolean canThreePartsEqualSum(int[] arr) {\n        int sum = 0;\n        \n        for (Integer no : arr) {\n            sum += no;\n        }\n        if (sum % 3 != 0) {\n            return false;\n        }\n        sum = sum / 3;\n        int tempSum = 0;\n        int count = 0;\n\n        for (int i = 0; i < arr.length; i++) {\n            tempSum += arr[i];\n            if (tempSum == sum) {\n                count++;\n                tempSum = 0;\n            }\n        }\n\n        return count >= 3;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool canThreePartsEqualSum(vector<int>& arr) {\n\t\tint sum=0;\n\t\tfor(auto i : arr)\n\t\t\tsum+=i;\n\t\tif(sum%3!=0)\n\t\t\treturn false;   //partition not possible\n\t\tint part=sum/3,temp=0,found=0;\n\t\tfor(int i=0;i<arr.size();i++){\n\t\t\ttemp+=arr[i];\n\t\t\tif(temp==part){\n\t\t\t\ttemp=0;\n\t\t\t\tfound++;\n\t\t\t}\n\t\t}\n\t\treturn found>=3 ? true : false;\n\t}\n};\n\nfeel free to ask your doubts :)\nand pls upvote if it was helpful :)"
    },
    {
        "title": "Minimum Genetic Mutation",
        "algo_input": "A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.\n\nSuppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.\n\n\n\tFor example, \"AACCGGTT\" --&gt; \"AACCGGTA\" is one mutation.\n\n\nThere is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.\n\nGiven the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.\n\nNote that the starting point is assumed to be valid, so it might not be included in the bank.\n\n&nbsp;\nExample 1:\n\nInput: start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput: 1\n\n\nExample 2:\n\nInput: start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput: 2\n\n\nExample 3:\n\nInput: start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tstart.length == 8\n\tend.length == 8\n\t0 &lt;= bank.length &lt;= 10\n\tbank[i].length == 8\n\tstart, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].\n\n",
        "solution_py": "class Solution:\n    def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n        q = deque()\n        q.append(start)\n        n = len(bank)\n        last = 0\n        used = [False] * n\n        for i, x in enumerate(bank):\n            if start == x:\n                used[i] = True\n            if end == x:\n                last = i\n        dist = 0\n        while q:\n            dist += 1\n            for _ in range(len(q)):\n                w = q.popleft()\n                for i, x in enumerate(bank):\n                    if used[i]:\n                        continue\n                    bad = 0\n                    for j in range(8):\n                        if w[j] != x[j]:\n                            bad += 1\n                            if bad == 2:\n                                break\n                    if bad == 1:\n                        if last == i:\n                            return dist\n                        used[i] = True\n                        q.append(x)\n        return -1",
        "solution_js": "/**\n * @param {string} start\n * @param {string} end\n * @param {string[]} bank\n * @return {number}\n */\nvar minMutation = function(start, end, bank) {\n    if(start.length!=end.length || !contains(end,bank)){\n            return -1;\n        }\n        return bfs(start,end,bank);\n    };\n    function contains(end,bank){\n        for(const x of bank){\n            if(x==end){\n                return true;\n            }\n        }\n        return false;\n    }\n    function convertPossible(a,b){\n        if(a.length != b.length) return false;\n        let count=0;\n        for(let i=0;i<a.length;i++){\n            if(a[i]!=b[i]){\n                count++;\n            }\n        }\n        return count==1;\n    }\n    function bfs(start,end,bank){\n        let count=0;\n        let q=[];\n        let set=new Set();\n        q.push(start);\n\n        while(q.length>0){\n            let size=q.length;\n\n            for(let i=0;i<size;i++){\n                let curr=q.shift();\n\n                if(curr==end){\n                    return count;\n                }\n                bank.forEach((x)=>{\n                    if(convertPossible(curr,x) && !set.has(x)){\n                        q.push(x);\n                        set.add(x);\n                    }\n                })\n            }\n            count++;\n        }\n        return -1;\n    }",
        "solution_java": "class Solution {\n    public int minMutation(String start, String end, String[] bank) {\n        Set<String> set = new HashSet<>();\n        for(String tmp: bank){\n            set.add(tmp);\n        }\n        if(!set.contains(end)) return -1;\n        if(start.equals(end)) return 0;\n        char[] var = {'A','C','G','T'};\n        Queue<String> q = new LinkedList<>();\n        q.add(start);\n        int count = 0;\n        while(!q.isEmpty()){\n            int size = q.size();\n            for(int i = 0; i < size; i ++){\n                String str = q.poll();\n                char[] tmp = str.toCharArray();\n                if(str.equals(end)) return count;\n                for(int j = 0; j < 8; j ++){\n                    char ch = tmp[j];\n                    for(int k = 0; k < 4; k ++){\n                        tmp[j] = var[k];\n                        String node = new String(tmp);\n                        if(set.contains(node)){\n                            q.add(node);\n                            set.remove(node);\n                        }\n                    }\n                    tmp[j] = ch;\n                }\n            }\n            count++;\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMutation(string start, string end, vector<string>& bank) {\n        unordered_set<string> st(bank.begin(), bank.end());\n        if (st.find(end) == st.end()) return -1;\n        \n        queue<string> q;\n        q.push(start);\n        \n        unordered_set<string> vis;\n        vis.insert(start);\n        \n        int res=0;\n        while (not q.empty()) {\n            int sz = q.size();\n            \n            while (sz--) {\n                string currString = q.front(); q.pop();\n                if (currString == end) return res;\n                \n                for (int i=0;i<currString.size();i++) {\n                    string temp = currString;\n                    for (auto g: string(\"ATGC\")) {\n                        temp[i] = g;\n                        if (st.find(temp) != st.end() and (vis.find(temp) == vis.end())) {\n                            q.push(temp);\n                            vis.insert(temp);\n                        }\n                    }\n                }\n            }\n            res++;\n        }\n        \n        return -1;\n    }\n};"
    },
    {
        "title": "Move Zeroes",
        "algo_input": "Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\nNote that you must do this in-place without making a copy of the array.\n\n&nbsp;\nExample 1:\nInput: nums = [0,1,0,3,12]\nOutput: [1,3,12,0,0]\nExample 2:\nInput: nums = [0]\nOutput: [0]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\n\n&nbsp;\nFollow up: Could you minimize the total number of operations done?",
        "solution_py": "class Solution:\n    def moveZeroes(self, nums: List[int]) -> None:\n        \"\"\"\n        Do not return anything, modify nums in-place instead.\n\n        \"\"\"\n        notzero = 0\n        zero = 0\n\n        while notzero < len(nums):\n            if nums[notzero] != 0:\n                nums[zero] , nums[notzero] = nums[notzero], nums[zero]\n                zero += 1\n            notzero += 1",
        "solution_js": "var moveZeroes = function(nums) {\n    let lastNonZeroNumber = 0;\n\n    //Moves all the non zero numbers at the start of the array\n    for(let i=0; i<nums.length;i++){\n       if(nums[i] !=0){\n           nums[lastNonZeroNumber] = nums[i];\n           lastNonZeroNumber++;\n       }\n    }\n\n    //Moves all the zeroes replaced from last non zero number found\n    //to the end of array\n    for(let i = lastNonZeroNumber; i<nums.length;i++){\n        nums[i] =0;\n    }\n\n};",
        "solution_java": "class Solution {\n    public void moveZeroes(int[] nums) {\n       int a = 0, z = 0, temp;\n        while(a < nums.length){\n            if(nums[a] != 0){\n                temp = nums[z];\n                nums[z] = nums[a];\n                nums[a] = temp; \n                z += 1;\n            }\n            a += 1;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void moveZeroes(vector<int>& nums) {\n        int nums_size = nums.size();\n        int cntr=0;\n\n        for(int i=0;i<nums_size;i++)\n        {\n            if(nums[i] != 0)\n            {\n                nums[cntr] = nums[i];\n                cntr++;\n            }\n        }\n        for( int i=cntr;i<nums_size;i++)\n        {\n            nums[i] = 0;\n        }\n    }\n};"
    },
    {
        "title": "Reverse Linked List",
        "algo_input": "Given the head of a singly linked list, reverse the list, and return the reversed list.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5]\nOutput: [5,4,3,2,1]\n\n\nExample 2:\n\nInput: head = [1,2]\nOutput: [2,1]\n\n\nExample 3:\n\nInput: head = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is the range [0, 5000].\n\t-5000 &lt;= Node.val &lt;= 5000\n\n\n&nbsp;\nFollow up: A linked list can be reversed either iteratively or recursively. Could you implement both?\n",
        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if head==None or head.next==None:\n            return head\n        p = None\n        while(head != None):\n            temp = head.next\n            head.next = p\n            p = head\n            head = temp\n        return p",
        "solution_js": "var reverseList = function(head) {\n    \n    //  Iteratively\n    [cur, rev, tmp] = [head, null, null]\n    while(cur){\n        tmp = cur.next;\n        cur.next = rev;\n        rev = cur;\n        cur = tmp;\n        //[current.next, prev, current] = [prev, current, current.next]\n    }\n}",
        "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public ListNode reverseList(ListNode head) {\n\n        if(head == null || head.next == null) return head;\n\n        ListNode curr = head;\n        ListNode temp = null, next = curr.next;\n        curr.next = null;\n\n        while(curr !=null && next !=null)\n        {\n            // before cutting off link between next & its next, save next.next\n            temp = next.next;\n            // let next point to curr\n            next.next = curr;\n\n            curr = next;\n            next = temp;\n\n        }\n\n        return curr;\n\n    }\n}",
        "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* reverseList(ListNode* head) {\n        if(head==NULL||head->next==NULL)\n        {\n            return head;\n        }\n        ListNode *s=reverseList(head->next);\n        ListNode *t=head->next;\n            t->next=head;\n        head->next=NULL;\n        return s;\n        \n    }\n};"
    },
    {
        "title": "Two Out of Three",
        "algo_input": "Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput: [3,2]\nExplanation: The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.\n\n\nExample 2:\n\nInput: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput: [2,3,1]\nExplanation: The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.\n\n\nExample 3:\n\nInput: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput: []\nExplanation: No value is present in at least two arrays.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length, nums3.length &lt;= 100\n\t1 &lt;= nums1[i], nums2[j], nums3[k] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n        output = []\n        for i in nums1:\n            if i in nums2 or i in nums3:\n                if i not in output:\n                    output.append(i)\n        for j in nums2:\n            if j in nums3 or j in nums1:\n                if j not in output:\n                    output.append(j)\n        return output",
        "solution_js": "var twoOutOfThree = function(nums1, nums2, nums3) {\n    let newArr = [];\n    newArr.push(...nums1.filter(num => nums2.includes(num) || nums3.includes(num)))\n    newArr.push(...nums2.filter(num => nums1.includes(num) || nums3.includes(num)))\n    return Array.from(new Set(newArr))\n};",
        "solution_java": "class Solution {\n    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {\n        int[] bits = new int[101];\n        for (int n : nums1) bits[n] |= 0b110;\n        for (int n : nums2) bits[n] |= 0b101;\n        for (int n : nums3) bits[n] |= 0b011;\n        List<Integer> result = new ArrayList();\n        for (int i = bits.length - 1; i > 0; i--)\n            if (bits[i] == 0b111)\n                result.add(i);\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {\n        vector<int>f(110, 0);\n        for (int n : nums1) f[n] |= 1<<0;\n        for (int n : nums2) f[n] |= 1<<1;\n        for (int n : nums3) f[n] |= 1<<2;\n        \n        vector<int>ret;\n        for (int i = 1; i <= 100; i++) if (f[i] == 3 || f[i] >= 5) ret.push_back(i);\n        return ret;\n    }\n};"
    },
    {
        "title": "Trim a Binary Search Tree",
        "algo_input": "Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.\n\nReturn the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,0,2], low = 1, high = 2\nOutput: [1,null,2]\n\n\nExample 2:\n\nInput: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput: [3,2,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t0 &lt;= Node.val &lt;= 104\n\tThe value of each node in the tree is unique.\n\troot is guaranteed to be a valid binary search tree.\n\t0 &lt;= low &lt;= high &lt;= 104\n\n",
        "solution_py": "class Solution:\n\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\tif not root: return root\n\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\troot.left = self.trimBST(root.left, low, high)\n\t\troot.right = self.trimBST(root.right, low, high)\n\t\treturn root",
        "solution_js": "var trimBST = function(root, low, high) {\n    if(!root) return null;\n    const { val, left, right } = root;\n    if(val < low) return trimBST(root.right, low, high);\n    if(val > high) return trimBST(root.left, low, high);\n    \n    root.left = trimBST(root.left, low, high);\n    root.right = trimBST(root.right, low, high);\n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode trimBST(TreeNode root, int low, int high) {\n        if (root == null) return root;\n        while (root.val < low || root.val > high) {\n            root = root.val < low ? root.right : root.left;\n            if (root == null)\n                return root;\n        }\n        root.left = trimBST(root.left, low, high);\n        root.right = trimBST(root.right, low, high);\n        return root;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* trimBST(TreeNode* root, int low, int high) {\n        if(!root) return NULL;\n        \n        root->left = trimBST(root->left, low, high);\n        root->right = trimBST(root->right, low, high);\n        \n        if(root->val < low){\n            if(root->right){\n                TreeNode* temp = root;\n                // delete root;\n                return temp->right;\n            }else{\n                return NULL;\n            }\n        }\n        if(root->val > high){\n            if(root->left){\n                TreeNode* temp = root;\n                // delete root;\n                return temp->left;\n            }else{\n                return NULL;\n            }\n        }\n        return root;\n    }\n};"
    },
    {
        "title": "Sliding Window Maximum",
        "algo_input": "You are given an array of integers&nbsp;nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.\n\nReturn the max sliding window.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation: \nWindow position                Max\n---------------               -----\n[1  3  -1] -3  5  3  6  7       3\n 1 [3  -1  -3] 5  3  6  7       3\n 1  3 [-1  -3  5] 3  6  7       5\n 1  3  -1 [-3  5  3] 6  7       5\n 1  3  -1  -3 [5  3  6] 7       6\n 1  3  -1  -3  5 [3  6  7]      7\n\n\nExample 2:\n\nInput: nums = [1], k = 1\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\t1 &lt;= k &lt;= nums.length\n\n",
        "solution_py": "class Solution:\n    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n        ans = []\n        pq = []\n\n        for i in range(k): heapq.heappush(pq,(-nums[i],i))\n\n        ans.append(-pq[0][0])\n\n        for i in range(k,len(nums)):\n            heapq.heappush(pq,(-nums[i],i))\n            while pq and pq[0][1] < i-k+1 : heapq.heappop(pq)\n            ans.append(-pq[0][0])\n\n        return ans",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar maxSlidingWindow = function(nums, k) {\n    var i=0, j=0, max=0, deque=[], output=[];\n    while(j<nums.length){\n        if(deque.length === 0){\n            deque.push(nums[j])\n        }else if(deque[deque.length-1] > nums[j]){\n            deque.push(nums[j])\n        }else{\n            while(deque[deque.length-1] < nums[j]){\n                deque.pop()\n            }\n            deque.push(nums[j])\n        }\n\n        if(j-i+1 === k){\n            if(nums[i] === deque[0]){\n                output.push(deque.shift());\n            }else{\n                output.push(deque[0])\n            }\n            i++;\n        }\n        j++;\n\n    }\n    return output\n};",
        "solution_java": "class Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        Deque<Integer> queue = new LinkedList<>();\n        int l = 0, r = 0;\n        int[] res = new int[nums.length - k + 1];\n        int index = 0;\n        while (r < nums.length) {\n            int n = nums[r++];\n            while (!queue.isEmpty() && n > queue.peekLast()) {\n                queue.pollLast();\n            }\n            queue.offer(n);\n            while (r - l > k) {\n                int m = nums[l++];\n                if (m == queue.peekFirst()) {\n                    queue.pollFirst();\n                }\n            }\n            if (r - l == k) {\n                res[index++] = queue.peekFirst();\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\t#define f first\n\t#define s second\n\tvector<int> maxSlidingWindow(vector<int>& nums, int k) {\n\t\tvector<int> ans;\n\t\tpriority_queue<pair<int,int>> pq;\n\t\tfor(int i=0;i<k;i++)pq.push({nums[i],i});\n\n\t\tans.push_back(pq.top().f);\n\n\t\tfor(int i=k; i<nums.size(); i++){\n\t\t\tpq.push({nums[i],i});\n\t\t\twhile(!pq.empty() && pq.top().s < i-k+1)pq.pop();\n\t\t\tans.push_back(pq.top().f);\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Number of Times Binary String Is Prefix-Aligned",
        "algo_input": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step.\n\nA binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros.\n\nReturn the number of times the binary string is prefix-aligned during the flipping process.\n\n&nbsp;\nExample 1:\n\nInput: flips = [3,2,4,1,5]\nOutput: 2\nExplanation: The binary string is initially \"00000\".\nAfter applying step 1: The string becomes \"00100\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"01100\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"01110\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"11110\", which is prefix-aligned.\nAfter applying step 5: The string becomes \"11111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2.\n\n\nExample 2:\n\nInput: flips = [4,1,2,3]\nOutput: 1\nExplanation: The binary string is initially \"0000\".\nAfter applying step 1: The string becomes \"0001\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"1001\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"1101\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"1111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == flips.length\n\t1 &lt;= n &lt;= 5 * 104\n\tflips is a permutation of the integers in the range [1, n].\n\n",
        "solution_py": "class Solution:\n    def numTimesAllBlue(self, flips: List[int]) -> int:\n        \n        \n        l = len(flips)\n        s = 0\n        c = 0\n        \n        for i in range(len(flips)):\n            f = flips[i]\n            s = 1 << (f - 1) | s\n            if s ==  (1 << (i+1))-1:\n                c += 1\n        \n        return c",
        "solution_js": "var numTimesAllBlue = function(flips) {\n    const flipped = new Array(flips.length).fill(0);\n    let prefixAlignedCount = 0;\n    flips.forEach((i, step) => {\n        flipped[i - 1] = 1;\n        if(isPrefixAligned(step)) {\n            ++prefixAlignedCount;\n        }\n    })\n    return prefixAlignedCount;\n    \n    function isPrefixAligned(step) {\n        for(let i = 0; i < flips.length; ++i) {\n            if((i < step && flipped[i] === 0) || (i > step && flipped[i] === 1)) {\n                return false;\n            }\n        }\n        return true;\n    }\n};",
        "solution_java": "class Solution {\n    public int numTimesAllBlue(int[] flips) {\n        int counter=0,total=0,max=Integer.MIN_VALUE;\n        for(int i=0;i<flips.length;i++){\n            if(max<flips[i])max=flips[i];\n            if(++counter==max)total++;\n        }\n        return total;\n    }\n}",
        "solution_c": "class BIT{\n  public:\nvector<int>bit;\nint n;\nBIT(int n){\n    bit.resize(n+1,0);\n    this->n=n;\n}\n\nint findSum(int i){\n    \n    int sum=0;\n    while(i>0){\n        sum+=bit[i];\n        i-=(i&(-i));\n    }\n    return sum;\n}\n\nvoid update(int i,int val){\n    \n\n    while(i<=n){\n        bit[i]+=val;\n        i+=(i&(-i));\n    }  \n}\n\n};\n\n\nclass Solution {\npublic:\nint numTimesAllBlue(vector<int>& flips) {\n\n    int n=flips.size();\n    BIT tree(n+1);\n    int res=0;\n    string s=string(n,'0');\n   \n    int maxi=0;\n    for(auto &x:flips){\n        if(s[x-1]=='1'){\n            tree.update(x,-1);\n            s[x-1]='0';\n        }\n        else {\n            s[x-1]='1';\n            tree.update(x,1);\n        }\n        maxi=max(maxi,x);\n        if(tree.findSum(x)==x && tree.findSum(maxi)==maxi)\n            res++;\n        \n     \n    \n    }\n    \n\t return res;   \n\t}\n};"
    },
    {
        "title": "Minimum Number of Moves to Seat Everyone",
        "algo_input": "There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.\n\nYou may perform the following move any number of times:\n\n\n\tIncrease or decrease the position of the ith student by 1 (i.e., moving the ith student from position&nbsp;x&nbsp;to x + 1 or x - 1)\n\n\nReturn the minimum number of moves required to move each student to a seat such that no two students are in the same seat.\n\nNote that there may be multiple seats or students in the same position at the beginning.\n\n&nbsp;\nExample 1:\n\nInput: seats = [3,1,5], students = [2,7,4]\nOutput: 4\nExplanation: The students are moved as follows:\n- The first student is moved from from position 2 to position 1 using 1 move.\n- The second student is moved from from position 7 to position 5 using 2 moves.\n- The third student is moved from from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.\n\n\nExample 2:\n\nInput: seats = [4,1,5,9], students = [1,3,2,6]\nOutput: 7\nExplanation: The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from from position 3 to position 4 using 1 move.\n- The third student is moved from from position 2 to position 5 using 3 moves.\n- The fourth student is moved from from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.\n\n\nExample 3:\n\nInput: seats = [2,2,6,6], students = [1,3,2,6]\nOutput: 4\nExplanation: Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from from position 1 to position 2 using 1 move.\n- The second student is moved from from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == seats.length == students.length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= seats[i], students[j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n        seats.sort()\n        students.sort()\n        return sum(abs(seat - student) for seat, student in zip(seats, students))",
        "solution_js": "var minMovesToSeat = function(seats, students) {\n    let sum = 0\n    seats=seats.sort((a,b)=>a-b)    \n    students=students.sort((a,b)=>a-b)\n    for(let i=0;i<seats.length;i++)\n        sum+=Math.abs(seats[i]-students[i])\n    return sum\n};",
        "solution_java": "class Solution {\n    public int minMovesToSeat(int[] seats, int[] students) {\n        Arrays.sort(seats);\n        Arrays.sort(students);\n        int diff = 0;\n        for(int i=0; i<seats.length; i++){\n            diff += Math.abs(students[i]-seats[i]);\n        }\n        return diff;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMovesToSeat(vector<int>& seats, vector<int>& students) {\n        sort(seats.begin(), seats.end());\n        sort(students.begin(), students.end());\n        \n        int res = 0;\n        for (int i = 0; i < seats.size(); i++) res += abs(seats[i] - students[i]);\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Count Integers With Even Digit Sum",
        "algo_input": "Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.\n\nThe digit sum of a positive integer is the sum of all its digits.\n\n&nbsp;\nExample 1:\n\nInput: num = 4\nOutput: 2\nExplanation:\nThe only integers less than or equal to 4 whose digit sums are even are 2 and 4.    \n\n\nExample 2:\n\nInput: num = 30\nOutput: 14\nExplanation:\nThe 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def countEven(self, num: int) -> int:\n        if num%2!=0:\n            return (num//2)\n        s=0\n        t=num\n        while t:\n            s=s+(t%10)\n            t=t//10\n        if s%2==0:\n            return num//2\n        else:\n            return (num//2)-1",
        "solution_js": "var countEven = function(num) {\n    let count=0;\n    for(let i=2;i<=num;i++){\n        if(isEven(i)%2==0){\n            count++;\n        }\n    }\n    return count\n};\n\nconst isEven = (c) =>{\n    let sum=0;\n    while(c>0){\n        sum+=(c%10)\n        c=Math.floor(c/10)\n    }\n    return sum\n}",
        "solution_java": "class Solution\n{\n    public int countEven(int num)\n    {\n        int count = 0;\n        for(int i = 1; i <= num; i++)\n            if(sumDig(i))\n                count++;\n        return count;\n    }\n    private boolean sumDig(int n)\n    {\n        int sum = 0;\n        while(n > 0)\n        {\n            sum += n % 10;\n            n /= 10;\n        }\n\t\treturn (sum&1) == 0 ? true : false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countEven(int num) {\n        int temp = num, sum = 0;\n        while (num > 0) {\n            sum += num % 10;\n            num /= 10;\n        }\n        return sum % 2 == 0 ? temp / 2 : (temp - 1) / 2;\n    }\n};"
    },
    {
        "title": "Reach a Number",
        "algo_input": "You are standing at position 0 on an infinite number line. There is a destination at position target.\n\nYou can make some number of moves numMoves so that:\n\n\n\tOn each move, you can either go left or right.\n\tDuring the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.\n\n\nGiven the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.\n\n&nbsp;\nExample 1:\n\nInput: target = 2\nOutput: 3\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to -1 (2 steps).\nOn the 3rd move, we step from -1 to 2 (3 steps).\n\n\nExample 2:\n\nInput: target = 3\nOutput: 2\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to 3 (2 steps).\n\n\n&nbsp;\nConstraints:\n\n\n\t-109 &lt;= target &lt;= 109\n\ttarget != 0\n\n",
        "solution_py": "class Solution: \n  def  reachNumber(self,target):\n    jumpCount = 1 \n    sum = 0 \n    while sum<abs(target):\n      sum+=jump \n      jumpCount+=1 \n    \n    if (sum-target)%2==0: return jumpCount-1 \n    else:\n      \n      if ((sum+jumpCount)-target)%2==0: \n        return jumpCount\n      else:\n        return jumpCount+1 ",
        "solution_js": "/**\n * @param {number} target\n * @return {number}\n */\nvar reachNumber = function(target) {\n    target = Math.abs(target);\n    let steps = 0, sum = 0;\n    while (sum < target) {\n        steps++;\n        sum += steps;\n    }\n    while ((sum - target) % 2 !== 0) {\n        steps++;\n        sum += steps;\n    }\n    return steps;\n};",
        "solution_java": "class Solution {\n    public int reachNumber(int target) {\n        int sum =0 ,steps = 0;\n        if(target ==0) return 0;\n        target = Math.abs(target);\n        while(sum< target){\n            sum+=steps;\n            steps++;\n        }\n        \n        while(((sum-target)%2!=0)){\n            sum+=steps;\n            steps++;\n        }\n        return steps-1;\n\n    }\n}",
        "solution_c": "long long fun(long long a){ //sum of all natural from 1 to a\n    long long b=a*(a+1)/2;\n    return b;\n}\n\nclass Solution {\npublic:\n    int reachNumber(int target) {\n\n         long long i=1,j=pow(10,5),x=abs(target),ans=0; //for -ve or +ve positive of a number the minimum no. of steps from the origin will be same\n\n    while(i<=j){ // binary search to search if x is continous sum of some natural number starting from 1\n        long long m=(i+j)/2;\n\n        if(fun(m)==x){\n            ans=m;\n        }\n        if(x>fun(m)){\n            i=m+1;\n        }\n        else{\n            j=m-1;\n        }\n\n    }\n\n    if(ans!=0){ // If we found our ans return it\n\n        return ans;\n    }\n    else{\n     //in this for loop i have set the limit too high it can be less then 10^6 as max value j can be is 44723, so loop will never run fully, whatever the value of j will be, loop will maximum run for 3-10 iterations\n    for(int l=j+1;l<100000;l++){ // in the end of binary search we get the value of j(or high end) as the position of the number(in the sequence of continous sum of natural number from 1, i.e. 1, 3,6,10........) whose value is just less than x(searching element)\n\n        if((fun(l)-x)%2 ==0){ // as the total step will be more than x if we go backward from zero, thing to note is that if we go -ve direction we also have to come back so we covering even distance\n             ans=l;// when the first fun(l) - x is even that l is our minimum jump\n\n            break; // no need to search further\n\n    }\n    }\n\n    }\n\n        return ans;\n    }\n\n};"
    },
    {
        "title": "Find Missing Observations",
        "algo_input": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.\n\nYou are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.\n\nReturn an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.\n\nThe average value of a set of k numbers is the sum of the numbers divided by k.\n\nNote that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.\n\n&nbsp;\nExample 1:\n\nInput: rolls = [3,2,4,3], mean = 4, n = 2\nOutput: [6,6]\nExplanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\n\n\nExample 2:\n\nInput: rolls = [1,5,6], mean = 3, n = 4\nOutput: [2,3,2,2]\nExplanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\n\n\nExample 3:\n\nInput: rolls = [1,2,3,4], mean = 6, n = 4\nOutput: []\nExplanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == rolls.length\n\t1 &lt;= n, m &lt;= 105\n\t1 &lt;= rolls[i], mean &lt;= 6\n\n",
        "solution_py": "class Solution:\n    def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n        missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)\n        if rem == 0:\n            if 1 <= missing_val <= 6:\n                return [missing_val] * n\n        elif 1 <= missing_val < 6:\n            return [missing_val + 1] * rem + [missing_val] * (n - rem)\n        return []",
        "solution_js": "var missingRolls = function(rolls, mean, n) {\n    let res = [];\n    let sum = ((n + rolls.length) * mean) - rolls.reduce((a,b)=>a+b);\n    if(sum>6*n || sum<1*n) return res;\n    let dec = sum % n;\n    let num = Math.floor(sum / n);\n    for(let i = 0; i < n; i++){\n        if(dec) res.push(num+1), dec--;\n        else res.push(num);\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public int[] missingRolls(int[] rolls, int mean, int n) {\n        \n    \tint i,m=rolls.length,sum=0;\n    \tfor(i=0;i<m;i++)\n    \t\tsum+=rolls[i];\n\t\t\t\n    \tint x=(mean*(m+n))-sum;\n\t\t\n\t\tif(x<=0||n*6<x||((x/n)==0)) {\n    \t\treturn new int[] {};\n\t\t}\n\t\t\t\n    \tint arr[]=new int[n];\n    \t\n\t\tint p=x/n,q=x%n;\n    \tfor(i=0;i<n;i++)  {\n\t\t\n    \t\tarr[i]=p+(q>0?1:0);\n    \t\tq--;\n    \t}\n    \treturn arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> missingRolls(vector<int>& rolls, int mean, int n) {\n        int size=rolls.size(),sum=accumulate(rolls.begin(),rolls.end(),0),missingSum=0;\n         missingSum=mean*(n+size)-sum;\n        if(missingSum<n || missingSum>6*n)\n            return {};\n         int rem=missingSum%n;\n         vector<int>ans(n,missingSum/n);\n        for(int i=0;i<rem;i++)\n            ans[i]+=1;\n        return ans;   \n    }\n};"
    },
    {
        "title": "Distribute Candies",
        "algo_input": "Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.\n\nThe doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.\n\nGiven the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.\n\n&nbsp;\nExample 1:\n\nInput: candyType = [1,1,2,2,3,3]\nOutput: 3\nExplanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.\n\n\nExample 2:\n\nInput: candyType = [1,1,2,3]\nOutput: 2\nExplanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.\n\n\nExample 3:\n\nInput: candyType = [6,6,6,6]\nOutput: 1\nExplanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == candyType.length\n\t2 &lt;= n &lt;= 104\n\tn&nbsp;is even.\n\t-105 &lt;= candyType[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def distributeCandies(self, candyType: List[int]) -> int:\n        return min(len(set(candyType)), (len(candyType)//2))",
        "solution_js": "/**\n * @param {number[]} candyType\n * @return {number}\n */\nvar distributeCandies = function(candyType) {\n\n    const set = new Set();\n    candyType.map(e => set.add(e));\n    return candyType.length/2 > set.size ? set.size : candyType.length/2\n\n};",
        "solution_java": "class Solution {\n    public int distributeCandies(int[] candyType) {\n        Set<Integer> set = new HashSet<>();\n        for (int type : candyType) set.add(type);\n        return Math.min(set.size(), candyType.length / 2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int distributeCandies(vector<int>& candyType) \n    {\n        unordered_set<int> s(candyType.begin(),candyType.end());\n        return min(candyType.size()/2,s.size());\n            \n        \n    }\n};\n//if you like the solution plz upvote."
    },
    {
        "title": "Insert Interval",
        "algo_input": "You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.\n\nInsert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).\n\nReturn intervals after the insertion.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput: [[1,5],[6,9]]\n\n\nExample 2:\n\nInput: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput: [[1,2],[3,10],[12,16]]\nExplanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= intervals.length &lt;= 104\n\tintervals[i].length == 2\n\t0 &lt;= starti &lt;= endi &lt;= 105\n\tintervals is sorted by starti in ascending order.\n\tnewInterval.length == 2\n\t0 &lt;= start &lt;= end &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n\n        intervals.append(newInterval)\n        intervals.sort(key=lambda x: x[0])\n\n        result = []\n        for interval in intervals:\n            if not result or result[-1][1] < interval[0]:\n                result.append(interval)\n            else:\n                result[-1][1] = max(result[-1][1],interval[1])\n\n        return result",
        "solution_js": "var insert = function(intervals, newInterval) {\n    //Edge case\n    if (intervals.length === 0) {\n        return [newInterval];\n    }\n\t//Find the index to insert newIntervals\n    let current = 0;\n    while (current < intervals.length && intervals[current][0] < newInterval[0]) {\n        current++;\n    }\n    intervals.splice(current, 0, newInterval);\n\t//If newInterval is not the last index, check the element behigh newInterval to see if merge is needed\n    if (current !== intervals.length -1) {\n        let pointer = current + 1;\n        if (intervals[pointer][0] <= newInterval[1]) {\n            while (pointer < intervals.length && intervals[pointer][0] <= newInterval[1]) {\n                pointer++;\n            }\n            newInterval[1] = Math.max(newInterval[1], intervals[pointer - 1][1]);\n            intervals.splice(current + 1, pointer - (current + 1));\n        }\n    }\n\t//If newInterval is not the first index, check the element berfore newInterval to see if merge is needed\n    if (current !== 0) {\n        if (intervals[current - 1][1] >= newInterval[0]) {\n            newInterval[0] = intervals[current - 1][0];\n            newInterval[1] = Math.max(newInterval[1], intervals[current - 1][1]);\n            intervals.splice(current - 1, 1);\n        }\n    }\n    return intervals;\n};",
        "solution_java": "class Solution {\n    public int[][] insert(int[][] intervals, int[] newInterval) {\n        if (newInterval == null || newInterval.length == 0) return intervals;\n        \n        List<int[]> merged = new LinkedList<>();\n        int i = 0;\n        // add not overlapping\n        while (i < intervals.length && intervals[i][1] < newInterval[0]) {\n            merged.add(intervals[i]);\n            i++;\n        }\n        // add overlapping\n        while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n            newInterval[0] = Math.min(intervals[i][0], newInterval[0]);\n            newInterval[1] = Math.max(intervals[i][1], newInterval[1]);\n            i++;\n        }\n        merged.add(newInterval);\n        // add rest\n        while (i < intervals.length) {\n            merged.add(intervals[i]);\n            i++;\n        }\n        return merged.toArray(new int[merged.size()][]);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {\n        vector<vector<int>> output;\n        int n = intervals.size();\n        int i = 0;\n        while(i < n){\n            if(newInterval[1] < intervals[i][0]){\n                output.push_back(newInterval);\n                while(i < n){\n                    output.push_back(intervals[i]);\n                    i++;\n                }\n                return output;\n            }\n            else if(newInterval[0] > intervals[i][1]){\n                output.push_back(intervals[i]);\n                i++;\n            }\n            else{\n                newInterval[0] = min(newInterval[0], intervals[i][0]);\n                newInterval[1] = max(newInterval[1], intervals[i][1]);\n                i++;\n            }\n        }\n        output.push_back(newInterval);//think about it\n        return output;\n    }\n};"
    },
    {
        "title": "Remove K Digits",
        "algo_input": "Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.\n\n&nbsp;\nExample 1:\n\nInput: num = \"1432219\", k = 3\nOutput: \"1219\"\nExplanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n\n\nExample 2:\n\nInput: num = \"10200\", k = 1\nOutput: \"200\"\nExplanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n\n\nExample 3:\n\nInput: num = \"10\", k = 2\nOutput: \"0\"\nExplanation: Remove all the digits from the number and it is left with nothing which is 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= num.length &lt;= 105\n\tnum consists of only digits.\n\tnum does not have any leading zeros except for the zero itself.\n\n",
        "solution_py": "# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict.\n#as soon as len(delete) == k delete those indexes from the initial string and thats the answer.\n#if len(delete) < k remove k-len(delete) chars from right and thats the answer\nclass Solution:\n    def removeKdigits(self, s: str, k: int) -> str:\n        if len(s) == k:\n            return '0'\n        stack = []\n        delete = {}\n        for i in range(len(s)):\n\n            while stack and s[i] < stack[-1][0]:\n                delete[stack.pop()[1]] = 1\n                if len(delete) == k:\n                    break\n            if len(delete) == k:\n                return self.deleteindexes(s, delete, k)\n            stack.append([s[i], i])\n        s1 = self.deleteindexes(s, delete, k)\n\n        return str(int(s1[:len(s1)-k +len(delete)]))\n\n\n    def deleteindexes(self, s, delete, k):\n        if not delete:\n            return s\n        if len(delete) == k:\n            return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete])))\n        else:\n            return ''.join([c for ind, c in enumerate(s) if ind not in delete])",
        "solution_js": "var removeKdigits = function(num, k) {\n    if(k == num.length) {\n        return '0'\n    }\n    let stack = []\n    for(let i = 0; i < num.length; i++) {\n        while(stack.length > 0 && num[i] < stack[stack.length - 1] && k > 0) {\n            stack.pop()\n            k--\n        }\n        stack.push(num[i])\n    }\n    while(k > 0) {\n        stack.pop()\n        k--\n    }\n    while(stack[0] == 0 && stack.length > 1) {\n        stack.shift()\n    }\n    return stack.join('')\n}",
        "solution_java": "class Solution {\n    public String removeKdigits(String num, int k) {\n        int n = num.length();\n        if(n == k){\n            return \"0\";\n        }\n        Deque<Character> dq = new ArrayDeque<>();\n        for(char ch : num.toCharArray()){\n            while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){\n                dq.pollLast();\n                k--;\n            }\n            dq.addLast(ch);\n        }\n        StringBuilder sb = new StringBuilder();\n        while(!dq.isEmpty() && dq.peekFirst() == '0'){\n            dq.pollFirst();\n        }\n        while(!dq.isEmpty()){\n            sb.append(dq.pollFirst());\n        }\n        if(k >= sb.length()){\n            return \"0\";\n        }\n        return sb.length() == 0 ? \"0\" : sb.toString().substring(0,sb.length()-k);\n    }\n}",
        "solution_c": "\t\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n    string removeKdigits(string num, int k) {\n        // number of operation greater than length we return an empty string\n        if(num.length() <= k)   \n            return \"0\";\n        \n        // k is 0 , no need of removing /  preforming any operation\n        if(k == 0)\n            return num;\n        \n        string res = \"\";// result string\n        stack <char> s; // char stack\n        \n        s.push(num[0]); // pushing first character into stack\n        \n        for(int i = 1; i<num.length(); ++i)\n        {\n            while(k > 0 && !s.empty() && num[i] < s.top())\n            {\n                // if k greater than 0 and our stack is not empty and the upcoming digit,\n                // is less than the current top than we will pop the stack top\n                --k;\n                s.pop();\n            }\n            \n            s.push(num[i]);\n            \n            // popping preceding zeroes\n            if(s.size() == 1 && num[i] == '0')\n                s.pop();\n        }\n        \n        while(k && !s.empty())\n        {\n            // for cases like \"456\" where every num[i] > num.top()\n            --k;\n            s.pop();\n        }\n        \n        while(!s.empty())\n        {\n            res.push_back(s.top()); // pushing stack top to string\n            s.pop(); // pop the top element\n        }\n        \n        reverse(res.begin(),res.end()); // reverse the string \n        \n        if(res.length() == 0)\n            return \"0\";\n        \n        return res;\n        \n        \n    }\n};"
    },
    {
        "title": "Convert a Number to Hexadecimal",
        "algo_input": "Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.\n\nAll the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.\n\nNote:&nbsp;You are not allowed to use any built-in library method to directly solve this problem.\n\n&nbsp;\nExample 1:\nInput: num = 26\nOutput: \"1a\"\nExample 2:\nInput: num = -1\nOutput: \"ffffffff\"\n\n&nbsp;\nConstraints:\n\n\n\t-231 &lt;= num &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def toHex(self, num: int) -> str:\n        ret = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n        ans = \"\"\n\n        if num < 0:\n            num = pow(2,32) +num\n\n        if num == 0:\n            return \"0\"\n        while num > 0:\n            ans = ret[num%16] +ans\n            num = num//16\n\n        return ans",
        "solution_js": " var toHex = function(num) {\n    let hexSymbols = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"];\n    if (num >= 0) {\n        let hex = \"\";\n        do {\n            let reminder = num % 16;\n            num = Math.floor(num/16);\n            hex = hexSymbols[reminder] + hex;\n        } while (num > 0)\n        return hex;\n    } else {\n        num = -num;\n        let invertedHex = \"\"; //FFFFFFFF - hex\n        let needToCarry1 = true; //adding + 1 initially and carrying it on if needed\n        while (num > 0) {\n            let reminder = num % 16;\n            let invertedReminder = 15 - reminder; //inverting\n            if (needToCarry1) { //adding 1 for 2's complement\n                invertedReminder += 1;\n                if (invertedReminder === 16) { //overflow, carrying 1 to the left\n                    invertedReminder = 0;\n                    needToCarry1 = true;\n                } else {\n                    needToCarry1 = false;\n                }\n            }\n            num = Math.floor(num/16);\n            invertedHex = hexSymbols[invertedReminder] + invertedHex;\n        }\n        //formatting as \"FFFFFFFF\"\n        while (invertedHex.length < 8) {\n            invertedHex = \"f\" + invertedHex;\n        }\n        return invertedHex;\n    }\n};",
        "solution_java": "class Solution {\n    public String toHex(int num) {\n        if(num == 0) return \"0\";\n\n        boolean start = true;\n\n        StringBuilder sb = new StringBuilder();\n\n        for(int i = 28; i >= 0; i -= 4) {\n            int digit = (num >> i) & 15;\n            if(digit > 9) {\n                char curr = (char)(digit%10 + 'a');\n                sb.append(curr);\n                start = false;\n            } else if(digit != 0) {\n                char curr = (char)(digit + '0');\n                sb.append(curr);\n                start = false;\n            } else {//digit == 0\n                if(start == false) { //avoid case: 00001a\n                    sb.append('0');\n                }\n            }\n\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    string toHex(int num)\n    {\n        string hex = \"0123456789abcdef\";\n        unsigned int n = num; // to handle neg numbers\n        string ans = \"\";\n        if (n == 0)\n            return \"0\";\n        while (n > 0)\n        {\n            int k = n % 16;\n            ans += hex[k];\n            n /= 16;\n        }\n        reverse(ans.begin(), ans.end()); // as we stored it in the opposite order\n        return ans;\n    }\n};"
    },
    {
        "title": "Smallest Range I",
        "algo_input": "You are given an integer array nums and an integer k.\n\nIn one operation, you can choose any index i where 0 &lt;= i &lt; nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.\n\nThe score of nums is the difference between the maximum and minimum elements in nums.\n\nReturn the minimum score of nums after applying the mentioned operation at most once for each index in it.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n\n\nExample 2:\n\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n\n\nExample 3:\n\nInput: nums = [1,3,6], k = 3\nOutput: 0\nExplanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t0 &lt;= nums[i] &lt;= 104\n\t0 &lt;= k &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def smallestRangeI(self, nums: List[int], k: int) -> int:\n        return max(0, max(nums)-min(nums)-2*k)",
        "solution_js": "var smallestRangeI = function(nums, k) {\n    let max = Math.max(...nums);\n    let min = Math.min(...nums);\n    return Math.max(0, max - min- 2*k)\n};",
        "solution_java": "class Solution {\n    public int smallestRangeI(int[] nums, int k) {\n        if (nums.length == 1)\n            return 0;\n\n        int min = Integer.MAX_VALUE;\n        int max = Integer.MIN_VALUE;\n\n        for (int num: nums) {\n            min = Math.min(min, num);\n            max = Math.max(max, num);\n        }\n        int diff = max - min;\n\n        return Math.max(0, diff - 2*k);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int smallestRangeI(vector<int>& nums, int k) {\n        int mx = *max_element(nums.begin(), nums.end());\n        int mn = *min_element(nums.begin(), nums.end());\n        \n        return max(0, (mx-mn-2*k));\n    }\n};"
    },
    {
        "title": "Number of Longest Increasing Subsequence",
        "algo_input": "Given an integer array&nbsp;nums, return the number of longest increasing subsequences.\n\nNotice that the sequence has to be strictly increasing.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,5,4,7]\nOutput: 2\nExplanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2]\nOutput: 5\nExplanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2000\n\t-106 &lt;= nums[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def findNumberOfLIS(self, nums: List[int]) -> int:\n        \n        if not nums or len(nums) == 0:\n            return 0\n        \n        def find_pos(sub, val):\n            left, right = 0, len(sub) - 1\n            while left < right:\n                mid = (left + right) >> 1\n                if sub[mid] >= val: \n                    right = mid\n                else:\n                    left = mid + 1\n            return left \n        \n    \n        sub_list = []\n        \n        for val in nums:\n            if len(sub_list) == 0 or val > sub_list[-1][-1][0]:\n                # should append a new element at the end\n                cur_count = sum([x[1] for x in sub_list[-1] if val > x[0]]) if len(sub_list) != 0 else 1\n                sub_list.append([(val, cur_count)])\n            else:\n                # get the last number to turn it back to a LIS problem\n                cur_sub = [array[-1][0] for array in sub_list]\n                pos = find_pos(cur_sub, val)\n                # if pos == 0, means it is smallest, no need to look the previous level and set it to be 1\n                cur_count = sum([x[1] for x in sub_list[pos - 1] if val > x[0]]) if pos > 0 else 1\n                sub_list[pos].append((val, cur_count))\n      \n        return sum([x[1] for x in sub_list[-1]])",
        "solution_js": "var findNumberOfLIS = function(nums) {\n    const { length } = nums;\n    const dpLength = Array(length).fill(1);\n    const dpCount = Array(length).fill(1);\n\n    for (let right = 0; right < length; right++) {\n        for (let left = 0; left < right; left++) {\n            if (nums[left] >= nums[right]) continue;\n            if (dpLength[left] + 1 === dpLength[right]) {\n                dpCount[right] += dpCount[left];\n            } else if (dpLength[left] + 1 > dpLength[right]) {\n                dpLength[right] = dpLength[left] + 1;\n                dpCount[right] = dpCount[left];\n            }\n        }\n    }\n\n    const maxLength = Math.max(...dpLength);\n    return dpLength.reduce((result, length, index) => {\n        const count = dpCount[index];\n        return result + (maxLength === length ? count : 0);\n    }, 0);\n};",
        "solution_java": "class Solution {\n    public int findNumberOfLIS(int[] nums) {\n        int N = nums.length;\n        int []dp =new int[N];\n        int []count = new int[N];\n        Arrays.fill(dp,1);Arrays.fill(count,1);\n        int maxi = 1;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<i;j++){\n                if(nums[j] < nums[i] && dp[j]+1 > dp[i]){\n                    dp[i] = dp[j]+1;\n                    //inherit a new one\n                    count[i]=count[j];\n                    maxi = Math.max(dp[i],maxi);\n                }else if(nums[j] < nums[i] && dp[j]+1 == dp[i]){\n                    //got one as same len, increase count\n                    count[i]+=count[j];\n                }\n            }\n        }//for ends\n        int maxlis=0;\n        for(int i=0;i<N;i++){\n            if(maxi == dp[i]){\n                maxlis+=count[i];\n            }\n        }\n        return maxlis;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint findNumberOfLIS(vector<int>& nums) {\n\t\tint n = nums.size(), maxI=0, inc=0;\n\t\tvector<int> dp(n,1), count(n,1);\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tfor(int j=0;j<i;j++){\n\t\t\t\tif(nums[i]>nums[j] && 1+dp[j] > dp[i])\n\t\t\t\t{\n\t\t\t\t\tdp[i] = 1+dp[j];\n\t\t\t\t\tcount[i] = count[j];\n\t\t\t\t}\n\t\t\t\telse if(nums[i]>nums[j] && 1+dp[j] == dp[i])\n\t\t\t\t\tcount[i] += count[j];\n\t\t\t}\n\t\t\tmaxI = max(maxI, dp[i]);\n\t\t}\n\t\tfor(int i=0;i<n;i++)\n\t\t\tif(maxI == dp[i])   inc += count[i];\n\t\treturn inc;\n\t}\n};"
    },
    {
        "title": "Shortest Subarray to be Removed to Make Array Sorted",
        "algo_input": "Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.\n\nReturn the length of the shortest subarray to remove.\n\nA subarray is a contiguous subsequence of the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,10,4,2,3,5]\nOutput: 3\nExplanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].\n\n\nExample 2:\n\nInput: arr = [5,4,3,2,1]\nOutput: 4\nExplanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].\n\n\nExample 3:\n\nInput: arr = [1,2,3]\nOutput: 0\nExplanation: The array is already non-decreasing. We do not need to remove any elements.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t0 &lt;= arr[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n        n = len(arr)\n        i = 0\n        while i < n-1 and arr[i+1] >= arr[i]:\n            i += 1\n        \n        if i == n-1:\n            return 0\n        \n        j = n-1\n        while j >= 0 and arr[j-1] <= arr[j]:\n            j -= 1\n        \n        ans = min(n, n-i-1, j)\n        \n        for l in range(i+1):\n            r = j\n            while r < n and arr[r] < arr[l]:\n                r += 1\n            ans = min(ans, r-l-1)\n        \n        return ans",
        "solution_js": "var findLengthOfShortestSubarray = function(arr) {\n    const n = arr.length;\n    \n    if (n <= 1) {\n        return 0;\n    }\n    \n    let prefix = 1;\n    \n    while (prefix < n) {\n        if (arr[prefix - 1] <= arr[prefix]) {\n            prefix++;\n        } else {\n            break;\n        }\n    }\n    \n    if (prefix === n) {\n        return 0;\n    }\n    \n    let suffix = 1;\n    \n    while (suffix < n) {\n        const i = n - 1 - suffix;\n        \n        if (arr[i] <= arr[i + 1]) {\n            suffix++;\n        } else {\n            break;\n        }\n    }\n\n    let res = Math.min(n - prefix, n - suffix);\n    let left = 0;\n    let right = n - suffix;\n\n    while (left < prefix && right < n) {\n        if (arr[left] <= arr[right]) {\n            res = Math.min(res, right - left - 1);\n            left++;\n        } else {\n            right++;\n        }\n    }\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public int findLengthOfShortestSubarray(int[] arr) {\n        int firstLast=0,lastFirst=arr.length-1;\n        for(;firstLast<arr.length-1;firstLast++){\n            if(arr[firstLast]>arr[firstLast+1]) break;\n        }\n\t\t//Base case for a non-decreasing sequence\n        if(firstLast==arr.length-1) return 0;\n        for( ;lastFirst>0;lastFirst--){\n            if(arr[lastFirst]<arr[lastFirst-1]) break;\n        }\n\t\t//Possibilities 1 or 2 as mentioned above\n        int minLength=Math.min(arr.length-firstLast-1,lastFirst);\n        for(;firstLast>=0;firstLast--){\n            for(int i=lastFirst;i<arr.length;i++){\n                if(arr[firstLast]>arr[i]) continue;\n                minLength = Math.min(minLength,i-firstLast-1);\n                break;\n            }\n        }\n        return minLength;\n    }\n}",
        "solution_c": "// itne me hi thakk gaye?\nclass Solution {\npublic:\n    bool ok(int &size, vector<int> &pref, vector<int> &suff, vector<int> &arr, int &n) {\n        for(int start=0; start<=n-size; start++) {\n            int end = start + size - 1;\n            int left = (start <= 0) ? 0 : pref[start-1];\n            int right = (end >= n-1) ? 0 : suff[end+1];\n            int le = (start <= 0) ? -1e9+2 : arr[start-1];\n            int re = (end >= n-1) ? 1e9+2 : arr[end+1];\n            if (left + right == n-size && le <= re) {\n                return true;\n            }\n        }\n        return false;\n    }\n    int findLengthOfShortestSubarray(vector<int>& arr) {\n        int n = arr.size();\n        if (!n || n==1) return 0;\n        vector<int> pref(n, 1);\n        vector<int> suff(n, 1);\n        for(int i=1; i<n; i++) {\n            if (arr[i] >= arr[i-1]) pref[i] = pref[i-1]+1;\n        }\n        for(int i=n-2; i>=0; i--) {\n            if (arr[i] <= arr[i+1]) suff[i] = suff[i+1]+1;\n        }\n        int low = 0;\n        int high = n-1;\n        while(low < high) {\n            int mid = (low + high)/2;\n            if(ok(mid, pref, suff, arr, n)) high = mid;\n            else low = mid+1;\n            if(high - low == 1) break;\n        }\n        if (ok(low, pref, suff, arr, n)) return low;\n        return high;\n    }\n};"
    },
    {
        "title": "Check If a String Contains All Binary Codes of Size K",
        "algo_input": "Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"00110110\", k = 2\nOutput: true\nExplanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n\n\nExample 2:\n\nInput: s = \"0110\", k = 1\nOutput: true\nExplanation: The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring. \n\n\nExample 3:\n\nInput: s = \"0110\", k = 2\nOutput: false\nExplanation: The binary code \"00\" is of length 2 and does not exist in the array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 105\n\ts[i] is either '0' or '1'.\n\t1 &lt;= k &lt;= 20\n\n",
        "solution_py": "class Solution:\n    def hasAllCodes(self, s: str, k: int) -> bool:\n        \n        Z = set()\n\n        for i in range(len(s)-k+1):\n            Z.add(s[i:i+k])\n            \n        if len(Z) == 2**k:\n            return True\n\n        return False",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {boolean}\n */\nvar hasAllCodes = function(s, k) {\n    \n    if (k > s.length) {\n        return false;\n    }\n    \n    /* Max strings can be generated of k chars 0/1. */\n    const max = Math.pow(2, k);\n    \n    /*\n    * Create a set. \n    * It will contain all unique values.\n    */ \n    const set = new Set();\n    \n    for(let i = 0; i < s.length - k + 1; i++) {\n        /* Generate substring of size k from index i */\n        const substr = s.substr(i, k);        \n        set.add(substr);\n        \n        /* \n        * if enough of unique strings are generated, \n        * break the loop as there is no point of iterating\n        * as we have found all necessary strings.\n        */\n        if (set.size === max) {\n            return true;\n        }\n    }\n          \n    return set.size === max;\n};",
        "solution_java": "class Solution {\n    public boolean hasAllCodes(String s, int k) {\n        HashSet<String> hs=new HashSet();\n        for(int i=0;i<=s.length()-k;i++){\n            hs.add(s.substring(i,i+k));\n        }\n        if(hs.size() == Math.pow(2,k))return true;\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool hasAllCodes(string s, int k) {\n        if (s.size() < k)\n        {\n            return false;\n        }\n        unordered_set<string> binary_codes;\n        for (int i = 0; i < s.size()-k+1; i++)\n        {\n            string str = s.substr(i, k);\n            binary_codes.insert(str);\n            if (binary_codes.size() == (int)pow(2, k))\n            {\n                return true;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Minimum Swaps to Make Strings Equal",
        "algo_input": "You are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].\n\nReturn the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.\n\n&nbsp;\nExample 1:\n\nInput: s1 = \"xx\", s2 = \"yy\"\nOutput: 1\nExplanation: Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".\n\n\nExample 2:\n\nInput: s1 = \"xy\", s2 = \"yx\"\nOutput: 2\nExplanation: Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.\n\n\nExample 3:\n\nInput: s1 = \"xx\", s2 = \"xy\"\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s1.length, s2.length &lt;= 1000\n\ts1, s2 only contain 'x' or 'y'.\n\n",
        "solution_py": "class Solution:\n    def minimumSwap(self, s1: str, s2: str) -> int:\n        h = defaultdict(int)\n        count = 0    # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd\n        for i in range(len(s1)):\n            if s1[i] != s2[i]:\n                count += 1\n                h[s1[i]] += 1\n        if count % 2 != 0:     \n            return -1\n        res, a, b = 0, h['x'], h['y']\n        res += a // 2 + b // 2\n        if a % 2 == 0:\n            return res\n        return res + 2",
        "solution_js": "var minimumSwap = function(s1, s2) {\n   let count1 = 0;\n    let count2 = 0;\n   for(let i in s1) {\n       if(s1[i] === \"x\" && s2[i] === \"y\") {\n           count1++\n       }\n        if(s1[i] === \"y\" && s2[i] === \"x\") {\n           count2++\n       }\n   }\n\n    let ans = Math.floor(count1 / 2) + Math.floor(count2 / 2);\n    if(count1 % 2 === 0 && count2 % 2 === 0){\n        return ans\n    }\n    else if(count1 % 2 !== 0 && count2 % 2 !== 0){\n        return ans + 2;\n    }\n    else {\n        return -1;\n    }\n};",
        "solution_java": "class Solution {\n    public int minimumSwap(String s1, String s2) {\n        if(s1.length() != s2.length()) return -1;\n\t\tint n = s1.length();\n        int x = 0 , y = 0;\n        \n        for(int i = 0 ; i < n ; i ++){\n            char c1 = s1.charAt(i) , c2 = s2.charAt(i);\n            if(c1 == 'x' && c2 == 'y') x++;\n            else if(c1 == 'y' && c2 == 'x') y++;\n        }\n        \n        if(x % 2 == 0 && y % 2 == 0) return x/2 + y/2;\n        else if(x % 2 == 1 && y % 2 == 1) return x/2 + y/2 + 2;\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumSwap(string s1, string s2) {\n        int n = s1.size();\n        int cnt1=0,cnt2=0,i=0;\n        \n        while(i<n){\n            int x = s1[i];\n            int y = s2[i++];\n            if(x=='x' and y=='y') cnt1++;\n            if(x=='y' and y=='x') cnt2++;\n        }\n        \n        if((cnt1+cnt2)%2==1) return -1;\n        \n        return (cnt1/2) + (cnt2/2) + (cnt1%2 + cnt2%2);\n    }\n};"
    },
    {
        "title": "Max Consecutive Ones III",
        "algo_input": "Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput: 6\nExplanation: [1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\nExample 2:\n\nInput: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput: 10\nExplanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\tnums[i] is either 0 or 1.\n\t0 &lt;= k &lt;= nums.length\n\n",
        "solution_py": "# TC : O(N)\n# SC : O(1)\nclass Solution:\n    def longestOnes(self, nums: List[int], k: int) -> int:\n        z_count = 0 #count zeors in nums\n        mx_ones = 0\n        j = 0\n        for i in range(len(nums)):\n            if nums[i] == 0: \n                z_count+=1\n            while z_count>k:#if zeros count cross k decrease count\n                if nums[j] == 0:\n                    z_count-=1\n                j+=1\n            print(i,j)\n            mx_ones = max(mx_ones, i-j+1)\n        return mx_ones",
        "solution_js": " * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar longestOnes = function(nums, k) {\n    let left = 0;\n    let oneCount = 0;\n    let maxLength = 0;\n    \n    for (let right = 0; right < nums.length; right ++) {\n        if (nums[right]) {  // so if the element is a 1 since 0 is falsy\n            oneCount++\n        }\n        \n        if ((right - left + 1 - oneCount) > k) { // check if we've used all of our replacements\n            if (nums[left]) { // start shrinking the window if its a 1 we subtract a count from oneCount\n                oneCount--\n            }\n            left++\n        }\n        \n        maxLength = Math.max(maxLength, right - left + 1); // update maxLength each iteration for largest window\n    }\n    \n    return maxLength\n};",
        "solution_java": "class Solution {\n    public int longestOnes(int[] nums, int k) {\n        int ans = 0;\n        int j = -1;\n        int count = 0;\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] == 0) {\n                count++;\n            }\n            while (count > k) {\n                j++;\n                if (nums[j] == 0) {\n                    count--;\n                }\n            }\n            int len = i - j;\n            if (len > ans) ans = len;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestOnes(vector<int>& nums, int k) {\n        \n        // max length of subarray with at most k zeroes \n    \n        int i=0;\n        int j=0;\n        int cnt = 0;\n        int ans = 0;\n\n        int n = nums.size();\n\n        while(j<n)\n        {\n            if(nums[j]==0)\n                cnt++;\n\n            if(cnt<=k)\n            {\n                ans = max(ans , j-i+1);\n                j++;\n            }\n            else //cnt>k\n            {\n                while(cnt>k)\n                {\n                    if(nums[i]==0)\n                        cnt--;\n                    i++;\n                }\n                j++;\n            }\n        }\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Longest Cycle in a Graph",
        "algo_input": "You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\n\nThe graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.\n\nReturn the length of the longest cycle in the graph. If no cycle exists, return -1.\n\nA cycle is a path that starts and ends at the same node.\n\n&nbsp;\nExample 1:\n\nInput: edges = [3,3,4,2,3]\nOutput: 3\nExplanation: The longest cycle in the graph is the cycle: 2 -&gt; 4 -&gt; 3 -&gt; 2.\nThe length of this cycle is 3, so 3 is returned.\n\n\nExample 2:\n\nInput: edges = [2,-1,3,1]\nOutput: -1\nExplanation: There are no cycles in this graph.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == edges.length\n\t2 &lt;= n &lt;= 105\n\t-1 &lt;= edges[i] &lt; n\n\tedges[i] != i\n\n",
        "solution_py": "class Solution:\n    def longestCycle(self, edges: List[int]) -> int:\n        preorder = [-1 for _ in range(len(edges))]\n        self.ans = -1\n        self.pre = 0\n        \n        def dfs(self, i: int, st: int) -> None:\n            preorder[i] = self.pre\n            self.pre += 1\n            \n            if edges[i] == -1:\n                return\n            elif preorder[edges[i]] == -1:\n                dfs(self, edges[i], st)\n                return\n            elif preorder[edges[i]] >= st:\n                self.ans = max(self.ans, preorder[i] - preorder[edges[i]] + 1)\n                return\n        \n        for i in range(len(edges)):\n            if preorder[i] == -1 and edges[i] != -1:\n                dfs(self, i, self.pre)\n        \n        return self.ans",
        "solution_js": "/**\n * @param {number[]} edges\n * @return {number}\n */\nfunction getCycleTopology(edges){\n    const indeg = new Array(edges.length).fill(0);\n    const queue = [];\n    const map = {};\n    for(const src in edges){\n        const des = edges[src]\n        if(des >= 0){\n            indeg[des] ++;\n        }\n        map[src] ? map[src].push(des) : map[src] = [des]\n    }\n    for(const node in indeg){\n        if(indeg[node] === 0){\n            queue.push(node)\n        }\n    }\n    while(queue.length > 0){\n        const node = queue.shift();\n        for(const connectedNode of map[node]){\n            if(connectedNode !== -1){\n                indeg[connectedNode] --;\n                if(indeg[connectedNode] === 0){\n                    queue.push(connectedNode);\n                }\n            }\n        }\n    }\n    return indeg\n}\nclass DisjointSet{\n    constructor(n){\n        this.n = n;\n        this.root = new Array(n).fill(0).map((_,i) => i);\n        this.rank = new Array(n).fill(1);\n\n    }\n    find(x){\n        if(x === this.root[x]) return x;\n        return this.root[x] = this.find(this.root[x]);\n    }\n    union(x,y){\n        const x_root = this.find(x);\n        const y_root = this.find(y);\n\n        if(this.rank[x_root] < this.rank[y_root]){\n            [this.rank[x_root] , this.rank[y_root]] = [this.rank[y_root] , this.rank[x_root]];\n        }\n        this.root[y_root] = x_root;\n        if(this.rank[x_root] === this.rank[y_root]) this.rank[x_root] ++;\n    }\n    _getGroupsComponentCounts(){\n        let groups = {};\n        for(const node of this.root){\n            const node_root = this.find(node);\n            groups[node_root] = groups[node_root] +1 || 1\n        }\n        return groups\n    }\n    getLongestGroupComponentLength(){\n        let longestLength = 1;\n        const lengths = this._getGroupsComponentCounts();\n        for(const length of Object.values(lengths)){\n            if(length > 1){\n                longestLength = Math.max(longestLength, length);\n            }\n        }\n        return longestLength > 1 ? longestLength : -1;\n    }\n}\nvar longestCycle = function(edges) {\n    const djs = new DisjointSet(edges.length);\n    let res = -1\n\n    // topology sort results topology array.\n    // component with greater than 0 is cyclic component.\n    // now we need to get groups of cycle since we can't distinguish each cycles with current datas.\n    const cycleComponent = getCycleTopology(edges); \n\n    //with edges info and cycle component data, we can now distinguish each cycle group by union finde\n    // because each cycle r independent with each other.\n    for(const src in edges){\n        const des = edges[src];\n        if(cycleComponent[src] && cycleComponent[des]){\n            djs.union(src, des);\n        }\n    }\n    res = djs.getLongestGroupComponentLength()\n    return res\n};",
        "solution_java": "class Solution {\n    public int longestCycle(int[] edges) {\n        int[] map = new int[edges.length];\n        int result = -1;\n\n        for (int i = 0; i < edges.length; i++)\n            result = Math.max(result, helper(i, 1, edges, map));\n\n        return result;\n    }\n\n    int helper(int index, int total, int[] edges, int[] map) {\n        if (index == -1 || map[index] == -1)\n            return -1;\n\n        if (map[index] != 0)\n            return total - map[index];\n\n        map[index] = total;\n        int result = helper(edges[index], total + 1, edges, map);\n        map[index] = -1;\n\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int maxLength = -1;\n    \n    void getcycle(vector<int> &edges,int si,vector<bool>& visit,vector<int>& store){\n        if(si == -1)return ;\n        if(visit[si]){\n            int count = -1;\n            for(int i =0;i<store.size();i++){\n                if(store[i]==si){\n                    count = i;\n                    break;\n                } }\n            \n            if(count==-1)return;\n            int size = (store.size()-count);\n            maxLength = max(maxLength,size);\n            return ;\n        }\n        \n        visit[si] = true;\n        store.push_back(si);\n        getcycle(edges,edges[si],visit,store);\n        \n        \n        return ;\n        \n    }\n    \n    \n    \n    int longestCycle(vector<int>& edges) {\n        \n        vector<bool> visit(edges.size(),0);\n        \n        for(int i =0;i<edges.size();i++){\n            \n            if(visit[i])continue;\n            vector<int> store;\n            getcycle(edges,i,visit,store);\n     \n        }\n        \n        return maxLength;\n        \n    }\n};"
    },
    {
        "title": "Validate Stack Sequences",
        "algo_input": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput: true\nExplanation: We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -&gt; 4,\npush(5),\npop() -&gt; 5, pop() -&gt; 3, pop() -&gt; 2, pop() -&gt; 1\n\n\nExample 2:\n\nInput: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput: false\nExplanation: 1 cannot be popped before 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pushed.length &lt;= 1000\n\t0 &lt;= pushed[i] &lt;= 1000\n\tAll the elements of pushed are unique.\n\tpopped.length == pushed.length\n\tpopped is a permutation of pushed.\n\n",
        "solution_py": "class Solution:\n    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n        stack=[]\n        i=0\n        for num in pushed:\n            stack.append(num) #we are pushing the number to the stack\n            while  len(stack) >0 and stack[len(stack)-1] == popped[i] :\n                #if the last element of the stack is equal to the popped element\n                stack.pop()\n                i+=1 #we are incrementing i\n        return True if len(stack) ==0 else False\n\t\t",
        "solution_js": "var validateStackSequences = function(pushed, popped) {\n    let stack = [];\n    let j = 0;\n    \n    for(let i=0; i<pushed.length; i++){\n        stack.push(pushed[i]);\n        while(stack.length != 0 && popped[j]== stack[stack.length-1]){\n            stack.pop();\n            j++\n        }\n    }\n    return stack.length<1\n\n};",
        "solution_java": "class Solution {\n    public boolean validateStackSequences(int[] pushed, int[] popped) {\n        Stack<Integer> st = new Stack<>(); // Create a stack\n\n        int j = 0; // Intialise one pointer pointing on popped array\n\n        for(int val : pushed){\n            st.push(val); // insert the values in stack\n            while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j];\n                st.pop(); // then pop out\n                j++; // increment j\n            }\n        }\n        return st.isEmpty(); // check if stack is empty return true else false\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {\n        stack<int> st; // Create a stack\n        \n        int j = 0; // Intialise one pointer pointing on popped array\n        \n        for(auto val : pushed){\n            st.push(val); // insert the values in stack\n            while(st.size() > 0 && st.top() == popped[j]){ // if st.peek() values equal to popped[j];\n                st.pop(); // then pop out\n                j++; // increment j\n            }\n        }\n        return st.size() == 0; // check if stack is empty return true else false\n    }\n};"
    },
    {
        "title": "Number of Excellent Pairs",
        "algo_input": "You are given a 0-indexed positive integer array nums and a positive integer k.\n\nA pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:\n\n\n\tBoth the numbers num1 and num2 exist in the array nums.\n\tThe sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.\n\n\nReturn the number of distinct excellent pairs.\n\nTwo pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.\n\nNote that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,1], k = 3\nOutput: 5\nExplanation: The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.\n\nExample 2:\n\nInput: nums = [5,1,1], k = 10\nOutput: 0\nExplanation: There are no excellent pairs for this array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\t1 &lt;= k &lt;= 60\n\n",
        "solution_py": "class Solution:\n    def countExcellentPairs(self, nums: List[int], k: int) -> int:\n        hamming = sorted([self.hammingWeight(num) for num in set(nums)])\n        ans = 0\n        for h in hamming:\n            ans += len(hamming) - bisect.bisect_left(hamming, k - h)\n        return ans\n\n    def hammingWeight(self, n):\n        ans = 0\n        while n:\n            n &= (n - 1)\n            ans += 1\n        return ans",
        "solution_js": "var countExcellentPairs = function(nums, k) {\n    const map = new Map();\n    const set = new Set();\n    const l = nums.length;\n    let res = 0;\n    for (let num of nums) {\n        let temp = num.toString(2).split(\"1\").length - 1;\n        if (!map.has(temp)) {\n            map.set(temp, new Set([num]));\n        } else {\n            map.get(temp).add(num);\n        }\n    }\n    \n    for (let num of nums) {\n        let temp = num.toString(2).split(\"1\").length - 1;\n        if(!set.has(num)) {\n            let gap = Math.max(0, k - temp)\n            for (let key of map.keys()) {\n                if (key >= gap) {\n                    res += map.get(key).size;\n                }\n            }  \n            set.add(num);\n        }else {\n            continue;\n        }\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public long countExcellentPairs(int[] nums, int k) {\n        HashMap<Integer,Set<Integer>> map = new HashMap<>();\n        for(int i : nums){\n            int x = Integer.bitCount(i);\n            map.putIfAbsent(x,new HashSet<>());\n            map.get(x).add(i);\n        }\n        long ans = 0;\n        HashSet<Integer> vis = new HashSet<>();\n        for(int i : nums){\n            if(vis.contains(i)) continue;\n            int need = Math.max(0,k-Integer.bitCount(i));\n            for(int key : map.keySet()) // runs at max 30 times\n                if(key >= need) ans += (long) map.get(key).size();\n            vis.add(i);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    typedef long long ll;\n    int setbits(int n){\n        int cnt = 0;\n        while(n){\n            cnt += (n%2);\n            n /= 2;\n        }\n        return cnt;\n    }\n    \n    long long countExcellentPairs(vector<int>& nums, int k) {\n        unordered_set<int> s(nums.begin(),nums.end());\n        vector<int> v;\n        for(auto& i: s){\n            int x = setbits(i);\n            v.push_back(x);\n        }\n        sort(v.begin(),v.end());\n        \n        ll ans = 0;\n        for(int i=0;i<v.size();i++){\n            auto it = lower_bound(v.begin(),v.end(),k-v[i]);\n            ans += (v.end()-it);\n        }\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Find the Distance Value Between Two Arrays",
        "algo_input": "Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.\n\nThe distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| &lt;= d.\n\n&nbsp;\nExample 1:\n\nInput: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput: 2\nExplanation: \nFor arr1[0]=4 we have: \n|4-10|=6 &gt; d=2 \n|4-9|=5 &gt; d=2 \n|4-1|=3 &gt; d=2 \n|4-8|=4 &gt; d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 &gt; d=2 \n|5-9|=4 &gt; d=2 \n|5-1|=4 &gt; d=2 \n|5-8|=3 &gt; d=2\nFor arr1[2]=8 we have:\n|8-10|=2 &lt;= d=2\n|8-9|=1 &lt;= d=2\n|8-1|=7 &gt; d=2\n|8-8|=0 &lt;= d=2\n\n\nExample 2:\n\nInput: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput: 2\n\n\nExample 3:\n\nInput: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr1.length, arr2.length &lt;= 500\n\t-1000 &lt;= arr1[i], arr2[j] &lt;= 1000\n\t0 &lt;= d &lt;= 100\n\n",
        "solution_py": "class Solution:\n\tdef findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int:\n\n\t\tresult = 0\n\n\t\tarray2 = sorted(array2)\n\n\t\tfor num in array1:\n\n\t\t\tflag = True\n\n\t\t\tlow = 0\n\t\t\thigh = len(array2)-1\n\n\t\t\twhile low <= high:\n\n\t\t\t\tmid = (low + high) // 2\n\n\t\t\t\tif abs(array2[mid] - num) <= d:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\n\t\t\t\telif array2[mid] > num:\n\t\t\t\t\thigh = mid - 1\n\n\t\t\t\telse:\n\t\t\t\t\tlow = mid + 1;\n\n\t\t\tif flag == True:\n\n\t\t\t\tresult = result + 1\n\n\t\treturn result",
        "solution_js": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @param {number} d\n * @return {number}\n */\nvar findTheDistanceValue = function(arr1, arr2, d) {\n    const arr2Sorted = arr2.sort((a, b) => a - b);\n    let dist = 0;\n\n    for (const num of arr1) {\n        if (isDistanceValid(num, d, arr2Sorted)) {\n            dist += 1;\n        }\n    }\n\n    return dist;\n};\n\nfunction isDistanceValid(number, dist, array) {\n    let left = 0;\n    let right = array.length - 1;\n\n    while (left <= right) {\n        const mid = Math.floor((right + left) / 2);\n\n        if (Math.abs(number - array[mid]) <= dist) {\n            return false;\n        }\n\n        if (array[mid] < number) {\n            left = mid + 1;\n        }\n\n        if (array[mid] > number) {\n            right = mid - 1;\n        }\n    }\n\n    return true;\n}",
        "solution_java": "class Solution {\n    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {\n        int x=0,val=0;\n        for(int i:arr1){\n            for(int j:arr2){\n                if(Math.abs(i-j)<=d){\n                   x--;\n                    break;\n                }\n            }\n            x++;\n        }\n      return x;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {\n        sort(arr2.begin(),arr2.end());\n        int ans = 0;\n        for(int i : arr1){\n            int id = lower_bound(arr2.begin(),arr2.end(),i) - arr2.begin();\n            int closest = d+1;\n            if(id != arr2.size()){\n                closest = min(abs(arr2[id]-i), closest);\n            } \n            if(id != 0){\n                closest = min(abs(arr2[id-1]-i), closest);\n            }\n            if(closest > d) ans++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Long Pressed Name",
        "algo_input": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.\n\nYou examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.\n\n&nbsp;\nExample 1:\n\nInput: name = \"alex\", typed = \"aaleex\"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\n\n\nExample 2:\n\nInput: name = \"saeed\", typed = \"ssaaedd\"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= name.length, typed.length &lt;= 1000\n\tname and typed consist of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def isLongPressedName(self, name: str, typed: str) -> bool:\n        #dic for memoization\n\t\tdic = {}\n        def dfs(i, j):\n            if (i, j) in dic:\n                return dic[(i, j)]\n            \n\t\t\t#see if there is any case where both i and j reach to the end, cuz that will be the true condition\n\t\t\t#I only need one True \n            if i >= len(name):\n                return j == len(typed)\n\t\t\t#we iterated through the end of typed, and not yet for name \n            if j >= len(typed):\n                return False\n            \n\t\t\t#if the characters don't match, return False\n            if name[i] != typed[j]:\n                dic[(i, j)] = False\n                return False\n            \n\t\t\t#if the two characters match\n\t\t\t#two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1))\n\t\t\t#return if any of them is True, which means that i, j reach to the end as aforementioned\n            dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1)\n            return dic[(i, j)]\n        \n\t\t#start from index 0, 0\n        return dfs(0, 0)",
        "solution_js": "var isLongPressedName = function(name, typed) {\n    let i = 0;\n    let j = 0;\n    while (j < typed.length) {\n        if (i < name.length && name[i] === typed[j]) i++;\n        else if (typed[j] !== typed[j - 1]) return false; // this needs when name is traversed but there is tail of characters in typed\n        j++; // Base case. keep going through typed anyway hitting first condition from time to time: (i < name.length && name[i] === typed[j])\n    }\n\n    return i === name.length;\n};",
        "solution_java": "class Solution {\n    public boolean isLongPressedName(String name, String typed) {\n        int i = 0;\n        int j = 0;\n        int m = name.length();\n        int n = typed.length();\n\n        while(j < n)\n        {\n            if(i < m && name.charAt(i) == typed.charAt(j))\n            {\n                i++;\n                j++;\n            }\n            else if(j > 0 && typed.charAt(j) == typed.charAt(j-1))\n            {\n                j++;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        return i == m;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isLongPressedName(string name, string typed) {\n        \n        int j = 0, i = 0;\n        for( ; i<name.length() && j<typed.length() ; i++)\n        {\n            if(name[i]!=typed[j++])\n                return false;\n            \n            \n            if(i<name.length() && name[i]!= name[i+1])\n            {\n                while(j<typed.length() && typed[j] == name[i])\n                j++;\n            }\n        }\n        \n         return (i == name.length() && j == typed.length());\n    }\n};"
    },
    {
        "title": "Maximum White Tiles Covered by a Carpet",
        "algo_input": "You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li &lt;= j &lt;= ri is colored white.\n\nYou are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.\n\nReturn the maximum number of white tiles that can be covered by the carpet.\n\n&nbsp;\nExample 1:\n\nInput: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\nOutput: 9\nExplanation: Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.\n\n\nExample 2:\n\nInput: tiles = [[10,11],[1,1]], carpetLen = 2\nOutput: 2\nExplanation: Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tiles.length &lt;= 5 * 104\n\ttiles[i].length == 2\n\t1 &lt;= li &lt;= ri &lt;= 109\n\t1 &lt;= carpetLen &lt;= 109\n\tThe tiles are non-overlapping.\n\n",
        "solution_py": "class Solution:\n    def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n        tiles.sort()\n\t\t#j: window index\n        j = cover = res = 0\n        for i in range(len(tiles)):\n\t\t\t#slide the window as far as we can to cover fully the intervals with the carpet\n            while j<len(tiles) and tiles[j][1]-tiles[i][0] + 1 <= carpetLen:\n                cover += tiles[j][1]-tiles[j][0] + 1\n                j += 1\n\t\t\t#process the remnant, that is, when the tiles[j] is covered by the carpet partially(not fully)\n            if j<len(tiles) and tiles[j][0]-tiles[i][0] + 1 <= carpetLen:\n                res = max(res, cover + carpetLen-(tiles[j][0]-tiles[i][0]))\n            else:\n                res = max(res, cover)\n            #when the tiles[j] is covered partially, the interval is not added to the variable cover\n\t\t\tif i!=j:\n                cover -= tiles[i][1]-tiles[i][0]+1\n\t\t\tj = max(j, i+1)\n        return res",
        "solution_js": "/**\n * @param {number[][]} tiles\n * @param {number} carpetLen\n * @return {number}\n */\nvar maximumWhiteTiles = function(tiles, carpetLen) {\n    const sorted = tiles.sort((a, b) => a[0]-b[0])\n    let res = 0\n\n    let total = 0\n    let right = 0\n\n    for (let tile of sorted){\n        const start = tile[0]\n        const end = start + carpetLen - 1\n        while(right < sorted.length && tiles[right][1] < end){\n            total += tiles[right][1] - tiles[right][0] + 1\n            right+=1\n        }\n        if(right === sorted.length || sorted[right][0] > end){\n            res = Math.max(res, total)\n        } else{\n            res = Math.max(res, total + (end-tiles[right][0] + 1))\n        }\n        total -= tile[1] - tile[0] + 1\n    }\n\n    return res\n};",
        "solution_java": "class Solution\n{\n    public int maximumWhiteTiles(int[][] tiles, int carpetLen)\n    {\n        Arrays.sort(tiles,(a,b)->{return a[0]-b[0];});\n        int x = 0;\n        int y = 0;\n        long maxCount = 0;\n        long count = 0;\n        \n        while(y < tiles.length && x <= y)\n        {\n            long start = tiles[x][0];\n            long end = tiles[y][1];\n            \n            if(end-start+1 <= carpetLen) \n            {\n                count += tiles[y][1] - tiles[y][0]+1;\n                maxCount = Math.max(maxCount,count);\n                y++;\n            }\n            else \n            {\n                long midDist = start+carpetLen-1;\n                long s = tiles[y][0];\n                long e = tiles[y][1];\n                if(midDist <= e && midDist >= s)  maxCount = Math.max(maxCount,count+midDist-s+1);\n                count -= tiles[x][1] - tiles[x][0] + 1;\n                x++;\n            }\n        }\n        return (int)maxCount;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) {\n        long long n = tiles.size() , ans = INT_MIN;\n        sort(tiles.begin(),tiles.end());\n        vector<long long> len(n) , li(n);\n\t\t//len array stores the prefix sum of tiles\n\t\t//li array stores the last index tiles[i]\n        for(int i=0;i<n;i++){\n            len[i] = (long long)(tiles[i][1] - tiles[i][0] + 1);\n            len[i]+=(i==0) ? 0 : len[i-1];\n            li[i] = tiles[i][1];\n        }\n        \n        for(int i=0 ; i<n ; i++){\n\t\t   //sp means starting tile index\n\t\t   //ep means ending tile index\n            long long sp = tiles[i][0] , ep = tiles[i][0] + (long long)carpetLen-1 , tc=0;\n            int idx = lower_bound(li.begin(),li.end(),ep) - li.begin();\n\t\t\t\n\t\t\t//logic to take count of tiles covered\n            if(idx==n){\n                tc = len[n-1];\n                tc-=(i==0) ? 0 : len[i-1];\n            }else{\n                tc = ep<tiles[idx][0] ? 0 : ep - (long long)tiles[idx][0]  + 1;\n                idx--;\n                if(idx>=0){\n                    tc+=len[idx];\n                    tc-=(i==0) ? 0 : len[i-1];\n                }\n            }\n            ans = max(ans,tc);\n        }\n        return (int)ans;\n    }\n};"
    },
    {
        "title": "Squares of a Sorted Array",
        "algo_input": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\nExplanation: After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].\n\n\nExample 2:\n\nInput: nums = [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-104 &lt;= nums[i] &lt;= 104\n\tnums is sorted in non-decreasing order.\n\n\n&nbsp;\nFollow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?",
        "solution_py": "class Solution:\n    def sortedSquares(self, nums: List[int]) -> List[int]:\n        l,r = 0, len(nums)-1\n        pointer = 0\n        arr = [0] *len(nums)\n        pointer = r\n        while l<=r:\n            if abs(nums[r]) > abs(nums[l]):\n                arr[pointer] = nums[r] **2\n                r-=1\n                pointer-=1\n            else:\n                arr[pointer] = nums[l] **2\n                l+=1\n                pointer-=1\n                \n            \n        return arr\n            \n            \n            ",
        "solution_js": "var sortedSquares = function(nums) {\n\tlet left = 0;\n\tlet right = nums.length - 1;\n\tconst arr = new Array(nums.length);\n\tlet arrIndex = arr.length - 1;\n\n\twhile (left <= right) {\n\t\tif (Math.abs(nums[left]) > Math.abs(nums[right])) {\n\t\t\tarr[arrIndex] = nums[left] * nums[left];\n\t\t\tleft++;\n\t\t} else {\n\t\t\tarr[arrIndex] = nums[right] * nums[right];\n\t\t\tright--;\n\t\t}\n\t\tarrIndex--;\n\t}\n\n\treturn arr;\n};",
        "solution_java": "class Solution {\n    public int[] sortedSquares(int[] nums) {\n        int s=0;\n        int e=nums.length-1;\n        int p=nums.length-1;\n        int[] a=new int[nums.length];\n        while(s<=e){\n            if(nums[s]*nums[s]>nums[e]*nums[e]){\n                a[p--]=nums[s]*nums[s];\n                s++;\n            }\n            else{\n                a[p--]=nums[e]*nums[e];\n                e--;\n            }\n        }\n        return a;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> sortedSquares(vector<int>& nums) {\n        for(int i=0;i<nums.size();i++){\n            nums[i] = nums[i]*nums[i];\n        }\n        sort(nums.begin(),nums.end());\n        return nums;\n    }\n};"
    },
    {
        "title": "Minimum Falling Path Sum",
        "algo_input": "Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.\n\nA falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[2,1,3],[6,5,4],[7,8,9]]\nOutput: 13\nExplanation: There are two falling paths with a minimum sum as shown.\n\n\nExample 2:\n\nInput: matrix = [[-19,57],[-40,-5]]\nOutput: -59\nExplanation: The falling path with a minimum sum is shown.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 &lt;= n &lt;= 100\n\t-100 &lt;= matrix[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n        for row in range(1, len(matrix)):\n            for col in range(0, len(matrix[row])):\n                if col == 0:\n                    matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col])\n                elif col == len(matrix[row]) - 1:\n                    matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col])\n                else:\n                    matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col], matrix[row-1][col+1])\n                \n        return min(matrix[-1])",
        "solution_js": "var minFallingPathSum = function(matrix) {\n    let n = matrix.length;\n    let m = matrix[0].length;\n    let dp = new Array(n).fill(0).map(() => new Array(m).fill(0));\n    \n    // tabulation // bottom-up approach\n    \n    // base case - when i will be 0, dp[0][j] will be matrix[0][j]\n    for(let j = 0; j < m; j++) dp[0][j] = matrix[0][j]\n    \n    for(let i = 1; i < n; i++) {\n        for(let j = 0 ; j < m; j++) {\n            let up = matrix[i][j] + dp[i - 1][j];\n            \n            let upLeft = matrix[i][j];\n            if((j - 1) >= 0) upLeft += dp[i - 1][j - 1]; // if not out of bound\n            else upLeft += 10000; // big enough number\n            \n            let upRight = matrix[i][j];\n            if((j + 1) < m) upRight += dp[i - 1][j + 1]; // if not out of bound\n            else upRight += 10000; // big enough number\n            \n            dp[i][j] = Math.min(up, upLeft, upRight);\n        }\n    }\n    return Math.min(...dp[n - 1]);\n};",
        "solution_java": "class Solution {\n    public int min(int[][] matrix, int[][]dp, int i, int j)\n    {\n        int a,b,c;\n        if(i==0)\n            return matrix[i][j];\n        if(dp[i][j] != Integer.MAX_VALUE)\n            return dp[i][j];\n        if(j==0)\n        {\n            dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1))+matrix[i][j];\n        }\n        else if(j==matrix.length -1)\n        {\n            dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j-1))+matrix[i][j];\n        }\n        else\n        {\n            dp[i][j] = Math.min(Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1)),min(matrix, dp, i-1, j-1))+matrix[i][j];\n        }\n        return dp[i][j];\n    }\n\n    public int minFallingPathSum(int[][] matrix) {\n        int dp[][] = new int[matrix.length][matrix.length];\n        if(matrix.length == 1)\n            return matrix[0][0];\n        for(int i=0;i<matrix.length;i++)\n            for(int j=0;j<matrix.length;j++)\n                dp[i][j] = Integer.MAX_VALUE;\n        int min=Integer.MAX_VALUE;\n        for(int i=0;i<matrix.length; i++)\n        {\n            min = Math.min(min, min(matrix, dp, matrix.length-1,i));\n        }\n        return min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int check( int i , int j , int n  ){\n        if( i <0  || j<0 || i>=n || j>=n )\n            return 0;\n        return 1;\n    }\n    \n    int solve(vector<vector<int>>&mat , int i , int j  , int n , vector<vector<int>>&dp ){\n        \n        if(not check( i , j , n ))\n            return 999999;\n        \n        if(i == n-1 && j < n  )return mat[i][j];\n        \n        if(dp[i][j]!= -1 )\n            return dp[i][j];\n        \n        \n        int op_1 = mat[i][j] + solve(mat , i+1,  j - 1 , n , dp );\n        int op_2 = mat[i][j] + solve(mat , i+1 , j  ,    n , dp );\n        int op_3 = mat[i][j] + solve(mat , i+1 , j + 1 , n , dp );\n        \n        \n        return dp[i][j] =  min( {op_1 , op_2 , op_3} );\n        \n        \n    }\n    \n    int minFallingPathSum(vector<vector<int>>& matrix) {\n        int n = matrix[0].size();\n        \n//         vector<vector<int>>dp(n+1 , vector<int>(n +1 , -1 ));\n//         int ans =  INT_MAX;\n//         for(int i = 0  ; i<n ; ++i )\n//             ans = min( ans , solve( matrix , 0, i , n , dp ));\n        \n        \n        \n        vector<vector<int>>dp(n , vector<int>(n, 0));\n        for( int i =0  ; i<n ; ++i )\n            dp[0][i] = matrix[0][i];\n        \n        \n        for( int i =1 ; i<n ; ++i ){\n            for( int j = 0  ; j<n ; ++j ){\n                \n                if(j-1>=0 && j+1 < n )\n                    dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] ,  dp[i-1][j] , dp[i-1][j+1] });\n                else if(j == 0 )\n                     dp[i][j] = matrix[i][j] + min( { dp[i-1][j] , dp[i-1][j+1] });\n                else if(j == n-1 )\n                     dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] ,  dp[i-1][j] });\n            }\n        }\n        \n        int ans = INT_MAX;\n        for( int i = 0  ; i<n ; ++i )\n            ans = min( ans , dp[n-1][i]);\n        \n        \n        \n        \n        return ans ;\n    }\n};"
    },
    {
        "title": "Count Number of Bad Pairs",
        "algo_input": "You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i &lt; j and j - i != nums[j] - nums[i].\n\nReturn the total number of bad pairs in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,1,3,3]\nOutput: 5\nExplanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: There are no bad pairs.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def countBadPairs(self, nums: List[int]) -> int:\n        nums_len = len(nums)\n        count_dict = dict()\n        for i in range(nums_len):\n            nums[i] -= i\n            if nums[i] not in count_dict:\n                count_dict[nums[i]] = 0\n            count_dict[nums[i]] += 1\n        \n        count = 0\n        for key in count_dict:\n            count += math.comb(count_dict[key], 2)\n        return math.comb(nums_len, 2) - count",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countBadPairs = function(nums) {\n    let map={},goodPair=0;\n    for(let i=0;i<nums.length;i++){\n        let value = nums[i]-i;\n        if(map[value]!==undefined){\n            goodPair += map[value];\n            map[value]++;\n        }else{\n            map[value]=1;\n        }\n    }\n    let n =  nums.length; \n    let totalPairs = n*(n-1)/2;\n    return totalPairs-goodPair;\n};",
        "solution_java": "class Solution {\n    public long countBadPairs(int[] nums) {\n        HashMap<Integer, Integer> seen = new HashMap<>();\n        long count = 0;\n        for(int i = 0; i < nums.length; i++){\n            int diff = i - nums[i];\n            if(seen.containsKey(diff)){\n                count += (i - seen.get(diff));\n            }else{\n                count += i;\n            }\n            seen.put(diff, seen.getOrDefault(diff, 0) + 1);\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long countBadPairs(vector<int>& nums) {\n        \n        //j - i != nums[j] - nums[i] means  nums[i]-i != nums[j]-j\n        map<long long,long long >mp;\n        for(int i=0;i<nums.size();i++)\n        {\n            nums[i] = nums[i]-i;\n            \n            mp[nums[i]]++;\n        }\n        long long  n = nums.size();\n        long long totalPair = n*(n-1)/2;\n        \n        for(auto& it:mp)\n        {\n            if(it.second>1)\n            {\n                totalPair -= (it.second)*(it.second-1)/2;\n            } \n        }\n        \n        \n        \n        return totalPair;\n    }\n};"
    },
    {
        "title": "Remove Outermost Parentheses",
        "algo_input": "A valid parentheses string is either empty \"\", \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.\n\n\n\tFor example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\n\n\nA valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.\n\nGiven a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.\n\nReturn s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"(()())(())\"\nOutput: \"()()()\"\nExplanation: \nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\n\n\nExample 2:\n\nInput: s = \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation: \nThe input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\n\n\nExample 3:\n\nInput: s = \"()()\"\nOutput: \"\"\nExplanation: \nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either '(' or ')'.\n\ts is a valid parentheses string.\n\n",
        "solution_py": "class Solution:\n    def removeOuterParentheses(self, s: str) -> str:\n        c=0\n        res=''\n        for i in s:\n            if i==')' and c==1:\n                c=c-1\n            elif i=='(' and c==0:\n                c=c+1\n            elif i=='(':\n                res=res+'('\n                c=c+1\n            elif i==')':\n                res=res+')'\n                c=c-1\n        return res",
        "solution_js": "var removeOuterParentheses = function(s) {\n    let open = -1, ans = \"\", stack = [];\n    for(let c of s) {\n        if(c == '(') {\n            // open for top level open\n            if(open != -1) ans += c;\n            stack.push(open)\n            open++;\n        } else {\n            open = stack.pop();\n            // close for top level open\n            if(open != -1) ans += c;\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public String removeOuterParentheses(String s) {\n    // if '(' check stack size > 0 add ans else not add ans\n        // if ')' check stack size > 0 add ans else not add ans\n        Stack<Character> st = new Stack<>();\n        StringBuilder sb = new StringBuilder();\n        for(int i=0;i<s.length();i++){\n            char ch = s.charAt(i);\n\n            if(ch == '('){\n                if(st.size() > 0){\n                    sb.append(ch);\n                }\n                st.push(ch);\n            }\n\n            else{\n                st.pop();\n                if(st.size() > 0){\n                    sb.append(ch);\n                }\n            }\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    stack<char>p;\n    int count=0;\n    string removeOuterParentheses(string s) {\n        string ans={};\n\n        for(auto &i:s){\n            if(i=='(' && count==0){\n                p.push(i);\n                count++;\n            }\n            else if (i=='(' && count!=0){\n                ans+='(';\n                p.push(i);\n                count++;\n            }\n            else{\n                count--;\n                p.pop();\n                if(count>0) ans+=')';\n            }\n            \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Split Array Largest Sum",
        "algo_input": "Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.\n\nWrite an algorithm to minimize the largest sum among these m subarrays.\n\n&nbsp;\nExample 1:\n\nInput: nums = [7,2,5,10,8], m = 2\nOutput: 18\nExplanation:\nThere are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8],\nwhere the largest sum among the two subarrays is only 18.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5], m = 2\nOutput: 9\n\n\nExample 3:\n\nInput: nums = [1,4,4], m = 3\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 106\n\t1 &lt;= m &lt;= min(50, nums.length)\n\n",
        "solution_py": "class Solution:\n    def splitArray(self, nums: List[int], m: int) -> int:\n        lo, hi = max(nums), sum(nums)\n        while lo < hi:\n            mid = (lo+hi)//2\n            tot, cnt = 0, 1\n            for num in nums:\n                if tot+num<=mid: \n                    tot += num\n                else:\n                    tot = num\n                    cnt += 1\n            if cnt>m: lo = mid+1\n            else: hi = mid\n        return hi",
        "solution_js": "var splitArray = function(nums, m) {\nconst n = nums.length;\nvar mat = [];\nvar sumArr = [nums[0]];\nfor(let i=1; i<n; i++){\n    sumArr.push(sumArr[i-1]+nums[i]);//find prefix sum\n}\nmat.push(sumArr);\nfor(let i=0; i<n-1;i++){//form prefix matrix, i.e. every row i shows prefix sum starting from i\n    let arr = new Array(n).fill(0);\n    for(let j=i+1; j<n; j++){\n        arr[j] = sumArr[j] - sumArr[i];\n    }\n    mat.push(arr);\n}\nlet memo = new Map();\nlet recursion = (m,lastPartition) => {// recursive partition finder\n    if(memo[m+'_'+lastPartition]!==undefined){\n        return memo[m+'_'+lastPartition];//memoised\n    }\n    if(m==1){//base case, only 1 partition left\n        memo[m+'_'+lastPartition] = mat[lastPartition][mat[0].length-1];\n        return memo[m+'_'+lastPartition];\n    }\n    let min = Infinity;\n    let maxSum = -Infinity;\n    let lastval = Infinity;\n    for(let i = lastPartition; i<=n-m; i++){//for mth partition, find the min sum for all possible partition placements\n        while(i>0 && i<n-m && mat[lastPartition][i] == lastval) i++;//if a large set of values are repeating, i.e. a lot of 0s in original array, skip them\n        lastval = mat[lastPartition][i];\n        maxSum = Math.max(mat[lastPartition][i],recursion(m-1,i+1));//max of current subarray sum with max from the rest of the partitions\n        min = Math.min(min, maxSum);//minimum sum for all the possible partition values\n    }\n    memo[m+'_'+lastPartition] = min;\n    return memo[m+'_'+lastPartition];\n}\nreturn recursion(m,0);\n};",
        "solution_java": "class Solution {\n    int[] nums;\n    public int splitArray(int[] nums, int m) {\n        this.nums = nums;\n        int low = 0, high = 0, min = Integer.MAX_VALUE;\n        for(int i=0;i<nums.length;i++){\n            low = Math.max(low, nums[i]);\n            high += nums[i];\n        }\n        while(low <= high) {\n            int mid = (low + high) / 2;\n            if(required_no_of_chunks(mid, m)){\n               min = Math.min(min, mid);\n               high = mid - 1;\n            }\n            else low = mid + 1;\n        }\n        return min;\n    }\n    \n    private boolean required_no_of_chunks(int mid, int m){\n        int chunks = 0, i=0;\n        while(i < nums.length){\n            int val = 0;\n            while(i < nums.length && nums[i] + val <= mid) val += nums[i++];\n            chunks++;\n        }\n        return chunks <= m;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int splitArray(vector<int>& nums, int m) {\n        long long low = 0;\n        long long res =0;\n        long long high = 1000000005;\n        while(low<=high){\n            long long mid = (low+high)/2;\n            int cnt = 1;\n            long long current_sum = 0;\n            int can = 1;\n            for(auto num: nums){\n                if(num > mid){\n                    can = 0;\n                    break;\n                }\n                if(current_sum+num>mid){\n                    cnt ++;\n                    current_sum = 0;\n                }\n                current_sum += num;\n            }\n            if(can==1){\n                if(cnt>m){\n                    low = mid+1;\n                }\n                else{\n                    res = mid;\n                    high = mid-1;\n                }\n            }\n            else{\n                low = mid+1;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Largest 1-Bordered Square",
        "algo_input": "Given a 2D grid of 0s and 1s, return the number of elements in&nbsp;the largest square&nbsp;subgrid that has all 1s on its border, or 0 if such a subgrid&nbsp;doesn't exist in the grid.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 9\n\n\nExample 2:\n\nInput: grid = [[1,1,0,0]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= grid.length &lt;= 100\n\t1 &lt;= grid[0].length &lt;= 100\n\tgrid[i][j] is 0 or 1\n",
        "solution_py": "class Solution:\n    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n        m = len(grid)\n        n = len(grid[0])\n        dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)]\n        for i in range(m):\n            for j in range(n):\n                if i > 0:\n                    if grid[i][j] == 1:\n                        dp[i][j][1] = dp[i - 1][j][1] + 1\n                if j > 0:\n                    if grid[i][j] == 1:\n                        dp[i][j][0] = dp[i][j - 1][0] + 1\n        for i in range(m - 1, -1, -1):\n            for j in range(n - 1, -1, -1):\n                if i < m - 1:\n                    if grid[i][j] == 1:\n                        dp[i][j][2] = dp[i + 1][j][2] + 1\n                if j < n - 1:\n                    if grid[i][j] == 1:\n                        dp[i][j][3] = dp[i][j + 1][3] + 1\n        mside = min(m, n)\n        for l in range(mside - 1, -1, -1):\n            for i in range(m - l):\n                for j in range(n - l):\n                    if min(dp[i][j][2], dp[i][j][3], dp[i + l][j + l][0], dp[i + l][j + l][1]) >= l + 1:\n                        return (l + 1) * (l + 1)\n        return 0",
        "solution_js": "var largest1BorderedSquare = function(grid) {\n  let m = grid.length, n = grid[0].length;\n  let top = Array(m).fill(0).map(() => Array(n).fill(0));\n  let left = Array(m).fill(0).map(() => Array(n).fill(0));\n  for (let i = 0; i < m; i++) {\n    for (let j = 0; j < n; j++) {\n      if (grid[i][j] === 1) {\n        left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;\n        top[i][j] = i > 0 ? top[i - 1][j] + 1 : 1;\n      }\n    }\n  }\n\n  let ans = 0;\n  for (let i = 0; i < m; i++) {\n    for (let j = 0; j < n; j++) {\n      let size = Math.min(top[i][j], left[i][j]);\n      for (let k = size; k > 0; k--) {\n        let bottomLeftTop = top[i][j - k + 1];\n        let topRightLeft = left[i - k + 1][j];\n        if (bottomLeftTop >= k && topRightLeft >= k) {\n          ans = Math.max(ans, k * k);\n          break;\n        }\n      }\n    }\n  }\n  return ans;\n};",
        "solution_java": "class Solution {\n    public int largest1BorderedSquare(int[][] grid) {\n        int m=grid.length;\n        int n=grid[0].length;\n\t\t// rows[r][c] is the length of the line ended at [r,c] on row r\n        int[][] rows=new int[m][n];        \n\t\t// the length of the line ended at [r,c] on colume c\n        int[][] cols=new int[m][n];\n        int res=0;\n        for(int r=0;r<m;r++){\n            for(int c=0;c<n;c++){\n                if(grid[r][c]==0){\n                    rows[r][c]=0;\n                    cols[r][c]=0;\n                }else{\n                    rows[r][c]=c==0?1:rows[r][c-1]+1;\n                    cols[r][c]=r==0?1:cols[r-1][c]+1;\n                    if(res>=rows[r][c]||res>=cols[r][c]){\n                        continue;\n                    }\n                    res=Math.max(res,getD(rows,cols,r,c));\n                }\n            }\n        }\n        return res*res;\n    }\n    \n\t// get the dimension of the largest square which bottom-right point is [row,col]\n    private int getD(int[][] rows,int[][] cols,int row,int col){\n        int len=Math.min(rows[row][col],cols[row][col]);\n        for(int i=len-1;i>=0;i--){\n            if(rows[row-i][col]>i && cols[row][col-i]>i){\n                return i+1;\n            }\n        }\n        return 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largest1BorderedSquare(vector<vector<int>>& g) {\n        int n=g.size();\n        int m=g[0].size();\n        int ver[n][m]; // to store lenght of continuous 1's vertically\n        int hor[n][m]; // to store lenght of continuous 1's horizontally\n\t\t\n\t\t// fill vertical table\n        for(int i=n-1;i>=0;i--){\n            for(int j=0;j<m;j++){\n                if(g[i][j]==1){\n                    if(i==n-1) ver[i][j]=1;\n                    else ver[i][j]=ver[i+1][j]+1;\n                }\n                else ver[i][j]=0;\n            }\n        }\n        \n\t\t// fill horizontal table\n        for(int i=n-1;i>=0;i--){\n            for(int j=m-1;j>=0;j--){\n                if(g[i][j]==1){\n                    if(j==m-1) hor[i][j]=1;\n                    else hor[i][j]=hor[i][j+1]+1;\n                }\n                else hor[i][j]=0;\n            }\n        }\n        \n\t\t// Iterate through the all i and j and find best solution\n        int ans=0;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(!g[i][j]) continue;\n                int temp=1;\n                int k=min(hor[i][j],ver[i][j]);\n                for(int p=1;p<k;p++){\n                    int mn = min(hor[i+p][j],ver[i][j+p]);\n                    if(mn>=p+1) temp=p+1;\n                }\n                ans=max(ans,temp);\n            }\n        }\n        ans*=ans;\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "String Compression",
        "algo_input": "Given an array of characters chars, compress it using the following algorithm:\n\nBegin with an empty string s. For each group of consecutive repeating characters in chars:\n\n\n\tIf the group's length is 1, append the character to s.\n\tOtherwise, append the character followed by the group's length.\n\n\nThe compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.\n\nAfter you are done modifying the input array, return the new length of the array.\n\nYou must write an algorithm that uses only constant extra space.\n\n&nbsp;\nExample 1:\n\nInput: chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput: Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation: The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".\n\n\nExample 2:\n\nInput: chars = [\"a\"]\nOutput: Return 1, and the first character of the input array should be: [\"a\"]\nExplanation: The only group is \"a\", which remains uncompressed since it's a single character.\n\n\nExample 3:\n\nInput: chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput: Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation: The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= chars.length &lt;= 2000\n\tchars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.\n\n",
        "solution_py": "class Solution:\n    def compress(self, chars: List[str]) -> int:\n        stri = ''\n        stack = [chars.pop(0)]\n        \n        while chars:\n            p = chars.pop(0)\n            \n            if p in stack:\n                stack.append(p)\n            else:\n                stri = stri + stack[-1] + str(len(stack) if len(stack) > 1 else '')\n                stack = [p] \n                \n        o = list(stri + stack[-1] + str(len(stack) if len(stack) > 1 else ''))\n        \n        for i in o:\n            chars.append(i)",
        "solution_js": "var compress = function(chars) {\n    for(let i = 0; i < chars.length; i++){\n        let count = 1\n        while(chars[i] === chars[i+count]){\n            delete chars[i+count]\n            count++\n        }\n        if(count > 1){\n            let count2 = 1\n            String(count).split('').forEach((a) =>{\n                chars[i+count2] = a\n                count2++\n            })\n        }\n        i = i + count -1\n    }\n    return chars.flat().filter((x) => x).length\n};",
        "solution_java": "class Solution {\n    public int compress(char[] chars) {\n        int index = 0;\n        int i = 0;\n\n        while (i < chars.length) {\n            int j = i;\n\n            while (j < chars.length && chars[j] == chars[i]) {\n                j++;\n            }\n\n            chars[index++] = chars[i];\n\n            if (j - i > 1) {\n                String count = j - i + \"\";\n\n                for (char c : count.toCharArray()) {\n                    chars[index++] = c;\n                }\n            }\n\n            i = j;\n        }\n\n        return index;\n    }\n}\n\n// TC: O(n), SC: O(1)",
        "solution_c": "class Solution {\npublic:\n\nvoid add1(vector<int>& arr) {\n    \n    if(arr.back() < 9) {\n        arr.back()++;\n        return ;\n    }\n    \n    reverse(begin(arr),end(arr));\n    int carry = 1;\n    \n    for(int i=0;i<arr.size();i++) {\n        \n        if(arr[i] < 9) {arr[i]++;carry=0;break;}\n        \n        arr[i] = 0;\n        carry = 1;\n    }\n    \n    if(carry == 1) arr.push_back(1);\n    reverse(begin(arr),end(arr));\n}\n\nint compress(vector<char>& chars) {\n    \n    int i=0;\n    for(int j=0;j<chars.size();j++) {\n        \n        if(j == chars.size()-1 or chars[j] != chars[j+1]) {\n            chars[i++] = chars[j];\n        }\n        \n        else {\n            \n            vector<int> cnt{0};\n            char ch = chars[j];\n            while(j < chars.size()and chars[j] == ch) {\n                j++;\n                add1(cnt);\n            }\n            \n            j--; // bcoz j will be incremented in for loop updation condition.\n            chars[i++] = ch;\n            \n            for(auto& it:cnt)\n                chars[i++] = '0'+it;\n            \n        }\n    }\n    chars.erase(chars.begin()+i,chars.end());\n    return i;\n}"
    },
    {
        "title": "Step-By-Step Directions From a Binary Tree Node to Another",
        "algo_input": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.\n\nFind the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction:\n\n\n\t'L' means to go from a node to its left child node.\n\t'R' means to go from a node to its right child node.\n\t'U' means to go from a node to its parent node.\n\n\nReturn the step-by-step directions of the shortest path from node s to node t.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput: \"UURL\"\nExplanation: The shortest path is: 3 → 1 → 5 → 2 → 6.\n\n\nExample 2:\n\nInput: root = [2,1], startValue = 2, destValue = 1\nOutput: \"L\"\nExplanation: The shortest path is: 2 → 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t2 &lt;= n &lt;= 105\n\t1 &lt;= Node.val &lt;= n\n\tAll the values in the tree are unique.\n\t1 &lt;= startValue, destValue &lt;= n\n\tstartValue != destValue\n\n",
        "solution_py": "class Solution:\n    def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n        def find(n: TreeNode, val: int, path: List[str]) -> bool:\n            if n.val == val:\n                return True\n            if n.left and find(n.left, val, path):\n                path += \"L\"\n            elif n.right and find(n.right, val, path):\n                path += \"R\"\n            return path\n        s, d = [], []\n        find(root, startValue, s)\n        find(root, destValue, d)\n        while len(s) and len(d) and s[-1] == d[-1]:\n            s.pop()\n            d.pop()\n        return \"\".join(\"U\" * len(s)) + \"\".join(reversed(d))",
        "solution_js": "var getDirections = function(root, startValue, destValue) {\n    const getPath = (node, value, acc='') => {\n        if (node === null) {\n            return '';\n        } else if (node.val === value) {\n            return acc;\n        } else {\n            return getPath(node.left, value, acc + 'L') + getPath(node.right, value, acc + 'R')\n        }\n    }\n    \n\t// generate the paths\n    let startPath = getPath(root, startValue);\n    let destPath = getPath(root, destValue);\n    \n    // find the lowest common ancestor\n    let i = 0;\n    for (; i < startPath.length && i < destPath.length && startPath[i] === destPath[i]; i++);\n    \n\t// output the final path\n    let output = '';\n    for (let j = i; j < startPath.length; j++) {\n        output += 'U';\n    }\n    \n    return output + destPath.substring(i);\n};",
        "solution_java": "class Solution {\n    \n    private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) {\n        if(currNode == null) return false;\n        if(currNode.val == destVal) return true;\n        if(DFS(currNode.left, path, destVal)) path.append(\"L\");\n        else if(DFS(currNode.right, path, destVal)) path.append(\"R\");\n        return path.length() > 0;\n    }\n    \n    public String getDirections(TreeNode root, int startValue, int destValue) {\n        StringBuilder startToRoot = new StringBuilder();\n        StringBuilder endToRoot = new StringBuilder();\n        \n        DFS(root, startToRoot, startValue);\n        DFS(root, endToRoot, destValue);\n        \n        int i = startToRoot.length(), j = endToRoot.length();\n        int cnt = 0;\n        while(i > 0 && j > 0 && startToRoot.charAt(i-1) == endToRoot.charAt(j-1)) {\n            cnt++; i--; j--;\n        }\n        \n        String sPath = \"U\".repeat(startToRoot.length() - cnt);\n        String ePath = endToRoot.reverse().toString().substring(cnt, endToRoot.length());\n        \n        return sPath + ePath;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool search(TreeNode* root, int target, string &s){\n        if(root==NULL) {\n            return false;\n        }\n        if(root->val==target) {\n            return true;\n        }\n        \n        bool find1=search(root->left,target, s+='L');  // search on left side\n        if(find1) return true;\n        s.pop_back(); // backtracking step\n        \n        bool find2= search(root->right,target, s+='R'); // search on right side\n        if(find2) return true;\n        s.pop_back(); // backtracking step\n        return false;\n    }\n  \n     TreeNode* lca(TreeNode* root ,int n1 ,int n2)\n    {\n       if(root==NULL)\n       return NULL;\n       if(root->val==n1 or root->val==n2)\n       return root;\n       \n       TreeNode* left=lca(root->left,n1,n2);\n       TreeNode* right=lca(root->right,n1,n2);\n       \n       if(left!=NULL && right!=NULL)\n       return root;\n       if(left)\n       return left;\n       if(right)\n       return right;\n       \n       return NULL; // not present in tree\n       \n    }\n    string getDirections(TreeNode* root, int startValue, int destValue) {\n        TreeNode* temp=lca(root,startValue,destValue);\n        \n        string s1,s2;\n        search(temp,startValue,s1);\n        search(temp,destValue,s2);\n        for(auto &it:s1){\n            it='U';\n        }\n        return s1+s2;\n    }\n};"
    },
    {
        "title": "Number of People Aware of a Secret",
        "algo_input": "On day 1, one person discovers a secret.\n\nYou are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.\n\nGiven an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, delay = 2, forget = 4\nOutput: 5\nExplanation:\nDay 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)\n\n\nExample 2:\n\nInput: n = 4, delay = 1, forget = 3\nOutput: 6\nExplanation:\nDay 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 1000\n\t1 &lt;= delay &lt; forget &lt;= n\n\n",
        "solution_py": "```class Solution:\n    def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n        table = [0]*(forget+1)\n        table[1] = 1\n        days = 1\n        while days<=n-1:\n            count = 0\n            for k in range(forget-1,-1,-1):\n                if k+1>delay:\n                    table[k+1] = table[k]\n                    count+=table[k]\n                elif k+1<=delay:\n                    table[k+1] = table[k]\n            table[1] = count\n            days+=1\n        count = 0\n        for k in range(1,forget+1):\n            count+=table[k]\n        return count%(pow(10,9)+7)\n\t\t\nTC---O(forget*n)\nsc---O(forget)\n            ",
        "solution_js": "/**\n * @param {number} n\n * @param {number} delay\n * @param {number} forget\n * @return {number}\n */\nvar peopleAwareOfSecret = function(n, delay, forget) {\n    const dp=new Array(n+1).fill(0);\n    let numberOfPeopleSharingSecret = 0;\n    let totalNumberOfPeopleWithSecret = 0;\n    const MOD = 1000000007n;\n    \n    dp[1]=1; // as on day one only one person knows the secret\n    \n    for(let i=2;i<=n;i++){\n        const numberOfNewPeopleSharingSecret = dp[Math.max(i-delay,0)];\n        const numberOfPeopleForgettingSecret = dp[Math.max(i-forget,0)];\n        numberOfPeopleSharingSecret = BigInt(numberOfPeopleSharingSecret) + \n            (   BigInt(numberOfNewPeopleSharingSecret) \n              - BigInt(numberOfPeopleForgettingSecret) \n              + BigInt(MOD)\n            ) % BigInt(MOD);\n        \n        dp[i] = numberOfPeopleSharingSecret;\n    }\n    \n    for(let i=n-forget+1;i<=n;i++){\n       totalNumberOfPeopleWithSecret = \n           (BigInt(totalNumberOfPeopleWithSecret) + BigInt(dp[i])) % BigInt(MOD); \n    }\n    \n    return totalNumberOfPeopleWithSecret;\n};",
        "solution_java": "class Solution {\n    public int peopleAwareOfSecret(int n, int delay, int forget) {\n        long mod = 1000000007L;\n        long[] shares = new long[n + 1];\n        long[] forgets = new long[n + 1];\n\n        if (delay < n) {\n            shares[delay + 1] = 1;\n        }\n        if (forget < n) {\n            forgets[forget + 1] = 1;\n        }\n\n        long shareToday = 0;\n        long peopleKnow = 1;\n        for (int i = delay; i <= n; i++) {\n            shareToday += shares[i] % mod;\n            shareToday -= forgets[i] % mod;\n\n            peopleKnow -= forgets[i] % mod;\n            peopleKnow += shareToday % mod;\n\n            if (i + delay < n + 1) {\n                shares[i + delay] += shareToday % mod;\n            }\n            if (i + forget < n + 1) {\n                forgets[i + forget] += shareToday % mod;\n            }\n        }\n\n        return (int) (peopleKnow % mod);\n    }\n}",
        "solution_c": "static int MOD=1e9+7;\nclass Solution {\npublic:\n    int delay,forget;\n    vector<long> memo;\n    // Total number of people who would have found out about the secret by the nth day.\n    long dp(int n) {\n        if(!n)\n            return 0;\n        if(memo[n]!=-1)  // Return cached result if exists.\n            return memo[n];\n\t\t// Current contribution of 1 person who knows the secret\n        long result=1;\n        for(int i=delay;i<forget;i++)       // Number of people that the secret will be forwarded to\n            if(n-i>=0)\n                result=(result+dp(n-i))%MOD;\n        return memo[n]=result;\n    }\n    int peopleAwareOfSecret(int n, int delay, int forget) {\n        this->delay=delay;\n        this->forget=forget;\n        memo.resize(n+1,-1);\n        return (dp(n)-dp(n-forget)+MOD)%MOD;    // Subtract the people who found out by the `n-forget` day as observed.\n    }\n};"
    },
    {
        "title": "Minimum Difference in Sums After Removal of Elements",
        "algo_input": "You are given a 0-indexed integer array nums consisting of 3 * n elements.\n\nYou are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:\n\n\n\tThe first n elements belonging to the first part and their sum is sumfirst.\n\tThe next n elements belonging to the second part and their sum is sumsecond.\n\n\nThe difference in sums of the two parts is denoted as sumfirst - sumsecond.\n\n\n\tFor example, if sumfirst = 3 and sumsecond = 2, their difference is 1.\n\tSimilarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.\n\n\nReturn the minimum difference possible between the sums of the two parts after the removal of n elements.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,1,2]\nOutput: -1\nExplanation: Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1. \n\n\nExample 2:\n\nInput: nums = [7,9,5,8,1,3]\nOutput: 1\nExplanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.\n\n\n&nbsp;\nConstraints:\n\n\n\tnums.length == 3 * n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minimumDifference(self, nums: List[int]) -> int:\n        h=heapq\n        k=len(nums)//3\n        min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, []\n        h.heapify(max_heap) , h.heapify(min_heap)\n        for x in nums[:-k]:\n            h.heappush(min_heap,-x)\n            min_sum+=x\n            if len(min_heap)>k: min_sum+=h.heappop(min_heap)\n            min_sol.append(min_sum)\n        for x in nums[::-1][:-k]:\n            h.heappush(max_heap,x)\n            max_sum+=x\n            if len(max_heap)>k: max_sum-=h.heappop(max_heap)\n            max_sol.append(max_sum)\n        min_sol =min_sol[k-1:]\n        max_sol=max_sol[k-1:][::-1]\n        return min( min_value - max_value for min_value , max_value in zip(min_sol,max_sol) )",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumDifference = function(nums) {\n//Creating heap \n    class Heap{\n        constructor(type){\n            this.type = type;\n            this.data = [];\n            this.data[0] = undefined;\n        }\n        print(){\n            for(let i=1;i<this.data.length;i++){\n                console.log(this.data[i])\n            }\n        }\n        getSize(){\n            return this.data.length-1;\n        }\n        insert(value){\n            this.data.push(value);\n            if(this.data.length==2){\n                return ;\n            }\n            let lastIndex = this.data.length-1;\n            while(this.data[Math.floor(lastIndex/2)]!==undefined && this.compare(this.data[lastIndex],this.data[Math.floor(lastIndex/2)])>0){\n                let temp = this.data[Math.floor(lastIndex/2)];\n                this.data[Math.floor(lastIndex/2)] = this.data[lastIndex];\n                this.data[lastIndex] = temp;\n                lastIndex = Math.floor(lastIndex/2);\n            }\n        }\n        //This returns a positive number if a is greater than b. Here meaing of being greater depends on the type of heap. For max heap it will return positive number if a>b and for min heap it will return positive number if a<b . \n        compare(a,b){\n            if(this.type===\"min\"){\n                return b-a;\n            }else{\n                return a-b;\n            }\n        }\n        removeTop(){\n            let max = this.data[1];\n            if(this.getSize()>1){\n                this.data[1] = this.data.pop();\n                this.heapify(1);\n            }else{//If the size is 0 then just remove the element, no shifting and hipify will be applicable\n                this.data.pop();\n            }\n            return max;\n        }\n        getTop(){\n            let max = null;\n            if(this.getSize()>=1){\n                max = this.data[1];\n            }\n            return max;\n        }\n        heapify(pos){\n            if(pos*2>this.data.length-1){\n                //That means element at index 'pos' is not having any child\n                return;\n            }\n            if(\n                (this.data[pos*2]!==undefined && this.compare(this.data[pos*2],this.data[pos])>0)\n              || (this.data[pos*2+1]!==undefined && this.compare(this.data[pos*2+1],this.data[pos])>0)\n              ){\n                if(this.data[pos*2+1]===undefined || this.compare(this.data[pos*2+1],this.data[pos*2])<=0){\n                    let temp = this.data[pos*2];\n                    this.data[pos*2] = this.data[pos];\n                    this.data[pos] = temp;\n                    this.heapify(pos*2);\n                }else{\n                    let temp = this.data[pos*2+1];\n                    this.data[pos*2+1] = this.data[pos];\n                    this.data[pos] = temp;\n                    this.heapify(pos*2+1);\n                }\n            }\n        }\n    }\n    let maxHeap=new Heap(),minHeap=new Heap('min'),sum=0;\n    let n = nums.length/3,leftArr=[],rightArr=[];\n    for(let i=0;i<2*n;i++){\n        if(maxHeap.getSize()<n){\n            sum += nums[i];\n            maxHeap.insert(nums[i]);\n        }else{\n            if(maxHeap.getTop()>nums[i]){\n                let top = maxHeap.removeTop();\n                sum -= top;\n                sum += nums[i];\n                maxHeap.insert(nums[i]);\n            }\n            \n        }\n        if(maxHeap.getSize()===n){\n            leftArr.push(sum);\n        }\n    }\n    sum=0;\n    for(let i=3*n-1;i>=n;i--){\n        if(minHeap.getSize()<n){\n            sum += nums[i];\n            minHeap.insert(nums[i]);\n        }else{\n            if(minHeap.getTop()<nums[i]){\n                let top = minHeap.removeTop();\n                sum -= top;\n                sum += nums[i];\n                minHeap.insert(nums[i]);\n            }\n            \n        }\n        if(minHeap.getSize()===n){\n            rightArr.push(sum);\n        }\n    }\n    rightArr.reverse();\n    let min = Number.MAX_SAFE_INTEGER;\n    \n    for(let i=0;i<leftArr.length;i++){\n        min = Math.min(min,leftArr[i]-rightArr[i]);\n    }\n    return min;\n};",
        "solution_java": "class Solution {\n    public long minimumDifference(int[] nums) {\n        int n=nums.length; //length of nums\n        int len3=n/3; // 1/3 length\n        long res=Long.MAX_VALUE; // final result;\n        //Try to make first part as min as possible;\n        //first[m] store the value, the min value of the size=len3, from[0,1,..., m];\n        long[] first=new long[n];\n        //Try to make second part as max as possible;\n        //second[m] store the value, the max value of the size=len3, from[m,...,n-1];\n        long[] second=new long[n];\n\n//--------------------for first part compute -------------------------------------\n        //Build max heap for first part;\n        PriorityQueue<Integer> max=new PriorityQueue<Integer>(Comparator.reverseOrder());\n\n        long sum=0;\n\n        // Initialize with the first 1/3 n part.\n        for(int i=0;i<len3;i++){\n            sum+=nums[i];\n            max.add(nums[i]);\n        }\n        //For the second part between 1/3 ~ 2/3. When we move to next index.\n        //we keep the sum as total 1/3n size: each time poll the max one and add the new one;\n        //And we keep tracking the exchange by long[] first;\n        //\n        for(int i=len3;i<=2*len3;i++){\n            first[i]=sum; //add sum from 1/3\n            max.add(nums[i]); //put new one in queue;\n            sum+=nums[i]; //sum + new one;\n            sum-=max.poll(); //sum - max one;\n        }\n//--------------------for second part compute -----------------------\n        sum=0;\n        //Build min heap for first part;\n        PriorityQueue<Integer> min=new PriorityQueue<Integer>();\n        // Initialize with the last 1/3 n part.\n        for(int i=0;i<len3;i++){\n            sum+=nums[n-1-i];\n            min.add(nums[n-1-i]);\n        }\n        //For the second part between 2/3~1/3 When we move to next index:\n        // we keep update the sum with(+ new element, - min element), and update second;\n        for(int i=len3;i<=2*len3;i++){\n            second[n-i]=sum;\n            min.add(nums[n-1-i]);\n            sum+=nums[n-1-i];\n            sum-=min.poll();\n        }\n//-----------------compute the final result------------\n\n        //find the max value in second part [ i,..., n-1];\n        //find the min value in first part [0,....,i];\n        // find the result;\n        for(int i=len3;i<=2*len3;i++){\n            res=Math.min(res,first[i]-second[i]);\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long minimumDifference(vector<int>& nums) {\n        int N = nums.size();\n        int n = N/3;\n        priority_queue<int> pq;\n        map<int, long long> m;\n        long long sum = 0;\n        for(int i=0;i<n;i++){\n            sum += nums[i];\n            pq.push(nums[i]);\n        }\n        for(int i=0;i<=n;i++){\n            if(i == 0){\n                m[i] = sum;\n            }\n            else{\n                pq.push(nums[n+i-1]);\n                sum += nums[i+n-1];\n                sum -= pq.top();\n                pq.pop();\n                m[i] = sum;\n            }\n        }\n        sum = 0;\n        priority_queue<int, vector<int>, greater<int>> p;\n        for(int i=N-1;i>N-1-n;i--){\n            sum += nums[i];\n            p.push(nums[i]);\n        }\n        for(int i=0;i<=n;i++){\n            if(i == 0){\n                m[n-i] -= sum;\n            }\n            else{\n                p.push(nums[N-n-i]);\n                sum += nums[N-n-i];\n                sum -= p.top();\n                p.pop();\n                m[n-i] -= sum;\n            }\n        }\n        long long ans = 9223372036854775807;\n        for(auto it : m){\n            ans = min(ans, it.second);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Reverse String II",
        "algo_input": "Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.\n\nIf there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.\n\n&nbsp;\nExample 1:\nInput: s = \"abcdefg\", k = 2\nOutput: \"bacdfeg\"\nExample 2:\nInput: s = \"abcd\", k = 2\nOutput: \"bacd\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of only lowercase English letters.\n\t1 &lt;= k &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def reverseStr(self, s: str, k: int) -> str:\n        a=list(s)\n        for i in range(0,len(a),2*k):\n            a[i:i+k]=a[i:i+k][::-1]\n        print(a)\n        return(\"\".join(a))",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar reverseStr = function(s, k) {\n    const sArr = s.split('');\n\n    let start = 0;\n    let end = k - 1;\n\n    const swapBlock = (start, end) => {\n        while (start < end) {\n            [sArr[start], sArr[end]] = [sArr[end], sArr[start]];\n\n            start++;\n            end--;\n        }\n    };\n\n    while (start < end) {\n        swapBlock(start, end);\n\n        start = start + (k * 2);\n        end = sArr[start + (k-1)] ? start + (k-1) : s.length - 1;\n    }\n\n    return sArr.join('');\n};",
        "solution_java": "class Solution {\n    public String reverseStr(String s, int k) {\n        char[] ch=s.toCharArray();\n        int cnt=1,i=0;\n        StringBuilder sb=new StringBuilder();\n        String ans=\"\";\n        if(k>=s.length()){\n            sb.append(s);\n            sb.reverse();\n            return sb.toString();\n        }\n        for(i=0;i<s.length()-k;i+=k){\n            String str=s.substring(i,i+k);\n            if(cnt%2!=0){\n                sb.append(str);\n                sb.reverse();\n                ans+=sb.toString();\n                cnt++;\n                sb=new StringBuilder();\n            }\n            else{\n                ans+=str;\n                cnt++;\n            }\n        }\n        if(cnt%2!=0){\n            sb.append(s.substring(i,s.length()));\n            sb.reverse();\n            ans+=sb.toString();\n        }\n        else{\n            ans+=s.substring(i,s.length());\n        }\n        return ans;\n    }\n}",
        "solution_c": "Time: O(n)  Space: O(1)\n\nclass Solution {\npublic:\n    string reverseStr(string s, int k) {\n        int n=size(s);\n        for(int i=0;i<n;i=i+2*k){\n            int j=i+k-1,k=i;\n            if(j>=n) \n                j=n-1;\n            while(k<(j)){\n                swap(s[k],s[j]);\n                k++,j--;\n            }\n        }\n        return s;\n    }\n};"
    },
    {
        "title": "Find Substring With Given Hash Value",
        "algo_input": "The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:\n\n\n\thash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.\n\n\nWhere val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.\n\nYou are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.\n\nThe test cases will be generated such that an answer always exists.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput: \"ee\"\nExplanation: The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".\n\n\nExample 2:\n\nInput: s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput: \"fbx\"\nExplanation: The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= s.length &lt;= 2 * 104\n\t1 &lt;= power, modulo &lt;= 109\n\t0 &lt;= hashValue &lt; modulo\n\ts consists of lowercase English letters only.\n\tThe test cases are generated such that an answer always exists.\n\n",
        "solution_py": "class Solution:\n    def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n        val = lambda ch : ord(ch) - ord(\"a\") + 1\n        hash, res, power_k = 0, 0, pow(power, k, mod)\n        for i in reversed(range(len(s))):\n            hash = (hash * power + val(s[i])) % mod\n            if i < len(s) - k:\n                hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod\n            res = i if hash == hashValue else res\n        return s[res:res + k]",
        "solution_js": "let arrChar =\"1abcdefghijklmnopqrstuvwxyz\".split(\"\");\nvar subStrHash = function(s, power, modulo, k, hashValue) {\n  \n    for(let i=0;i<s.length;i++){\n        let subStr = s.substring(i,i+k);\n        if(hash(subStr,power,modulo)==hashValue){\n            return subStr;\n        }\n    }\n};\nlet hash = function(str,power,m){\n    let result=0;\n    for(let i=0;i<str.length;i++){\n        result += arrChar.indexOf(str[i])*Math.pow(power,i);\n    }\n    return result%m;\n}",
        "solution_java": "class Solution {\n    public String subStrHash(String s, int power, int modulo, int k, int hashValue) {\n\t\t// calculate all the powers from power^0 till power^k\n\t\t// utilized binary exponentiation\n\t\tlong[] powers = new long[k];\n        for (int i = 0; i < k; i++) \n            powers[i] = binaryExponentiation(power, i, modulo);\n        \n\t\t// pre compute the initial hash from behind.\n\t\t// I have explained at top you why traversing from behind is easy\n        long currentHashValue = 0;\n        int index = s.length() - 1;\n        int powerIndex = k-1;\n        while (index >= s.length() - k) {\n\t\t\t// (a+b) % modulo = ( (a % modulo) + (b % modulo) ) % modulo;\n\t\t\t// do it for k times from behind\n            currentHashValue += ((s.charAt(index--) - 'a' + 1) % modulo * powers[powerIndex--] % modulo) % modulo;\n        }\n        currentHashValue %= modulo;\n        \n        int startIndex = 0;\n        if (currentHashValue == hashValue) {\n            startIndex = s.length() - k;\n        }\n        \n\t\t// I have pre computed already for k values from behind. so start from (length of S - k - 1)\n\t\t// Let's take an example of \"leetcode\" itself\n\t\t// \"de\" is pre computed\n\t\t// point is to add one character from behind and remove one from end (Sliding from back to first)\n\t\t// Modular Arithmetic for (a-b) % modulo = ( (a % modulo) - (b % modulo) + modulo) % modulo;\n\t\t// keep tracking of the start index if hash value matches. That's it.\n        for (int i = s.length() - k - 1; i >= 0; i--) {\n\t\t\t// below line a --> currentHashValue \n\t\t\t// below line b --> (s.charAt(i+k) - 'a' + 1 * powers[k-1])\n            currentHashValue = ((currentHashValue % modulo) - (((s.charAt(i+k) - 'a' + 1) * powers[k-1]) % modulo) + modulo) % modulo;\n\t\t\t// we need to multiply a power once for all\n\t\t\t// MULTIPLICATION\n            currentHashValue = currentHashValue * power;\n\t\t\t// Modular Arithmetic for (a+b) % modulo is below line\n            currentHashValue = (currentHashValue % modulo + (s.charAt(i) - 'a' + 1) % modulo) % modulo;\n            \n            if (currentHashValue == hashValue) {\n                startIndex = i;\n            }\n        }\n        return s.substring(startIndex, startIndex+k);\n    }\n    \n    private long binaryExponentiation(long a, long b, long mod) {\n        a %= mod;\n        long result = 1;\n        while (b > 0) {\n            if (b % 2 == 1)\n                result = result * a % mod;\n            a = a * a % mod;\n            b >>= 1;\n        }\n        return result;\n    }\n}",
        "solution_c": "'''\nclass Solution {\npublic:\n    string subStrHash(string s, int power, int modulo, int k, int hashValue) {\n        int n=s.size();                         \n        long long int sum=0;\n        long long int p=1;\n\t\t// Intializing a window from end of size k \n        for(int i=0;i<k;i++){\n                sum=(sum+((s[n-k+i]-'a'+1)*p));         \n                if(i!=k-1)\n                    p=(p*power)%modulo;\n        }\n\t\t// storing the res when ever we get required answer\n        int res=n-k;   // storing the res when ever we get required answer\n\t\t// slide window to right and removing ith index element and adding (i-k)th index element \n        for(int i=n-1;i>=k;i--)\n\t\t{                                          \n\t\t//removing last element from window\n                sum-=(s[i]-'a'+1)*(p%modulo);               \n\t\t\t\t // dividing by modulo to avoid integer overflow conditions\n                sum=sum%modulo;                  \n\t\t\t\t // muliplying the given string by power\n                sum=sum*(power%modulo);            \n\t\t\t\t // adding (i-k)th element in the window  \n                sum+=s[i-k]-'a'+1;                 \n\t\t\t\t // if sum < 0 then it created problem in modulus thats why making it positive\n            while(sum%modulo<0){                              \n                sum=sum+modulo;\n            }\n            if(sum%modulo==hashValue){\n                res=i-k;                                           // storing the starting window index because we have to return the first string from starting \n            }\n        }\n        return s.substr(res,k);\n    }\n};\n'''"
    },
    {
        "title": "Smallest Missing Genetic Value in Each Subtree",
        "algo_input": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.\n\nThere are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.\n\nReturn an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.\n\nThe subtree rooted at a node x contains node x and all of its descendant nodes.\n\n&nbsp;\nExample 1:\n\nInput: parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput: [5,1,1,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\n\n\nExample 2:\n\nInput: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput: [7,1,1,4,2,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\n\n\nExample 3:\n\nInput: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput: [1,1,1,1,1,1,1]\nExplanation: The value 1 is missing from all the subtrees.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == parents.length == nums.length\n\t2 &lt;= n &lt;= 105\n\t0 &lt;= parents[i] &lt;= n - 1 for i != 0\n\tparents[0] == -1\n\tparents represents a valid tree.\n\t1 &lt;= nums[i] &lt;= 105\n\tEach nums[i] is distinct.\n\n",
        "solution_py": "class Solution:\n    def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n        ans = [1] * len(parents)\n        if 1 in nums:\n            tree = {}\n            for i, x in enumerate(parents):\n                tree.setdefault(x, []).append(i)\n\n            k = nums.index(1)\n            val = 1\n            seen = set()\n\n            while k != -1:\n                stack = [k]\n                while stack:\n                    x = stack.pop()\n                    seen.add(nums[x])\n                    for xx in tree.get(x, []):\n                        if nums[xx] not in seen:\n                            stack.append(xx)\n                            seen.add(nums[xx])\n                while val in seen: val += 1\n                ans[k] = val\n                k = parents[k]\n        return ans",
        "solution_js": "var smallestMissingValueSubtree = function(parents, nums) {\n    let n=parents.length,next=[...Array(n)].map(d=>[]),used={}\n    for(let i=1;i<n;i++)\n        next[parents[i]].push(i)\n    let dfs=(node)=>{\n        if(used[nums[node]])\n            return\n        used[nums[node]]=true\n        for(let child of next[node])\n            dfs(child)\n    }\n    let cur=nums.indexOf(1),leftAt=1,res=[...Array(n)].map(d=>1)\n    while(cur!==-1){\n        dfs(cur)\n        while(used[leftAt])\n            leftAt++\n        res[cur]=leftAt\n        cur=parents[cur]\n    }\n    return res\n};",
        "solution_java": "class Solution {\n    public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n        int n = parents.length;\n        int[] res = new int[n];\n        for (int i = 0; i < n; i++) {\n            res[i] = 1;\n        }\n        \n        int oneIndex = -1;\n        for (int i = 0; i < n; i++) {\n            if (nums[i] == 1) {\n                oneIndex = i;\n                break;\n            }\n        }\n        \n        // 1 not found\n        if (oneIndex == -1) {\n            return res;\n        }\n        \n        Map<Integer, Set<Integer>> graph = new HashMap<>();\n        for (int i = 1; i < n; i++) {\n            Set<Integer> children = graph.getOrDefault(parents[i], new HashSet<Integer>());\n            children.add(i);\n            graph.put(parents[i], children);\n        }\n        \n        Set<Integer> visited = new HashSet<Integer>();\n        \n        int parentIter = oneIndex;\n        int miss = 1;\n        while (parentIter >= 0) {\n            dfs(parentIter, graph, visited, nums);\n            while (visited.contains(miss)) {\n                miss++;\n            }\n            res[parentIter] = miss;\n            parentIter = parents[parentIter];\n        }\n        return res;\n    }\n    \n    public void dfs(int ind, Map<Integer, Set<Integer>> graph, Set<Integer> visited, int []nums) {\n        if (!visited.contains(nums[ind])) {\n            Set <Integer> children = graph.getOrDefault(ind, new HashSet<Integer>());\n        \n            for (int p : children) {\n                dfs(p, graph, visited, nums);\n            }\n            visited.add(nums[ind]);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    unordered_set<int> visited;\n    vector<int> nums ;\n    vector<vector<int>> adj;\n\n    void dfs(int node){\n        for(auto child:adj[node]){\n            if(!visited.count(nums[child])){\n                visited.insert(nums[child]);\n                dfs(child);\n            }\n        }\n    }\n\n    vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {\n        int n = parents.size(), missing = 1;\n        adj.resize(n);\n        vector<int> res;\n        this->nums = nums;\n        res.resize(n,1);\n\n        for(int i=1; i<n; i++) adj[parents[i]].push_back(i);\n\n        int node = -1;\n        for(int i=0; i<n; i++){\n            if(nums[i] == 1) {\n                node = i;\n                break ;\n            }\n        }\n        if(node == -1) return res;\n        while(node != -1) {\n            visited.insert(nums[node]);\n            dfs(node);\n            while(visited.count(missing)) missing++;\n            res[node] = missing;\n            node = parents[node];\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Buddy Strings",
        "algo_input": "Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.\n\nSwapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].\n\n\n\tFor example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\".\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"ab\", goal = \"ba\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.\n\n\nExample 2:\n\nInput: s = \"ab\", goal = \"ab\"\nOutput: false\nExplanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.\n\n\nExample 3:\n\nInput: s = \"aa\", goal = \"aa\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, goal.length &lt;= 2 * 104\n\ts and goal consist of lowercase letters.\n\n",
        "solution_py": "from collections import Counter\n\nclass Solution:\n    def buddyStrings(self, s: str, goal: str) -> bool:\n        if len(s) != len(goal):\n            return False\n        diffCharactersCount = 0\n        diffCharactersInS = []\n        diffCharactersInGoal = []\n        for i in range(len(s)):\n            if s[i] != goal[i]:\n                diffCharactersCount += 1\n                diffCharactersInS.append(s[i])\n                diffCharactersInGoal.append(goal[i])\n        if diffCharactersCount == 2:\n            # if there are only 2 different characters, then they should be swappable\n            if ((diffCharactersInS[0] == diffCharactersInGoal[1]) and (diffCharactersInS[1] == diffCharactersInGoal[0])):\n                return True\n            return False\n        elif diffCharactersCount == 0:\n            # if there is atleast one repeating character in the string then its possible for swap\n            counts = Counter(s)\n            for k,v in counts.items():\n                if v > 1:\n                    return True\n        # if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings\n        return False",
        "solution_js": "var buddyStrings = function(A, B) {\n    if(A.length != B.length) return false;\n    const diff = [];\n    \n    for(let i = 0; i < A.length; i++) {\n        if(A[i] != B[i]) diff.push(i);\n        if(diff.length > 2) return false;\n    }\n    if(!diff.length) return A.length != [...new Set(A)].length;\n    const [i, j] = diff; \n    return A[i] == B[j] && B[i] == A[j];\n};",
        "solution_java": "class Solution {\n    public boolean buddyStrings(String s, String goal) {\n        char a = '\\u0000', b = '\\u0000';\n        char c = '\\u0000', d = '\\u0000';\n        int lenS = s.length();\n        int lenGoal = goal.length();\n        boolean flag = true;\n        HashSet<Character> hset = new HashSet<>();\n\n        if(lenS != lenGoal)\n            return false;\n\n        if(s.equals(goal)){\n            for(int i = 0; i < lenS; i++){\n                if(!hset.contains(s.charAt(i))){\n                    hset.add(s.charAt(i));\n                }\n                else\n                    return true;\n            }\n            return false;\n        }\n        else{\n            for(int i = 0; i < lenS; i++){\n                if(s.charAt(i) == goal.charAt(i)){\n                    continue;\n                }\n                if(a == '\\u0000'){\n                    a = s.charAt(i);\n                    c = goal.charAt(i);\n                    continue;\n                }\n                if(b == '\\u0000'){\n                    b = s.charAt(i);\n                    d = goal.charAt(i);\n                    continue;\n                }\n                return false;\n            }\n\n            if(a == d && c == b && a != '\\u0000')\n                return true;\n\n            return false;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    //In case string is duplicated, check if string has any duplicate letters\n    bool dupeCase(string s){\n        unordered_set<char> letters;\n        for(auto it : s){\n            if(letters.count(it)){  //Found dupe letter (they can be swapped)\n                return true;\n            } else {\n                letters.insert(it);\n            }\n        }\n        return false;   //all letters unique\n    }\n    \n    bool buddyStrings(string s, string goal) {\n        //check len\n        if(goal.length() != s.length()) return false;\n        //If strings are the same, use diff. method\n        if(s == goal) return dupeCase(s);\n        //Track index of differences \n        vector<int> diff;\n        for(int i = 0; i < s.length(); i++){\n            if(s[i] != goal[i]){    //If diff found\n                if(diff.size() > 2){    //If this is third diff, return false\n                    return false;\n                } else {            //If not store in diff array\n                    diff.push_back(i);\n                }\n            }\n        }\n        //If only one diff found, return false\n        if(diff.size() == 1) return false;\n        //else return if swap works\n        return (s[diff[0]] == goal[diff[1]] && s[diff[1]] == goal[diff[0]]);\n    }\n};"
    },
    {
        "title": "Minimum Time Difference",
        "algo_input": "Given a list of 24-hour clock time points in \"HH:MM\" format, return the minimum minutes difference between any two time-points in the list.\n&nbsp;\nExample 1:\nInput: timePoints = [\"23:59\",\"00:00\"]\nOutput: 1\nExample 2:\nInput: timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput: 0\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= timePoints.length &lt;= 2 * 104\n\ttimePoints[i] is in the format \"HH:MM\".\n\n",
        "solution_py": "class Solution:\n\tdef findMinDifference(self, timePoints: List[str]) -> int:\n\t\ttimePoints.sort()\n\n\t\tdef getTimeDiff(timeString1, timeString2):\n\t\t\ttime1 = int(timeString1[:2]) * 60 + int(timeString1[3:])\n\t\t\ttime2 = int(timeString2[:2]) * 60 + int(timeString2[3:])\n\n\t\t\tminDiff = abs(time1 - time2)\n\n\t\t\treturn min(minDiff, 1440 - minDiff)\n\n\t\tresult = getTimeDiff(timePoints[0], timePoints[-1]) # edge case, we need to check minDiff of first and last time after sorting\n\n\t\tfor i in range(len(timePoints)-1):\n\t\t\tcurMin = getTimeDiff(timePoints[i], timePoints[i+1])\n\n\t\t\tif curMin < result:\n\t\t\t\tresult = curMin\n\n\t\treturn result\n\t\t",
        "solution_js": "var findMinDifference = function(timePoints) {\n    const DAY_MINUTES = 24 * 60;\n    const set = new Set();\n\n    for (let index = 0; index < timePoints.length; index++) {\n        const time = timePoints[index];\n        const [hours, minutes] = time.split(':');\n        const totalMinutes = hours * 60 + +minutes;\n        if (set.has(totalMinutes)) return 0;\n        set.add(totalMinutes);\n    }\n\n    const timeMinutes = [...set].sort((a, b) => a - b);\n    return timeMinutes.reduce((min, time, index) => {\n        const next = timeMinutes[index + 1];\n        const diff = next ? next - time : DAY_MINUTES - time + timeMinutes[0];\n        return Math.min(min, diff);\n    }, Infinity);\n};",
        "solution_java": "class Solution {\n    public int findMinDifference(List<String> timePoints) {\n        int N = timePoints.size();\n        int[] minutes = new int[N];\n        for(int i = 0; i < N; i++){\n            int hr = Integer.parseInt(timePoints.get(i).substring(0, 2));\n            int min = Integer.parseInt(timePoints.get(i).substring(3, 5));\n            minutes[i] = hr * 60 + min;\n        }\n        Arrays.sort(minutes);\n        int res = Integer.MAX_VALUE;\n        for(int i = 0; i < N - 1; i++){\n            res = Math.min(res, minutes[i + 1] - minutes[i]);\n        }\n        int b = minutes[0];\n        int a = minutes[N - 1];\n        return Math.min(res, (b - a + 1440) % 1440);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findMinDifference(vector<string>& timePoints) {\n        unordered_set<string> st;\n        for(auto &i: timePoints)\n        {\n            if(st.count(i)) return 0;\n            st.insert(i);\n        }\n        int ans = INT_MAX;\n        int first = -1,prev = 0; // first variable will take the diffrence of the first time stamp given in the input and 00:00\n        int hour = 0, minute = 0;\n        while(hour<24)\n        {\n            minute=0;\n            while(minute < 60)\n            {\n                string hh = to_string(hour), mm = to_string(minute);\n                if(hh.size() == 1) hh = '0' + hh;\n                if(mm.size() == 1) mm = '0' + mm;\n                string p = hh + \":\"+ mm;\n                if(st.count(p))\n                {\n                    if(first == -1){first = prev;}\n                    else\n                    {\n                        ans = min(ans,prev);\n                    }\n                    prev = 0;\n                }\n                prev++;\n                minute++;\n            }\n            hour++;\n        }\n        ans = min(first+prev,ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Decode String",
        "algo_input": "Given an encoded string, return its decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.\n\nYou may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].\n\nThe test cases are generated so that the length of the output will never exceed 105.\n\n&nbsp;\nExample 1:\n\nInput: s = \"3[a]2[bc]\"\nOutput: \"aaabcbc\"\n\n\nExample 2:\n\nInput: s = \"3[a2[c]]\"\nOutput: \"accaccacc\"\n\n\nExample 3:\n\nInput: s = \"2[abc]3[cd]ef\"\nOutput: \"abcabccdcdcdef\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 30\n\ts consists of lowercase English letters, digits, and square brackets '[]'.\n\ts is guaranteed to be a valid input.\n\tAll the integers in s are in the range [1, 300].\n\n",
        "solution_py": "class Solution:\n    def decodeString(self, s):\n        it, num, stack = 0, 0, [\"\"]\n        while it < len(s):\n            if s[it].isdigit():\n                num = num * 10 + int(s[it])\n            elif s[it] == \"[\":\n                stack.append(num)\n                num = 0\n                stack.append(\"\")\n            elif s[it] == \"]\":\n                str1 = stack.pop()\n                rep = stack.pop()\n                str2 = stack.pop()\n                stack.append(str2 + str1 * rep)\n            else:\n                stack[-1] += s[it]              \n            it += 1           \n        return \"\".join(stack)",
        "solution_js": "var decodeString = function(s) {\n    const stack = [];\n\n    for (let char of s) {\n         if (char === \"]\") {\n            let curr = stack.pop();\n            let str = '';\n            while (curr !== '[') {\n                str = curr+ str;\n                curr = stack.pop();\n            }\n            let num = \"\";\n            curr = stack.pop();\n            while (!isNaN(curr)) {\n                num = curr + num;\n                curr = stack.pop();\n            }\n            stack.push(curr);\n            for (let i=0; i<Number(num);i++) {\n                stack.push(str);\n            }\n        }\n        else stack.push(char);\n    }\n\n    return stack.join('');\n};",
        "solution_java": "class Solution {\n    public String decodeString(String s) {\n\n        int bb = s.indexOf('['); // location of beginning bracket\n        int nbb = s.indexOf('[', bb + 1); // location of next beginning bracket\n        int eb = s.indexOf(']'); // location of ending bracket\n\n        int n = 0; // number of times to repeat\n        int nl = 1; // number of digits for n\n        char nd; // next digit\n\n        String insert = \"\"; // repeated string\n        String end = \"\"; // remainder of string after repeated portion\n\n        while (bb != -1) { // while the string contains a beginning bracket\n\n            while (nbb < eb && nbb > bb) { // while the next beginning bracket is before the ending bracket\n                bb = nbb; // update location of beginning bracket\n                nbb = s.indexOf('[', bb + 1); // update location of next beginning bracket\n            }\n\n            nl = 1; // reset length of n\n            while (bb - nl >= 0) { // while there are characters in front of the beginning bracket\n                nd = s.charAt(bb - nl); // next digit\n                if (nd <= '9' && nd >= '0') { // if next digit is an integer\n                    n += (int)(nd - '0') * Math.pow(10, nl - 1); // update value of n\n                    nl++; // increment length of n\n                }\n                else break; // not an integer\n            }\n\n            insert = s.substring(bb + 1, eb); // set repeated string\n            end = s.substring(eb + 1); // set remainder of string\n            s = s.substring(0, bb - nl + 1); // remove everything after the digits\n\n            while (n > 0) {\n                s += insert; // add repeated string n times\n                n--;\n            }\n            s += end; // add remainder of string\n\n            bb = s.indexOf('['); // new location of beginning bracket\n            nbb = s.indexOf('[', bb + 1); // new location of next beginning bracket\n            eb = s.indexOf(']'); // new location of ending bracket\n        }\n        return s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    string decodeString(string s) {\n        stack<char> st;\n        for(int i = 0; i < s.size(); i++){\n            if(s[i] != ']') {\n                st.push(s[i]);\n            }\n            else{\n                string curr_str = \"\";\n                \n                while(st.top() != '['){\n                    curr_str = st.top() + curr_str ;\n                    st.pop();\n                }\n                \n                st.pop();   // for '['\n                string number = \"\";\n                \n                // for calculating number\n                \n                while(!st.empty() && isdigit(st.top())){\n                    number = st.top() + number;\n                    st.pop();\n                }\n                int k_time = stoi(number);    // convert string to number\n                \n                while(k_time--){\n                    for(int p = 0; p < curr_str.size() ; p++)\n                        st.push(curr_str[p]);\n                }\n            }\n        }\n        \n        s = \"\";\n        while(!st.empty()){\n            s = st.top() + s;\n            st.pop();\n        }\n        return s;\n        \n    }\n};"
    },
    {
        "title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix",
        "algo_input": "Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.\n\nReturn the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.\n\nA binary matrix is a matrix with all cells equal to 0 or 1 only.\n\nA zero matrix is a matrix with all cells equal to 0.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[0,0],[0,1]]\nOutput: 3\nExplanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n\n\nExample 2:\n\nInput: mat = [[0]]\nOutput: 0\nExplanation: Given matrix is a zero matrix. We do not need to change it.\n\n\nExample 3:\n\nInput: mat = [[1,0,0],[1,0,0]]\nOutput: -1\nExplanation: Given matrix cannot be a zero matrix.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 3\n\tmat[i][j] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    flips = [11, 23, 38, 89, 186, 308, 200, 464, 416]\n    \n    def minFlips(self, mat: List[List[int]]) -> int:\n        mask = self.make_mask(mat)\n        check = self.make_mask([[1 for c in r] for r in mat])\n        min_steps = -1\n        last = 0\n        for x in range(2**9):\n            x = x & check\n            flips = last ^ x\n            last = x\n            if not flips:\n                continue\n            for i in range(len(mat)):\n                for j in range(len(mat[0])):\n                    index = (i * 3 + j)\n                    if 1 << index & flips:\n                        mask ^= self.flips[index]\n            if check & ~mask == check:\n                steps = self.count_bits(x & check)\n                if min_steps < 0 or steps < min_steps:\n                    min_steps = steps\n        return min_steps\n    \n    def make_mask(self, mat):\n        d = 0\n        for i in range(3):\n            for j in range(3):\n                if i < len(mat) and j < len(mat[0]):\n                    d |= mat[i][j] << (i * 3 + j)\n        return d\n\n    def count_bits(self, x):\n        count = 0\n        i = 1\n        while i <= x:\n            count += int(bool(x & i))\n            i <<= 1\n        return count",
        "solution_js": "// Helper counts how many ones are in the matrix to start with. O(mn)\nvar countOnes = function(mat) {\n    let count = 0;\n    for (let r = 0; r < mat.length; r++) {\n        count += mat[r].reduce((a, b) => a + b);\n    }\n    return count;\n}\n\n// Helper flips a cell and its neighbors. Returns updated number of ones left in matrix. O(1)\nvar flip = function(mat, r, c, numOnes) {\n    const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0], [0, 0]];\n    dirs.forEach(el => {\n        let newR = r + el[0], newC = c + el[1];\n        if (newR >= 0 && newR < mat.length && newC >= 0 && newC < mat[0].length) {\n            if (mat[newR][newC] === 0) {\n                mat[newR][newC] = 1;\n                numOnes++;\n            } else {\n                mat[newR][newC] = 0;\n                numOnes--;\n            }\n        }\n    })\n    return numOnes;\n}\n\n// Main function tries every possible combination of cells being flipped using backtracking. O (2^(mn))\nvar minFlips = function(mat) {\n    const rows = mat.length, cols = mat[0].length;\n    let minFlips = Infinity, numOnes = countOnes(mat);\n    \n    var backtrackFlip = function(cell, flips) {\n        if (numOnes === 0) minFlips = Math.min(minFlips, flips);\n        for (let newCell = cell; newCell < rows * cols; newCell++) {\n\t\t\t// Function uses a cell number instead of row / col to keep track of column flips\n\t\t\t// For example, a 2 x 2 grid has cells \"0\", \"1\", \"2\", \"3\" and the line below calculates row / col based on that number\n            const r = Math.floor(newCell / cols), c = newCell % cols;\n            numOnes = flip(mat, r, c, numOnes);\n            backtrackFlip(newCell + 1, flips + 1);\n            numOnes = flip(mat, r, c, numOnes);\n        }\n    }\n    \n    backtrackFlip(0, 0);\n    return minFlips === Infinity ? -1 : minFlips;\n    \n};",
        "solution_java": "class Solution {\n    public int minFlips(int[][] mat) {\n        int m = mat.length, n = mat[0].length;\n        Set<Integer> visited = new HashSet<>();\n        Queue<Integer> queue = new LinkedList<>();\n        int steps = 0;\n        \n        int initialState = toBinary(mat);\n        queue.add(initialState);\n        visited.add(initialState);\n        \n        while (!queue.isEmpty()) {\n            int size = queue.size();\n            \n            for (int i = 0; i < size; i++) {\n                int state = queue.poll();\n                if (state == 0) return steps;\n                int mask = 1;\n\n                for (int y = 0; y < m; y++) {\n                    for (int x = 0; x < n; x++) {\n                        int nextState = flip(state, x, y, n, m);\n                        if (!visited.contains(nextState)) {\n                            visited.add(nextState);\n                            queue.add(nextState);\n                        }\n                        mask = mask << 1;\n                    }\n                }\n            }\n            steps++;\n        }\n        return -1;\n    }\n    \n    private int toBinary(int[][] M) {\n        int bin = 0;\n        for (int y = 0; y < M.length; y++) {\n            for (int x = 0; x < M[0].length; x++) {\n                bin = (bin << 1) + M[y][x];\n            }\n        }\n        return bin;\n    }\n    \n    private int flip(int state, int x, int y, int n, int m) {\n        int flip = 1 << ((y*n) + x);\n        flip += (x > 0) ? 1 << ((y*n) + (x-1)) : 0;\n        flip += (x < n-1) ? 1 << ((y*n) + (x+1)) : 0;\n        flip += (y > 0) ? 1 << (((y-1)*n) + x) : 0;\n        flip += (y < m-1) ? 1 << (((y+1)*n) + x) : 0;\n        return state ^ flip;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool check(string str) {\n        for(auto &i: str)\n            if(i=='1')\n                return false;\n        return true;\n    }\n    int minFlips(vector<vector<int>>& mat) {\n        int m = mat.size();\n        int n = mat[0].size();\n        string str = \"\";\n        for(auto &i: mat) {\n            for(auto &j: i)\n                str+=(j+'0');\n        }\n        \n        unordered_set<string> st;\n        queue<pair<string,int>> q;\n        q.push({str,0});\n        int steps = 0;\n        \n        while(q.size()) {\n            string top = q.front().first;\n            int step = q.front().second;\n            if(check(top)) {\n                    return step;\n            }\n            \n            q.pop();\n            steps++;\n            for(int i=0; i<top.size(); ++i) {\n                string temp = top;\n                int x = i/n;\n                int y = i%n;\n                \n                \n                temp[i] = !(temp[i] - '0') + '0';\n                if(x+1<m)\n                    temp[y + (x+1)*n] = !(temp[y + (x+1)*n] - '0') + '0';\n                if(x-1>=0)\n                    temp[y + (x-1)*n] = !(temp[y + (x-1)*n] - '0') + '0';\n                if(y+1<n)\n                    temp[(y+1) + (x)*n] = !(temp[(y+1) + (x)*n] - '0') + '0';\n                if(y-1>=0)\n                    temp[(y-1) + (x)*n] = !(temp[(y-1) + (x)*n] - '0') + '0';\n                \n                // cout<<i<<\" : \"<<temp<<\" \"<<step+1<<endl;\n                if(st.count(temp)==0) {\n                    q.push({temp,step+1});\n                    st.insert(temp);\n                }\n                \n                \n                if(check(temp)) {\n                    return step+1;\n                }\n                \n            }\n            \n        }\n        return -1;\n        \n    }\n};"
    },
    {
        "title": "Get Biggest Three Rhombus Sums in a Grid",
        "algo_input": "You are given an m x n integer matrix grid​​​.\n\nA rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:\n\nNote that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.\n\nReturn the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput: [228,216,211]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211\n\n\nExample 2:\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [20,9,8]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)\n\n\nExample 3:\n\nInput: grid = [[7,7,7]]\nOutput: [7]\nExplanation: All three possible rhombus sums are the same, so return [7].\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 50\n\t1 &lt;= grid[i][j] &lt;= 105\n\n",
        "solution_py": "class Solution:\ndef getBiggestThree(self, grid: List[List[int]]) -> List[int]:\n    \n    def calc(l,r,u,d):\n        sc=0\n        c1=c2=(l+r)//2\n        expand=True\n        for row in range(u,d+1):\n            if c1==c2:\n                sc+=grid[row][c1]\n            else:\n                sc+=grid[row][c1]+grid[row][c2]\n            \n            if c1==l:\n                expand=False\n            \n            if expand:\n                c1-=1\n                c2+=1\n            else:\n                c1+=1\n                c2-=1\n        return sc\n        \n    \n    m=len(grid)\n    n=len(grid[0])\n    heap=[]\n    for i in range(m):\n        for j in range(n):\n            l=r=j\n            d=i\n            while l>=0 and r<=n-1 and d<=m-1:\n                sc=calc(l,r,i,d)\n                l-=1\n                r+=1\n                d+=2\n                if len(heap)<3:\n                    if sc not in heap:\n                        heapq.heappush(heap,sc)\n                else:\n                    if sc not in heap and sc>heap[0]:\n                        heapq.heappop(heap)\n                        heapq.heappush(heap,sc)\n    \n    heap.sort(reverse=True)\n    return heap",
        "solution_js": "var getBiggestThree = function(grid) {\n    const m = grid.length;\n    const n = grid[0].length;\n\n    const set = new Set();\n\n    for (let i = 0; i < m; ++i) {\n        for (let j = 0; j < n; ++j) {\n            let sum = grid[i][j];\n\n            set.add(sum)\n\n            let len = 1;\n            let row = i;\n            let col = j;\n\n            while (withinBound(row + 1, col - 1)) {\n                ++len;\n                ++row;\n                --col;\n\n                traverse(i, j, row, col, sum, len, 0, \"botRight\");\n                sum += grid[row][col];\n            }\n        }\n    }\n\n    let max1;\n    let max2;\n    let max3;\n\n    for (const num of set) {\n        if (max1 == null || num > max1) {\n            max3 = max2;\n            max2 = max1;\n            max1 = num;\n        }\n        else if (max2 == null || num > max2) {\n            max3 = max2;\n            max2 = num;\n        }\n        else if (max3 == null || num > max3) {\n            max3 = num;\n        }\n    }\n\n    const res = [];\n\n    if (max1) res[0] = max1;\n    if (max2) res[1] = max2;\n    if (max3) res[2] = max3;\n\n    return res;\n\n    function traverse(destRow, destCol, currRow, currCol, totSum, lenSize, currLen, currDir) {\n        if (currRow === destRow && currCol === destCol) {\n            set.add(totSum);\n            return;\n        }\n\n        totSum += grid[currRow][currCol];\n        ++currLen;\n\n        if (currDir === \"botRight\") {\n            if (currLen < lenSize) {\n                if (!withinBound(currRow + 1, currCol + 1)) return;\n\n                traverse(destRow, destCol, currRow + 1, currCol + 1, totSum, lenSize, currLen, currDir);\n            }\n            else if (currLen === lenSize) {\n                if (!withinBound(currRow - 1, currCol + 1)) return;\n\n                traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, 1, \"topRight\");\n            }\n        }\n        else if (currDir === \"topRight\") {\n            if (currLen < lenSize) {\n                if (!withinBound(currRow - 1, currCol + 1)) return;\n\n                traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, currLen, \"topRight\");\n            }\n            else if (currLen === lenSize) {\n                if (!withinBound(currRow - 1, currCol - 1)) return;\n\n                traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, 1, \"topLeft\");\n            }\n        }\n        else if (currDir === \"topLeft\") {\n            if (!withinBound(currRow - 1, currCol - 1)) return;\n\n            traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, currLen, \"topLeft\");\n        }\n    }\n\n    function withinBound(row, col) {\n        return row >= 0 && col >= 0 && row < m && col < n;\n    }\n};",
        "solution_java": "class Solution {\n    public int[] getBiggestThree(int[][] grid) {\n        int end = Math.min(grid.length, grid[0].length);\n        int maxThree[] = {0,0,0};\n        for(int length=0; length<end; length++){\n            searchBigThree(grid, maxThree, length);\n        }\n\n        Arrays.sort(maxThree);\n\n        // If there are less than three distinct values, return all of them.\n        if(maxThree[0] == 0){\n            if(maxThree[1] == 0){\n                return new int[]{maxThree[2]};\n            }\n            return new int[]{maxThree[2],maxThree[1]};\n        }\n\n        // reverse array\n        maxThree[0] = maxThree[0]^maxThree[2];\n        maxThree[2] = maxThree[0]^maxThree[2];\n        maxThree[0] = maxThree[0]^maxThree[2];\n\n        return maxThree;\n    }\n\n    void searchBigThree(int[][] grid, int[] maxThree, int length){\n        int end = grid.length-(length==0?0: 2*length);\n        int end1 = grid[0].length-(length);\n        for(int start = 0; start<end; start++){\n            for(int start1 = length; start1<end1; start1++){\n                if(start+start1 >= length){\n                    addToMaxThree(maxThree, getSum(grid, start, start1, length));\n                }\n            }\n        }\n    }\n\n    /*\n    get sum of edges of rhombus abcd\n            a\n           / \\\n          d b\n           \\ /\n            c\n\n    */\n    int getSum(int[][] grid, int i, int j, int length){\n        if(length == 0){\n            return grid[i][j];\n        }\n\n        int sum = 0;\n        // edge ab\n        for(int it=0; it<=length; it++){\n            sum = sum + grid[i+it][j+it];\n        }\n\n        // edge ad\n        for(int it=1; it<=length; it++){\n            sum = sum + grid[i+it][j-it];\n        }\n\n        // edge dc\n        for(int it=1; it<=length; it++){\n            sum = sum + grid[i+length+it][j-length+it];\n        }\n\n        // edge bc\n        for(int it=1; it<length; it++){\n            sum = sum + grid[i+length+it][j+length-it];\n        }\n\n        return sum;\n    }\n\n    void addToMaxThree(int[] maxThree, int num){\n        // Do not add duplicate entry\n        if(maxThree[0] == num || maxThree[1] == num || maxThree[2] == num ){\n            return;\n        }\n\n        Arrays.sort(maxThree);\n\n        if(maxThree[0] < num){\n            maxThree[0] = num;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> getBiggestThree(vector<vector<int>>& grid) {\n\n        int n = grid.size(), m = grid[0].size();\n        set<int> s;\n\n        // 1x1, 3x3, 5x5\n        for (int len = 1; len <= min(m, n); len += 2) {\n            for (int i = 0; i + len <= n; i ++) {\n                for (int j = 0; j + len <= m; j ++) {\n                    int d = len / 2;\n                    if (d == 0) { s.insert(grid[i][j]); }\n                    else {\n                        int x = i, y = j + d;\n                        long long sum = 0;\n                        for (int k = 0; k < d; k ++) sum += grid[x++][y++];\n                        for (int k = 0; k < d; k ++) sum += grid[x++][y--];\n                        for (int k = 0; k < d; k ++) sum += grid[x--][y--];\n                        for (int k = 0; k < d; k ++) sum += grid[x--][y++];\n                        s.insert(sum);\n                    }\n                }\n            }\n        }\n\n        if (s.size() < 3)\n            return vector<int>(s.rbegin(), s.rend());\n\n        return vector<int>(s.rbegin(), next(s.rbegin(), 3));\n    }\n};"
    },
    {
        "title": "Minimum Absolute Sum Difference",
        "algo_input": "You are given two positive integer arrays nums1 and nums2, both of length n.\n\nThe absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 &lt;= i &lt; n (0-indexed).\n\nYou can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.\n\nReturn the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.\n\n|x| is defined as:\n\n\n\tx if x &gt;= 0, or\n\t-x if x &lt; 0.\n\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,7,5], nums2 = [2,3,5]\nOutput: 3\nExplanation: There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] =&gt; [1,1,5], or\n- Replace the second element with the third: [1,7,5] =&gt; [1,5,5].\nBoth will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\n\n\nExample 2:\n\nInput: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput: 0\nExplanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.\n\n\nExample 3:\n\nInput: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput: 20\nExplanation: Replace the first element with the second: [1,10,4,4,2,7] =&gt; [10,10,4,4,2,7].\nThis yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums1.length\n\tn == nums2.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= nums1[i], nums2[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n        n = len(nums1)\n        diff = []\n        sum = 0\n        for i in range(n):\n            temp = abs(nums1[i]-nums2[i])\n            diff.append(temp)\n            sum += temp\n        nums1.sort()\n        best_diff = []\n        for i in range(n):\n            idx = bisect.bisect_left(nums1, nums2[i])\n            if idx != 0 and idx != n:\n                best_diff.append(\n                    min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n            elif idx == 0:\n                best_diff.append(abs(nums2[i]-nums1[idx]))\n            else:\n                best_diff.append(abs(nums2[i]-nums1[idx-1]))\n        saved = 0\n        for i in range(n):\n            saved = max(saved, diff[i]-best_diff[i])\n        return (sum-saved) % ((10**9)+(7))",
        "solution_js": "var minAbsoluteSumDiff = function(nums1, nums2) {\n    const MOD = 1e9 + 7;\n    const n = nums1.length;\n\n    const origDiffs = [];\n    let diffSum = 0;\n\n    for (let i = 0; i < n; i++) {\n        const num1 = nums1[i];\n        const num2 = nums2[i];\n\n        const currDiff = Math.abs(num1 - num2);\n\n        origDiffs[i] = currDiff;\n        diffSum += currDiff;\n    }\n\n    nums1.sort((a, b) => a - b);\n\n    let minDiffSum = diffSum;\n\n    for (let i = 0; i < n; i++) {\n        const origDiff = origDiffs[i];\n\n        const num2 = nums2[i];\n\n        let left = 0;\n        let right = n - 1;\n\n        let bestDiff = origDiff;\n\n        while (left <= right) {\n            const mid = (left + right) >> 1;\n            const num1 = nums1[mid];\n\n            const candDiff = num1 - num2;\n\n            if (Math.abs(candDiff) < bestDiff) {\n                bestDiff = Math.abs(candDiff);\n                if (bestDiff === 0) break;\n            }\n\n            if (candDiff < 0) left = mid + 1;\n            else right = mid - 1;\n        }\n\n        const replacedDiffSum = (diffSum - origDiff) + bestDiff;\n\n        minDiffSum = Math.min(minDiffSum, replacedDiffSum);\n    }\n\n    return minDiffSum % MOD;\n};",
        "solution_java": "class Solution {\n    public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {\n        int mod = (int)1e9+7;\n\n        // Sorted copy of nums1 to use for binary search\n        int[] snums1 = nums1.clone();\n        Arrays.sort(snums1);\n        \n        int maxDiff = 0;    // maximum difference between original and new absolute diff\n        int pos = 0;        // where the maximum difference occurs\n        int newn1 = 0;      // nums1 value to copy to nums1[pos]\n\n        // For each array position i from 0 to n-1, find up to two elements\n        // in nums1 that are closest to nums2[i] (one on each side of nums2[i]).\n        // Calculate a new absolute difference for each of these elements.\n        for (int i=0; i<nums2.length; i++) {\n            int n2 = nums2[i];\n            int origDiff = Math.abs(nums1[i] - n2);\n            \n            // Find the largest element in nums1 that is less than or equal to\n            // the current element in nums2, if such an element exists.\n            int floor = arrayFloor(snums1, n2);\n            if (floor > Integer.MIN_VALUE) {\n                // If a valid element exists, calculate a new absolute difference\n                // at the current position, and calculate how much smaller this is\n                // than the current absolute difference. If the result is better\n                // than what we have seen so far, update the maximum difference and\n                // save the data for the current position.\n                int newDiff = Math.abs(floor - n2);\n                int diff = origDiff - newDiff;\n                if (diff > maxDiff) {\n                    pos = i;\n                    newn1 = floor;\n                    maxDiff = diff;\n                }\n            }\n            \n            // Find the smallest element in nums1 that is greater than or equal to\n            // the current element in nums2, if such an element exists.\n            int ceiling = arrayCeiling(snums1, n2);\n            if (ceiling < Integer.MAX_VALUE) {\n                // Same as above\n                int newDiff = Math.abs(ceiling - n2);\n                int diff = origDiff - newDiff;\n                if (diff > maxDiff) {\n                    pos = i;\n                    newn1 = ceiling;\n                    maxDiff = diff;\n                }\n            }\n        }\n\n        // If we found a replacement value, overwrite the original value.\n        if (newn1 > 0) {\n            nums1[pos] = newn1;\n        }\n        \n        // Calculate the absolute sum difference with the replaced value.\n        int sum = 0;\n        for (int i=0; i<nums1.length; i++) {\n            sum = (sum + Math.abs(nums1[i] - nums2[i])) % mod;\n        }\n        \n        return sum;\n    }\n\n\n    //\n    // Array versions of TreeSet.floor and TreeSet.ceiling\n    //\n    \n    // Greatest element less than or equal to val\n    private int arrayFloor(int[] arr, int val) {\n        int lo = 0;\n        int hi = arr.length-1;\n        int max = Integer.MIN_VALUE;\n        \n        while (lo <= hi) {\n            int mid = lo+(hi-lo)/2;\n            if (arr[mid] <= val) {\n                max = arr[mid];\n                lo = mid+1;\n            } else {\n                hi = mid-1;\n            }\n        }\n        \n        return max;\n    }\n    \n    // Smallest element greater than or equal to val\n    private int arrayCeiling(int[] arr, int val) {\n        int lo = 0;\n        int hi = arr.length-1;\n        int min = Integer.MAX_VALUE;\n        \n        while (lo <= hi) {\n            int mid = lo+(hi-lo)/2;\n            if (arr[mid] >= val) {\n                min = arr[mid];\n                hi = mid-1;\n            } else {\n                lo = mid+1;\n            }\n        }\n        \n        return min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {\n      long sum=0, minSum;\n      vector<int> nums=nums1;\n      int n=nums.size();\n\t  // Calculate the current sum of differences.\n      for(int i=0;i<n;i++) sum+=abs(nums1[i]-nums2[i]);\n      \n      sort(nums.begin(), nums.end());\n      minSum=sum;\n      \n      for(int i=0;i<n;i++) {\n        int dist=abs(nums1[i]-nums2[i]);\n        int l=0, h=n-1;\n        \n\t\t// Find the number closest to nums2[i]. \n\t\t// The closer the element, the smaller the difference.\n        while(l<h) {\n          int m=l+(h-l)/2;\n          if(nums[m]>nums2[i]) {\n            h=m;\n          } else {\n            l=m+1;\n          }\n          dist=min(dist, abs(nums2[i]-nums[m]));\n        }\n        dist=min(dist, abs(nums2[i]-nums[l]));\n        minSum = min(minSum, sum - abs(nums1[i]-nums2[i]) + dist);\n      }\n      \n      return minSum % 1000000007;\n    }\n};"
    },
    {
        "title": "Permutation Sequence",
        "algo_input": "The set [1, 2, 3, ...,&nbsp;n] contains a total of n! unique permutations.\n\nBy listing and labeling all of the permutations in order, we get the following sequence for n = 3:\n\n\n\t\"123\"\n\t\"132\"\n\t\"213\"\n\t\"231\"\n\t\"312\"\n\t\"321\"\n\n\nGiven n and k, return the kth permutation sequence.\n\n&nbsp;\nExample 1:\nInput: n = 3, k = 3\nOutput: \"213\"\nExample 2:\nInput: n = 4, k = 9\nOutput: \"2314\"\nExample 3:\nInput: n = 3, k = 1\nOutput: \"123\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 9\n\t1 &lt;= k &lt;= n!\n\n",
        "solution_py": "  class Solution:\n    def nextPermutation(self, nums: List[int]):\n        n = len(nums)\n        high = n-1\n        low = -1\n        for i in range(n-1, 0, -1):\n            if nums[i] > nums[i-1]:\n                low = i-1\n                break\n        if low == -1:\n            nums[low+1:] = reversed(nums[low+1:])\n            return\n        for i in range(n-1, low, -1):\n            if nums[low] < nums[i]:\n                nums[low], nums[i] = nums[i], nums[low]\n                break\n        nums[low+1:] = reversed(nums[low+1:])\n        return nums\n\n    def getPermutation(self, n: int, k: int) -> str:\n        s = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n        s = s[:n]\n        if k==1:\n            return ''.join(s)\n        dic = {1:1,2:2,3:6,4:24,5:120,6:720,7:5040,8:40320,9:362880}        \n        if k==dic[n]:\n            return ''.join(s)[::-1]\n        x = 0\n        while k>dic[n-1]:\n            k -= dic[n-1]\n            x += 1\n        y=[]\n        y.append(s[x])\n        for i in range(n):\n            if i==x:\n                continue\n            y.append(s[i])\n        while k!=1:\n            self.nextPermutation(y)\n            k-= 1\n        y = ''.join(y)\n        return y",
        "solution_js": "const dfs = (path, visited, result, numbers, limit) => {\n    // return if we already reached the permutation needed\n    if(result.length === limit) {\n        return;\n    }\n    \n    // commit the result\n    if(path.length === numbers.length) {\n        result.push(path.join(''))\n        return;\n    }\n    \n    // easier to reason and less prone to miss the -1 offset of normal for loop\n    for(const [index, number] of numbers.entries()) {\n        if(visited[index]) continue;\n        \n        path.push(number);\n        visited[index] = true;\n        dfs(path, visited, result, numbers);\n        path.pop();\n        visited[index] = false;\n    }\n}\n\nvar getPermutation = function(n, k) {\n    const numbers = Array.from({length: n}, (_, i) => i + 1);\n    let visitedNumbers = Array.from(numbers, () => false);\n    let result = [];\n    dfs([], visitedNumbers, result, numbers, k);\n    return result[k - 1];\n};",
        "solution_java": "class Solution {\n    public String getPermutation(int n, int k) {\n        int fact = 1;\n        List<Integer> nums = new ArrayList<>();\n        for(int i = 1; i<n; i++){\n            fact = fact * i;\n            nums.add(i);\n        }\n        nums.add(n); // Add last permutation number.\n        String res = \"\";\n        k = k - 1; // We use 0 indexing.\n        while(true){\n            res = res + nums.get(k / fact); \n            nums.remove(k / fact); \n            if(nums.size() == 0) break;\n            \n            k = k % fact;\n            fact = fact / nums.size();\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string getPermutation(int n, int k) {\n        int fact=1;\n        vector<int> numbers;\n        for(int i=1;i<n;i++){\n            fact=fact*i;\n            numbers.push_back(i);\n        }\n        numbers.push_back(n);\n        string ans=\"\";\n        k=k-1;\n        while(true){\n            ans=ans+to_string(numbers[k/fact]);\n            numbers.erase(numbers.begin()+(k/fact));\n            if(numbers.size()==0) break;\n            k=k%fact;\n            fact=fact/numbers.size();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Convert Sorted List to Binary Search Tree",
        "algo_input": "Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n\nFor this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.\n\n&nbsp;\nExample 1:\n\nInput: head = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.\n\n\nExample 2:\n\nInput: head = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in head is in the range [0, 2 * 104].\n\t-105 &lt;= Node.val &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:\n        arr = []\n        while head:\n            arr.append(head.val)\n            head = head.next\n        def dfs(left, right):\n            if left > right: return\n            m = (left + right)//2\n            return TreeNode(arr[m], dfs(left, m-1), dfs(m+1, right))\n        return dfs(0, len(arr)-1)",
        "solution_js": "var sortedListToBST = function(head) {\n    if(!head) return null;\n    if(!head.next) return new TreeNode(head.val);\n    \n    let fast = head, slow = head, prev = head;\n    while(fast && fast.next) {\n        prev = slow;\n        slow = slow.next;\n        fast = fast.next.next;\n    }\n    \n    const root = new TreeNode(slow.val);\n    prev.next = null;\n    \n    const newHead = slow.next;\n    slow.next = null;\n    \n    root.left = sortedListToBST(head);\n    root.right = sortedListToBST(newHead);\n    \n    return root;\n};",
        "solution_java": "class Solution {\n    \n        public TreeNode sortedListToBST(ListNode head) {\n            \n            ListNode tmp = head;\n            ArrayList<Integer> treelist = new ArrayList<>();\n            \n            while(tmp != null) {\n                treelist.add(tmp.val);\n                tmp = tmp.next;\n            }\n            \n            return createTree(treelist, 0, treelist.size()-1);\n        }\n    \n        public TreeNode createTree(ArrayList<Integer> treelist, int start, int end) {\n            \n            if(start > end)\n                return null;\n            \n            int mid = start + (end-start)/2;\n            \n            TreeNode node = new TreeNode(treelist.get(mid));//getNode(treelist.get(mid));\n            \n            node.left = createTree(treelist, start, mid-1);\n            node.right = createTree(treelist, mid+1, end);\n            return node;\n        }\n}",
        "solution_c": "class Solution {\npublic:\n    typedef vector<int>::iterator vecIt;\n    TreeNode* buildTree(vector<int>& listToVec, vecIt start, vecIt end)\n    {\n        if (start >= end)\n            return NULL;\n        vecIt midIt = start + (end - start) / 2;\n        TreeNode* newNode = new TreeNode(*midIt);\n        newNode->left = buildTree(listToVec, start, midIt);\n        newNode->right = buildTree(listToVec, midIt + 1, end);\n        return (newNode);\n    }\n    TreeNode* sortedListToBST(ListNode* head) {\n        vector<int> listToVec;\n        while (head)\n        {\n            listToVec.push_back(head->val);\n            head = head->next;\n        }\n        return (buildTree(listToVec, listToVec.begin(), listToVec.end()));\n    }\n};"
    },
    {
        "title": "Minimum Size Subarray Sum",
        "algo_input": "Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.\n\n&nbsp;\nExample 1:\n\nInput: target = 7, nums = [2,3,1,2,4,3]\nOutput: 2\nExplanation: The subarray [4,3] has the minimal length under the problem constraint.\n\n\nExample 2:\n\nInput: target = 4, nums = [1,4,4]\nOutput: 1\n\n\nExample 3:\n\nInput: target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target &lt;= 109\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 104\n\n\n&nbsp;\nFollow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).",
        "solution_py": "class Solution:\n    def minSubArrayLen(self, target, nums):\n\t\t# Init left pointer and answer\n        l, ans = 0, len(nums) + 1\n\t\t# Init sum of subarray\n        s = 0 \n\t\t# Iterate through all numbers as right subarray \n        for r in range(len(nums)):\n\t\t\t# Add right number to sum\n            s += nums[r]\n\t\t\t# Check for subarray greater than or equal to target\n            while s >= target:\n\t\t\t\t# Calculate new min\n                ans = min(ans, r - l + 1)\n\t\t\t\t# Remove current left nubmer from sum\n                s -= nums[l]\n\t\t\t\t# Move left index up one\n                l += 1\n\t\t# No solution\n        if ans == len(nums) + 1:\n            return 0\n\t\t# Solution\n        return ans ",
        "solution_js": "/**\n * @param {number} target\n * @param {number[]} nums\n * @return {number}\n */\nvar minSubArrayLen = function(target, nums) {\n    let indexStartPosition = 0;\n    let sum = 0;\n    let tempcounter = 0;\n    let counter = Infinity;\n\n    for(var indexI=0; indexI<nums.length; indexI++){\n           sum = sum + nums[indexI];\n        tempcounter++;\n\n        while(sum >= target) {\n           sum = sum - nums[indexStartPosition];\n           indexStartPosition = indexStartPosition + 1;\n           counter = Math.min(counter, tempcounter);\n           tempcounter--;\n        }\n\n    }\n\n    return counter === Infinity ? 0 : counter;\n};",
        "solution_java": "class Solution {\n    public int minSubArrayLen(int target, int[] nums) {\n        int left = 0;\n        int n = nums.length;\n        int sum = 0;\n        int minCount = Integer.MAX_VALUE;\n        for(int i = 0;i<n;i++){\n            sum += nums[i];\n            while(sum >= target){\n                minCount = Math.min(minCount, i-left+1);\n                sum -= nums[left++];\n            }   \n        }\n        return minCount == Integer.MAX_VALUE?0:minCount;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minSubArrayLen(int target, vector<int>& nums) {\n        int m=INT_MAX,s=0,l=0;\n        for(int i=0;i<nums.size();i++)\n        {\n            s+=nums[i];\n            if(s>=target)\n                m=min(m,i-l+1);\n            while(s>=target)\n            {\n                m=min(m,i-l+1);\n                s-=nums[l++];\n            }\n        }\n        if(m==INT_MAX)\n            m=0;\n        return m;\n    }\n};"
    },
    {
        "title": "Wiggle Subsequence",
        "algo_input": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.\n\n\n\tFor example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.\n\tIn contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.\n\n\nA subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.\n\nGiven an integer array nums, return the length of the longest wiggle subsequence of nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,7,4,9,2,5]\nOutput: 6\nExplanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n\n\nExample 2:\n\nInput: nums = [1,17,5,10,13,15,10,5,16,8]\nOutput: 7\nExplanation: There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,6,7,8,9]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 1000\n\n\n&nbsp;\nFollow up: Could you solve this in O(n) time?\n",
        "solution_py": "#####################################################################################################################\n# Problem:  Wiggle Subsequence\n# Solution : Dynamic Programming\n# Time Complexity : O(n) \n# Space Complexity : O(1)\n#####################################################################################################################\n\nclass Solution:\n    def wiggleMaxLength(self, nums: List[int]) -> int:\n        \n        positive, negative = 1, 1\n        \n        if len(nums) < 2:\n            return len(nums)\n        \n        for i in range(1, len(nums)):\n            if nums[i] > nums[i - 1]:\n                positive = negative + 1\n            elif nums[i] < nums[i - 1]:\n                negative = positive + 1\n                \n        return max(positive, negative)",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar wiggleMaxLength = function(nums) {\n    //two pass\n    //assume we start with positive or start with negative\n    //choose the longest of the two\n    return Math.max(helper(nums,true),helper(nums,false))\n};\n\nconst helper =  (nums, start) =>{\n    let l = 0\n    let r = 1\n    let res = nums.length\n    let sign = start\n    while(r < nums.length){\n        //if sign are what we expected, just flip the sign\n        if((sign && nums[r] > nums[l]) || (!sign && nums[r] < nums[l])){\n            sign = !sign\n        }\n        //if sign aren't what we expected then we \"remove\" one\n        //if we want positive then we remove the bigger number to give us a better chance of getting positive\n        //if we want negative we remove the smaller number go give us a chance of getting a negative\n        // want negative but nums[r] - nums[l] = positive   => remove nums[l] \n        // want positive but nums[r] - nums[l] = negative   => remove nums[l]\n        //it just so happens that the number we want to remove will always be nums[l], so we don't have to do anything special\n        else{\n            res--\n        }\n        l++\n        r++\n    }\n    return res\n}",
        "solution_java": "class Solution {\n    int n;\n    int dp[][][];\n    public int wiggleMaxLength(int[] nums) {\n        n = nums.length;\n        dp = new int[n][1005][2];\n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < 1005; j++){\n                Arrays.fill(dp[i][j] , -1);\n            }\n        }\n        int pos = f(0 , 0 , nums , -1);\n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < 1005; j++){\n                Arrays.fill(dp[i][j] , -1);\n            }\n        }\n        int neg = f(0 , 1 , nums , 1001);\n        return Math.max(pos , neg);\n    }\n    int f(int i , int posPre , int a[] , int prev){\n        if(i == n) return 0;\n        if(dp[i][prev + 1][posPre] != -1) return dp[i][prev + 1][posPre];\n        if(posPre == 0){\n            int not = f(i + 1 , 0 , a , prev);\n            int take = 0;\n            if(a[i] - prev > 0){\n                take = f(i + 1 , 1 , a , a[i]) + 1;\n            }\n            return dp[i][prev + 1][posPre] = Math.max(not , take);\n        }\n        else{\n            int not = f(i + 1 , 1 , a , prev);\n            int take = 0;\n            if(a[i] - prev < 0){\n                take = f(i + 1 , 0 , a , a[i]) + 1;\n            }\n            return dp[i][prev + 1][posPre] = Math.max(not , take);\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int wiggleMaxLength(vector<int>& nums) {\n        vector<vector<int>> dp(2, vector<int>(nums.size(),0));\n        int ans = 1, high, low;\n        dp[0][0] = dp[1][0] = 1;\n        for(int i=1; i<nums.size(); ++i){\n            high = low = 0;\n            for(int j=0; j<i; ++j){\n                if(nums[i]>nums[j]) low = max(low, dp[1][j]);\n                else if(nums[i]<nums[j]) high = max(high, dp[0][j]);\n            }\n            dp[0][i] = low + 1;\n            dp[1][i] = high + 1;\n            ans = max({ans, dp[0][i], dp[1][i]});\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Largest Perimeter Triangle",
        "algo_input": "Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,1,2]\nOutput: 5\n\n\nExample 2:\n\nInput: nums = [1,2,1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 104\n\t1 &lt;= nums[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def largestPerimeter(self, nums: List[int]) -> int:\n        nums=sorted(nums,reverse=True)\n        l=len(nums)\n        for i in range(l-2):\n            if nums[i]<nums[i+1]+nums[i+2]: #condition if triangle can be formed\n                return  nums[i]+nums[i+1]+nums[i+2]\n        return 0",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar largestPerimeter = function(nums) {\n    const sorted=nums.sort((a,b)=>a-b);\n    const result=[];\n    \n    for(let i=0;i<sorted.length;i++){\n        \n        if((sorted[i]+sorted[i+1]>sorted[i+2])&&(sorted[i+2]+sorted[i+1]>sorted[i])&&(sorted[i]+sorted[i+2]>sorted[i+1])){\n            \n           result.push(sorted[i]+sorted[i+1]+sorted[i+2]);\n        \n        }\n    }\n    if(result.length!==0){\n        \n    return Math.max(...result); \n        \n    }else{\n        \n    return 0;\n        \n    }\n};",
        "solution_java": "class Solution {\n    public int largestPerimeter(int[] nums) {\n        Arrays.sort(nums);\n\n        for(int i = nums.length - 3; i >= 0; i--) {\n            if(nums[i] + nums[i + 1] > nums[i + 2])\n                return nums[i] + nums[i + 1] + nums[i + 2];\n        }\n        return 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largestPerimeter(vector<int>& nums) {\n\t// sort the elements \n        sort(nums.begin(),nums.end());\n\t\t// iterate in everse order to get maximum perimeter\n        for (int i=nums.size()-2; i>=1 ; i--){\n\t\t//Triangle is formed if sum of two sides is greater than third side\n        if (nums[i]+nums[i-1] >nums[i+1])return (nums[i]+nums[i+1]+nums[i-1]); // return perimeter which is sum of three sides\n        }\n        return 0; // when no triangle possible it will come out of loop so return 0 here\n        \n    }\n};"
    },
    {
        "title": "Check if All A's Appears Before All B's",
        "algo_input": "Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aaabbb\"\nOutput: true\nExplanation:\nThe 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.\n\n\nExample 2:\n\nInput: s = \"abab\"\nOutput: false\nExplanation:\nThere is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.\n\n\nExample 3:\n\nInput: s = \"bbb\"\nOutput: true\nExplanation:\nThere are no 'a's, hence, every 'a' appears before every 'b' and we return true.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts[i] is either 'a' or 'b'.\n\n",
        "solution_py": "class Solution:\n    def checkString(self, s: str) -> bool:\n        if \"ba\" in s:\n            return False\n        else:\n            return True",
        "solution_js": "var checkString = function(s) {\n    \n    // a cannot come after b\n    let violation = \"ba\";\n    \n    return s.indexOf(violation, 0) == -1;\n};",
        "solution_java": "class Solution {\n    public boolean checkString(String s) {\n        for(int i = 0; i < s.length(); i++){\n            if(s.charAt(i) == 'b'){\n                for(int j = i+1; j < s.length(); j++){\n                    if(s.charAt(j) == 'a'){\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool checkString(string s) {\n\t\tfor(int i = 1; i < s.size(); i++){\n\t\t\tif(s[i - 1] == 'b' && s[i] == 'a'){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};"
    },
    {
        "title": "Validate Binary Search Tree",
        "algo_input": "Given the root of a binary tree, determine if it is a valid binary search tree (BST).\n\nA valid BST is defined as follows:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [2,1,3]\nOutput: true\n\n\nExample 2:\n\nInput: root = [5,1,4,null,null,3,6]\nOutput: false\nExplanation: The root node's value is 5 but its right child's value is 4.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 &lt;= Node.val &lt;= 231 - 1\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n    def isValidBST(self, root: Optional[TreeNode]) -> bool:\n\n        def valid(node,left,right):\n            if not node: # checking node is none\n                return True\n            if not (node.val>left and node.val<right): # checking the left value is less than node and right value is greater than node\n                return False\n            return (valid(node.left,left,node.val) and valid(node.right,node.val,right)) # recursively calling left child and right child and returing the result True if both are true else False\n\n        return valid(root,float(\"-inf\"),float(\"inf\")) #calling recursive function to check",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar isValidBST = function(root) {\n    const nodesToCheck = [{node: root, lowerLimit: -Infinity, upperLimit: Infinity}]\n    \n    while (nodesToCheck.length > 0) {\n        const {node: currentNode, lowerLimit, upperLimit} = nodesToCheck.pop()\n        \n        if (currentNode.val <= lowerLimit || currentNode.val >= upperLimit) {\n            return false\n        }\n        \n        if (currentNode.left) {\n            nodesToCheck.push({\n                node: currentNode.left,\n                lowerLimit,\n                upperLimit: currentNode.val\n            })\n        }\n        \n        if (currentNode.right) {\n            nodesToCheck.push({\n                node: currentNode.right,\n                lowerLimit: currentNode.val,\n                upperLimit\n            })\n        }\n    }\n    \n    return true\n};",
        "solution_java": "class Solution {\n    public boolean isValidBST(TreeNode root) {\n        return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);\n    }\n    \n    public boolean dfs(TreeNode root, int min, int max) {\n        if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) ||                    (root.val == Integer.MAX_VALUE && root.right != null)) return false;\n        boolean leftRight = true;\n        if (root.left == null && root.right == null) return true;\n        if (root.left != null) {\n            leftRight = dfs(root.left, min, root.val - 1);\n        }\n        if (root.right != null) {\n            leftRight = dfs(root.right, root.val + 1, max) && leftRight;\n        }\n        return leftRight;\n    }\n}",
        "solution_c": "// We know inorder traversal of BST is always sorted, so we are just finding inorder traversal and check whether it is in sorted manner or not, but only using const space using prev pointer.\nclass Solution {\npublic:\n    TreeNode* prev;\n    Solution(){\n        prev = NULL;\n    }\n    bool isValidBST(TreeNode* root) {\n        if (root == NULL)\n            return true;\n        bool a = isValidBST(root->left);\n        if (!a)\n            return false;\n        if (prev != NULL)\n        {\n            if (prev->val >= root->val)\n                return false;\n        }\n        prev = root;\n        return isValidBST(root->right);\n    }\n};"
    },
    {
        "title": "Basic Calculator II",
        "algo_input": "Given a string s which represents an expression, evaluate this expression and return its value.&nbsp;\n\nThe integer division should truncate toward zero.\n\nYou may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].\n\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n\n&nbsp;\nExample 1:\nInput: s = \"3+2*2\"\nOutput: 7\nExample 2:\nInput: s = \" 3/2 \"\nOutput: 1\nExample 3:\nInput: s = \" 3+5 / 2 \"\nOutput: 5\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 3 * 105\n\ts consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.\n\ts represents a valid expression.\n\tAll the integers in the expression are non-negative integers in the range [0, 231 - 1].\n\tThe answer is guaranteed to fit in a 32-bit integer.\n\n",
        "solution_py": "class Solution:\n    def calculate(self, s: str) -> int:\n        stack = []\n        currentNumber = 0\n        operator = '+'\n        operations = '+-/*'\n        for i in range(len(s)):\n            ch = s[i]\n            if ch.isdigit():\n                currentNumber = currentNumber * 10 + int(ch)\n\n            if ch in operations or i == len(s) - 1:\n                if operator == '+':\n                    stack.append(currentNumber)\n\n                elif operator == '-':\n                    stack.append(-currentNumber)\n\n                elif operator == '*':\n                    stack.append(stack.pop() * currentNumber)\n\n                elif operator == '/':\n                    stack.append(int(stack.pop()/currentNumber))\n\n                currentNumber =0\n                operator = ch\n\n        return sum(stack)",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar calculate = function(s) {\n    const n = s.length;\n    let currNum = 0, lastNum = 0, res = 0;\n    let op = '+';\n    \n    for (let i = 0; i < n; i++) {\n        let currChar = s[i];\n        \n        if (currChar !== \" \" && !isNaN(Number(currChar))) {\n            currNum = currNum * 10 + Number(currChar);\n        }\n        \n        if (isNaN(Number(currChar)) && currChar !== \" \" || i === n - 1) {\n            if (op === '+' || op === '-') {\n                res += lastNum;\n                lastNum = (op === '+' ? currNum : -currNum);\n            } else if (op === '*') {\n                lastNum *= currNum;\n            } else if (op === '/') {\n                lastNum = Math.floor(Math.abs(lastNum) / currNum) * (lastNum < 0 ? -1 : 1);\n            }\n            \n            op = currChar;\n            currNum = 0;\n        }\n    }\n    \n    res += lastNum;\n    return res;\n};",
        "solution_java": "class Solution {\n    public int calculate(String s) {\n        if(s==null ||s.length()==0)return 0;\n        Stack<Integer> st = new Stack<>();\n        int curr=0;\n        char op = '+';\n        char [] ch = s.toCharArray();\n        for(int i=0;i<s.length();i++){\n            if(Character.isDigit(ch[i])){\n                curr= curr*10+ch[i]-'0';\n            }\n            if(!Character.isDigit(ch[i])&& ch[i]!=' ' || i==ch.length-1){\n                if(op=='+'){\n                    st.push(curr);\n                }else if(op=='-'){\n                    st.push(-curr);\n                }else if(op=='*'){\n                    st.push(st.pop()*curr);\n                }else if(op=='/'){\n                    st.push(st.pop()/curr);\n                }\n                op=ch[i];\n                curr=0;\n            }\n        }\n        int sum=0;\n        while(!st.isEmpty()){\n            sum+=st.pop();\n        }\n        return sum;\n    }\n} //TC=o(n),SC=o(n)",
        "solution_c": "class Solution {\npublic:\n    int calculate(string s) {\n        stack<int> nums;\n        stack<char> ops;\n        int n = 0;\n        for(int i = 0; i < s.size(); ++i){\n            if(s[i] >= '0' && s[i] <= '9'){\n                string t(1, s[i]);\n                n = n*10 + stoi(t);\n            }else if( s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){\n                nums.push(n);\n                n = 0;\n                if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){\n                    int n2 = nums.top(); nums.pop();\n                    int n1 = nums.top(); nums.pop();\n                    if(ops.top() == '*') nums.push(n1*n2);\n                    else nums.push(n1/n2);\n                    ops.pop();\n                }\n                ops.push(s[i]);\n            }\n        }\n        nums.push(n);\n        if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){\n            int n2 = nums.top(); nums.pop();\n            int n1 = nums.top(); nums.pop();\n            if(ops.top() == '*') nums.push(n1*n2);\n            else nums.push(n1/n2);\n            ops.pop();\n        }\n        stack<int> tnums;\n        stack<char> tops;\n        while(!nums.empty()){ tnums.push(nums.top()); nums.pop();}\n        while(!ops.empty()) { tops.push(ops.top()); ops.pop(); }\n        \n        while(!tops.empty()){ //cout<<tops.top()<<\" \" ;\n            int n1 = tnums.top(); tnums.pop();\n            int n2 = tnums.top(); tnums.pop();\n            if(tops.top() == '+') tnums.push(n1 + n2);\n            else tnums.push(n1 - n2);\n            tops.pop();\n        }\n        return tnums.top();\n    }\n};"
    },
    {
        "title": "N-ary Tree Preorder Traversal",
        "algo_input": "Given the root of an n-ary tree, return the preorder traversal of its nodes' values.\n\nNary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [1,3,5,6,2,4]\n\n\nExample 2:\n\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t0 &lt;= Node.val &lt;= 104\n\tThe height of the n-ary tree is less than or equal to 1000.\n\n\n&nbsp;\nFollow up: Recursive solution is trivial, could you do it iteratively?\n",
        "solution_py": "function preorder(root: Node | null): number[] {\n  const res: number[] = [];\n\n  const getNodeVal = (node: Node | null): void => {\n    if (node) {\n      res.push(node.val);\n\n      for (let i = 0; i < node.children.length; i++) {\n        getNodeVal(node.children[i]);\n      }\n    }\n  };\n\n  getNodeVal(root);\n\n  return res;\n}",
        "solution_js": "var preorder = function(root) {\n    return [root.val].concat(root.children.map( (c)=>c ? preorder(c) : [] ).flat() );\n};",
        "solution_java": "class Solution {\n    public List<Integer> preorder(Node root) {\n        if (root == null) return new ArrayList<Integer>();\n        \n        Stack<Node> stk = new Stack<Node>();\n        ArrayList<Integer> arr = new ArrayList<Integer>();\n        stk.push(root);\n        Node ref;\n        while(!stk.empty()) {\n            ref = stk.pop();\n            // System.out.println(ref.val);\n            arr.add(ref.val);\n            for(int i=ref.children.size() - 1;i>=0;i--) {\n                stk.push(ref.children.get(i));\n            }\n        }\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> preorder(Node* root) {\n        vector<int>ans;\n        stack<Node*>st;\n        st.push(root);\n        while(!st.empty()){\n            auto frnt=st.top();\n            st.pop();\n            ans.push_back(frnt->val);\n            for(int i=frnt->children.size()-1;i>=0;i--){\n                st.push(frnt->children[i]);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Height Trees",
        "algo_input": "A tree is an undirected graph in which any two vertices are connected by&nbsp;exactly&nbsp;one path. In other words, any connected graph without simple cycles is a tree.\n\nGiven a tree of n nodes&nbsp;labelled from 0 to n - 1, and an array of&nbsp;n - 1&nbsp;edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes&nbsp;ai and&nbsp;bi in the tree,&nbsp;you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))&nbsp; are called minimum height trees (MHTs).\n\nReturn a list of all MHTs' root labels.&nbsp;You can return the answer in any order.\n\nThe height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput: [1]\nExplanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\n\n\nExample 2:\n\nInput: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput: [3,4]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 2 * 104\n\tedges.length == n - 1\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tAll the pairs (ai, bi) are distinct.\n\tThe given input is guaranteed to be a tree and there will be no repeated edges.\n\n",
        "solution_py": "class Solution:\n    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n        if n==0:\n            return []\n        if n==1:return [0]\n        adj=[[] for i in range (n)]\n        degree=[0]*n\n        for i in edges:\n            adj[i[0]].append(i[1])\n            adj[i[1]].append(i[0])\n            degree[i[0]]+=1\n            degree[i[1]]+=1\n            \n        print(adj)\n        q=[]\n        for i in range(n):\n            if degree[i]==1:\n                q.append(i)\n                \n        while n>2:\n            size=len(q)\n            n-=size\n            while size>0:\n                v=q.pop(0)\n                for i in adj[v]:\n                    degree[i]-=1\n                    if degree[i]==1:\n                        q.append(i)\n                size-=1\n        return q\n                \n            \n        ",
        "solution_js": "var findMinHeightTrees = function(n, edges) {\n  \n    //edge case\n    if(n <=0) return [];\n    if(n === 1) return [0]\n  \n  \n    let graph ={}\n    let indegree  = Array(n).fill(0)\n    let leaves = []\n    // build graph\n    \n    for(let [v,e] of edges){\n      //as this is undirected graph we will build indegree for both e and v\n      if(!(v in graph)) graph[v] = [];\n      if(!(e in graph)) graph[e] = [];\n      graph[v].push(e)\n      graph[e].push(v)\n      indegree[v]++\n      indegree[e]++\n    }\n  \n  \n  // get all nodes with indegree 1\n    for(let i =0; i<indegree.length; i++){\n      if(indegree[i] === 1) leaves.push(i)\n    }\n  \n  \n    let total  = n;\n  \n    while(total > 2){\n      let size = leaves.length\n      // as we are removing nodes from our  total\n      total -= size;\n      \n      for(let i =0 ; i<size; i++){\n        let vertex = leaves.shift()\n        for(let edge of  graph[vertex] ){\n          indegree[edge]--\n          if(indegree[edge] === 1) leaves.push(edge)\n        }\n      }\n    }\n  \n  return leaves;\n    \n};",
        "solution_java": "class Solution {\n    public List<Integer> findMinHeightTrees(int n, int[][] edges) {\n        if(edges.length == 0) {\n            List<Integer> al = new ArrayList<>();\n            al.add(0);\n            return al;\n        }\n        HashMap<Integer, Set<Integer>> map = new HashMap<>(); // map == graph\n        int [] degree = new int[n];\n        for(int [] edge : edges){\n            int src = edge[0];\n            int dest = edge[1];\n            map.putIfAbsent(src, new HashSet<>());\n            map.get(src).add(dest);\n            map.putIfAbsent(dest, new HashSet<>());\n            map.get(dest).add(src);\n            degree[src]++;\n            degree[dest]++;\n        }\n        Queue<Integer> q = new ArrayDeque<>();\n        for(int i = 0; i < degree.length; i++){\n            if(degree[i] == 1){\n                q.offer(i);\n            }\n        }\n        int count = n;\n        while(count > 2){\n            int size = q.size();\n            count -= size;\n            while(size-- > 0){\n                Integer src = q.poll();\n\n                for(Integer connection : map.get(src)){\n                    degree[connection]--;\n                    if(degree[connection] == 1){\n                        q.offer(connection);\n                    }\n                }\n            }\n        }\n        return new ArrayList<>(q);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getheight(vector<int> a[],int sv,int n)\n    {\n        int lvl = 0;\n        vector<int> vis(n,0);\n        queue<int> q;\n        q.push(sv);\n        vis[sv] = 0;\n        while(q.size())\n        {\n            int sz = q.size();\n            lvl++;\n            while(sz--)\n            {\n                int curr = q.front();\n                q.pop();\n                vis[curr] = 1;\n                \n                for(auto it:a[curr])\n                {\n                    if(vis[it]==0)\n                    {\n                        q.push(it);\n                    }\n                }\n            }\n        }\n        return lvl;\n    }\n    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {\n        vector<int> a[n];\n        vector<int> indegree(n,0);\n        for(auto it:edges)\n        {\n            a[it[0]].push_back(it[1]);\n            a[it[1]].push_back(it[0]);\n            indegree[it[0]]++;\n            indegree[it[1]]++;\n        }\n        \n        //cutting leafs whose indegree is 1\n        queue<int> q;\n        vector<int> ans;\n        for(int i = 0;i<n;i++)\n        {\n            if(indegree[i]==1)\n            {\n                q.push(i);\n                indegree[i]--;\n            }\n        }\n        \n        while(q.size())\n        {\n            int sz=q.size();\n            ans.clear();\n            while(sz--)\n            {\n                int curr = q.front();\n                q.pop();\n                ans.push_back(curr);\n                for(auto it:a[curr])\n                {\n                    indegree[it]--;\n                    if(indegree[it]==1)\n                        q.push(it);\n                }\n            }\n        }\n        \n        if(n==1)return {0};\n        \n        return ans;\n        \n        \n        //brute force gives tle\n//         int mn = INT_MAX;\n//         unordered_map<int,vector<int>> mp;\n//         for(int i = 0;i<n;i++)\n//         {\n//             int x = getheight(a,i,n);\n//             mp[x].push_back(i);\n            \n//             // cout<<i<<\" \"<<x<<endl;\n            \n//             mn = min(mn,x);\n//         }\n        \n//         return mp[mn];\n        \n    }\n};"
    },
    {
        "title": "Max Sum of Rectangle No Larger Than K",
        "algo_input": "Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.\n\nIt is guaranteed that there will be a rectangle with a sum no larger than k.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput: 2\nExplanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n\n\nExample 2:\n\nInput: matrix = [[2,2,-1]], k = 3\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 100\n\t-100 &lt;= matrix[i][j] &lt;= 100\n\t-105 &lt;= k &lt;= 105\n\n\n&nbsp;\nFollow up: What if the number of rows is much larger than the number of columns?\n",
        "solution_py": "class Solution:\n    def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n        import numpy as np\n        \n        matrix = np.array(matrix, dtype=np.int32)\n        \n        M,N = matrix.shape\n        \n        ret = float(\"-inf\")\n        \n        CUM = np.zeros((M,N), dtype=np.int32)\n        for shift_r in range(M):\n            CUM[:M-shift_r] += matrix[shift_r:]\n            \n            _CUM = np.zeros((M-shift_r,N), dtype=np.int32)\n            for shift_c in range(N):\n                _CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]\n                tmp = _CUM[(_CUM<=k) & (_CUM>ret)]\n                if tmp.size:\n                    ret = tmp.max()\n            if ret == k:\n                return ret\n        \n        return ret\n\n'''",
        "solution_js": "/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nvar maxSumSubmatrix = function(matrix, k) {\n    if (!matrix.length) return 0;\n\n    let n = matrix.length, m = matrix[0].length;\n    let sum = new Array(n + 1).fill(0).map(a => new Array(m + 1).fill(0));\n    let ans = -Infinity;\n\n    for (let i = 1; i <= n; i++) {\n        for (let j = 1; j <= m; j++) {\n            sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];\n            for(let x = 1; x <= i; ++x) {\n                for(let y = 1; y <= j; ++y) {\n                    let s = rangeSum(sum, x, y, i, j);\n                    if (s <= k) {\n                        ans = Math.max(s, ans);\n                    }\n                }\n            }\n        }\n    }\n    return ans;\n}\n\nconst rangeSum = (sum, x1, y1, x2, y2) => {\n    return sum[x2][y2] - sum[x1-1][y2] - sum[x2][y1-1] + sum[x1-1][y1-1];\n}",
        "solution_java": "class Solution {\n    public int maxSumSubmatrix(int[][] matrix, int tar) {\n        int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar;\n        for(i=0;i<n;i++){\n            for(j=0;j<m;j++){\n                dp[i][j]=matrix[i][j];\n                if(j>0) dp[i][j]+=dp[i][j-1];\n            }\n        }\n        for(i=0;i<n;i++){\n            for(j=0;j<m;j++){\n                if(i>0) dp[i][j]+=dp[i-1][j];\n            }\n        }\n        for(i=0;i<n;i++){\n            for(j=0;j<m;j++){\n                for(k=i;k<n;k++){\n                    for(l=j;l<m;l++){\n                        val=dp[k][l];\n                        if((i-1)>=0 && (j-1)>=0) val += dp[i-1][j-1];\n                        if((i-1)>=0) val=val-dp[i-1][l];\n                        if((j-1)>=0) val=val-dp[k][j-1];\n                        if(val>max && val<=target) max=val;\n                    }\n                }\n            }\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // function for finding maximum subarray having sum less than k\n\n    int find_max(vector<int>& arr, int k)\n    {\n        int n = arr.size();\n\n        int maxi = INT_MIN;\n\n        // curr_sum will store cumulative sum\n\n        int curr_sum = 0;\n\n        // set will store the prefix sum of array\n\n        set<int> s;\n\n        // put 0 into set, if curr_sum == k, (curr_sum - k) will be zero\n\n        s.insert(0);\n\n        for(int i = 0; i < n; i++)\n        {\n            // calculate cumulative sum\n\n            curr_sum += arr[i];\n\n            // find the prefix sum in set having sum == curr_sum - k\n\n            auto it = s.lower_bound(curr_sum - k);\n\n            // if prefix sum is present, update the maxi\n\n            if(it != s.end())\n            {\n                maxi = max(maxi, curr_sum - *it);\n            }\n\n            // insert prefix sum into set\n\n            s.insert(curr_sum);\n        }\n\n        return maxi;\n    }\n\n    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {\n\n        int n = matrix.size();\n\n        int m = matrix[0].size();\n\n        int maxi = INT_MIN;\n\n        // fix the position two two rows and take cumulative sum of columns between two fixed rows\n\n        for(int start_row = 0; start_row < n; start_row++)\n        {\n            vector<int> col_array(m, 0);\n\n            for(int end_row = start_row; end_row < n; end_row++)\n            {\n                // take cumulative sum of columns between two fixed rows\n\n                for(int col = 0; col < m; col++)\n                {\n                    col_array[col] += matrix[end_row][col];\n                }\n\n                // find maximum subarray having sum less than equal to k\n\n                int curr_max = find_max(col_array, k);\n\n                // update the maximum sum\n\n                maxi = max(maxi, curr_max);\n            }\n        }\n\n        return maxi;\n    }\n};"
    },
    {
        "title": "Minimum Number of Flips to Make the Binary String Alternating",
        "algo_input": "You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:\n\n\n\tType-1: Remove the character at the start of the string s and append it to the end of the string.\n\tType-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.\n\n\nReturn the minimum number of type-2 operations you need to perform such that s becomes alternating.\n\nThe string is called alternating if no two adjacent characters are equal.\n\n\n\tFor example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"111000\"\nOutput: 2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".\n\n\nExample 2:\n\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating.\n\n\nExample 3:\n\nInput: s = \"1110\"\nOutput: 1\nExplanation: Use the second operation on the second element to make s = \"1010\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def minFlips(self, s: str) -> int:\n        prev = 0\n        start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n        odd = len(s)%2\n        for val in s:\n            val = int(val)\n            if val == prev:\n                if odd:\n                    start_0_odd = min(start_0_odd, start_1)\n                    start_1_odd += 1\n                start_1 += 1\n            else:\n                if odd:\n                    start_1_odd = min(start_1_odd, start_0)\n                    start_0_odd += 1\n                start_0 += 1\n            prev = 1 - prev\n        return min([start_1, start_0, start_1_odd, start_0_odd])",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minFlips = function(s) {\n    let length = s.length-1\n    let flipMap = {\n        '1': '0',\n        '0': '1'\n    }\n    s = s + s\n    let alt1 = '1'\n    let alt2 = '0'\n    let left = 0\n    let right = 0\n    let diff1 = 0\n    let diff2 = 0\n    let min = Infinity\n\n    while (right < s.length) {\n        if (right > 0) {\n            alt1 = flipMap[alt1]\n            alt2 = flipMap[alt2]\n        }\n\n        let current = s[right]\n        if (current !== alt1) diff1++\n        if (current !== alt2) diff2++\n        if (right-left === length) {\n            min = Math.min(diff1, diff2, min)\n            if ((length+1)%2 === 0) {\n                if (s[left] !== flipMap[alt1]) diff1--\n                if (s[left] !== flipMap[alt2]) diff2--\n            } else {\n                if (s[left] !== alt1) diff1--\n                if (s[left] !== alt2) diff2--\n            }\n            left++\n        }\n        right++\n    }\n    return min\n};",
        "solution_java": "class Solution {\n    public int minFlips(String s) {\n        /*\n        * Sliding Window Approach\n        */\n        \n        \n        int n = s.length();\n        \n        int mininumFlip = Integer.MAX_VALUE;\n        \n        int misMatchCount = 0;\n        for(int i = 0; i < (2 * n); i++){\n            \n            int r = i % n;\n            \n            //add mis watch count in current window\n            if((s.charAt(r) - '0') != (i % 2 == 0 ? 1 : 0)) misMatchCount++;\n            \n            //remove mismatch count which are not relvent for current window\n            if(i >= n && (s.charAt(r) - '0') != (r % 2 == 0 ? 1 : 0)) misMatchCount--;\n            \n            \n            //misMatchCount : when valid binary string start from 1\n            //n - misMatchCount : when valid binary string start from 0\n            if(i >= n - 1) mininumFlip = Math.min(mininumFlip, Math.min(misMatchCount, n - misMatchCount));\n        }\n        \n        return mininumFlip;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minFlips(string s)\n    {\n     int n = s.size();\n     string ss = s+s;\n     string s1, s2;\n     int ans = INT_MAX;\n     for(int i=0; i<ss.size(); i++)\n     {\n         s1+=(i%2?'1':'0');\n         s2+=(i%2?'0':'1');\n     }\n     int ans1 = 0, ans2 = 0;\n     for(int i=0; i<ss.size(); i++)\n     {\n         if(s1[i]!=ss[i]) ans1++;\n         if(s2[i]!=ss[i]) ans2++;\n         if(i>=n-1)\n         {\n             if(i!=n-1 && s1[i-n]!=ss[i-n]) ans1--;\n             if(i!=n-1 && s2[i-n]!=ss[i-n]) ans2--;\n             ans = min({ans,ans1,ans2});\n         }\n     }\n     return ans;\n    }\n};"
    },
    {
        "title": "Range Sum of Sorted Subarray Sums",
        "algo_input": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.\n\nReturn the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput: 13 \nExplanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. \n\n\nExample 2:\n\nInput: nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput: 6\nExplanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput: 50\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 100\n\t1 &lt;= left &lt;= right &lt;= n * (n + 1) / 2\n\n",
        "solution_py": "from itertools import accumulate\n\nclass Solution:\n    def rangeSum(self, nums, n, left, right):\n        acc = []\n\n        for i in range(n):\n            acc.extend(accumulate(nums[i:]))\n\n        acc.sort()\n\n        return sum(acc[left - 1:right]) % (10**9 + 7)",
        "solution_js": "var rangeSum = function(nums, n, left, right) {\n    const sums = [];\n    \n    for (let i = 0; i < nums.length; i++) {\n        let sum = 0;\n        \n        for (let j = i; j < nums.length; j++) {\n            sum += nums[j];\n            sums.push(sum);\n        }\n    }\n    \n    sums.sort((a, b) => a - b);\n    \n    let ans = 0;\n    \n    for (let i = left - 1; i < right; i++) {\n        ans += sums[i];\n    }\n    \n    return ans % 1000000007;\n};",
        "solution_java": "class Solution {\n    private static int mod=(int)1e9+7;\n    public int rangeSum(int[] nums, int n, int left, int right) {\n        \n        PriorityQueue<int[]> pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]);\n        \n        for(int i=0;i<n;i++) pq.add(new int[]{i,nums[i]});\n        \n        int ans=0;\n        for(int i=1;i<=right;i++){\n            int[] k=pq.remove();\n            if(i>=left){\n                ans=(ans+k[1])%mod;\n            }\n            if(k[0]+1<n){\n                pq.add(new int[]{k[0]+1,k[1]+nums[k[0]+1]});\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution \n{\npublic:\n    int rangeSum(vector<int>& nums, int n, int left, int right) \n    {\n        const int m= 1e9+7; // To return ans % m\n        int ans=0;  // Final Answer\n        int k=1;  // For 1 based indexing\n        int size= (n*(n+1))/2;  // We can form n(n+1)/2 subarrays for an array of size n\n        vector<int> subsum(size+1); \n        for(int i=0;i<n;i++)\n        {\n            int sum=0;\n            for(int j=i;j<n;j++)\n            {\n                sum+=nums[j];     // Sum of the subarray\n                subsum[k++]=sum;   // Inserting the prefix sum at the index\n            }\n        }\n        sort(subsum.begin(),subsum.end()); // Sorting the array\n        for(int i=left; i<=right; i++)\n        {\n            ans=(ans+subsum[i])%m;   // ans modulo 10^9 +7\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Index Sum of Two Lists",
        "algo_input": "Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.\n\nYou need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.\n\n&nbsp;\nExample 1:\n\nInput: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]\nOutput: [\"Shogun\"]\nExplanation: The only restaurant they both like is \"Shogun\".\n\n\nExample 2:\n\nInput: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"KFC\",\"Shogun\",\"Burger King\"]\nOutput: [\"Shogun\"]\nExplanation: The restaurant they both like and have the least index sum is \"Shogun\" with index sum 1 (0+1).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= list1.length, list2.length &lt;= 1000\n\t1 &lt;= list1[i].length, list2[i].length &lt;= 30\n\tlist1[i] and list2[i] consist of spaces ' ' and English letters.\n\tAll the stings of list1 are unique.\n\tAll the stings of list2&nbsp;are unique.\n\n",
        "solution_py": "class Solution:\n    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n        \n      \n        hashmap1 = {}\n        hashmap2 = {}\n        common = {}\n        for i in range(len(list1)):\n            \n            hashmap1[list1[i]] = i \n            \n            \n        for j in range(len(list2)):\n            hashmap2[list2[j]] = j \n            \n     \n        \n        for i in hashmap1:\n            \n            if i in hashmap2:\n                print(1)\n                common[i] = hashmap1[i] + hashmap2[i]\n                \n        \n        common = list(common.items())\n        \n        answer =[]\n        minimum = float(\"inf\")\n        \n        for  i in range(0,len(common)):\n            \n            if common[i][1] < minimum:\n                minimum = common[i][1]\n                \n        for i in range(len(common)):\n            \n            if common[i][1] == minimum:\n                answer.append(common[i][0])\n        \n        return answer\n                \n        \n       ",
        "solution_js": "var findRestaurant = function(list1, list2) {\n    let obj ={}\n    for(let i =0; i <list1.length; i ++){\n        if(list2.indexOf(list1[i]) !==-1){\n            const sum = i+ list2.indexOf(list1[i])\n            if(obj[sum]!==undefined)\n                {\n                    obj[sum]['value'].push(list1[i])\n                }\n            else{\n                obj[sum]={}\n                obj[sum]['sum']=sum\n                obj[sum]['value']=[]\n                obj[sum]['value'].push(list1[i])\n            }\n\n        }\n    }\n    return Object.values(obj)[0]['value']\n\n};",
        "solution_java": "class Solution {\n    public String[] findRestaurant(String[] list1, String[] list2) {\n        List<String> l1 = Arrays.asList(list1);\n        int least = Integer.MAX_VALUE;\n        List<String> returnArray = new ArrayList<>();\n        Map<String, Integer> map = new HashMap<>();\n\n        for (int i = 0; i < list2.length; i++) {\n           if (l1.contains(list2[i])) {\n               map.put(list2[i], l1.indexOf(list2[i]) + i);\n           }\n        }\n        for (Map.Entry<String, Integer> entry: map.entrySet()){ \n            if (entry.getValue() <= least) least = entry.getValue();\n        }\n        for (Map.Entry<String, Integer> entry: map.entrySet()){ \n            if (entry.getValue() == least) returnArray.add(entry.getKey());\n        }\n        \n        if (returnArray.size() > 1) return returnArray.toArray(String[]::new);\n        return new String[]{returnArray.get(0)};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {\n      vector<string>vc;\n      unordered_map<string,int>umap,umap1;\n      \n      for(int i=0;i<list1.size();i++)\n      {\n        \n        \n        umap[list1[i]]=i;\n        \n      }\n      \n\n      for(int i=0;i<list2.size();i++)\n      {\n        \n        \n        umap1[list2[i]]=i;\n        \n      }\n      int min=10000;\nfor(auto i:umap)\n{\n  int k=0;\n  for(auto j :umap1)\n  {\n    \n    if(i.first==j.first)\n    {\n      k=i.second+j.second;\n      if(min>k)\n      {vc.clear();\n        min=k;\n       vc.push_back(j.first);\n      }\n      else if(k==min)\n      {\n        vc.push_back(j.first);\n      }\n        \n    }\n  }\n}\n  \n  \n  return vc;\n}\n};"
    },
    {
        "title": "Closest Divisors",
        "algo_input": "Given an integer num, find the closest two integers in absolute difference whose product equals&nbsp;num + 1&nbsp;or num + 2.\n\nReturn the two integers in any order.\n\n&nbsp;\nExample 1:\n\nInput: num = 8\nOutput: [3,3]\nExplanation: For num + 1 = 9, the closest divisors are 3 &amp; 3, for num + 2 = 10, the closest divisors are 2 &amp; 5, hence 3 &amp; 3 is chosen.\n\n\nExample 2:\n\nInput: num = 123\nOutput: [5,25]\n\n\nExample 3:\n\nInput: num = 999\nOutput: [40,25]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num &lt;= 10^9\n\n",
        "solution_py": "class Solution:\n\tdef closestDivisors(self, num: int) -> List[int]:\n\t\tfor i in range(int((num+2) ** (0.5)), 0, -1):  \n\t\t\tif not (num+1) % i: return [i, (num+1)//i] \n\t\t\tif not (num+2) % i: return [i, (num+2)//i] \n\t\treturn []",
        "solution_js": "/**\n * @param {number} num\n * @return {number[]}\n */\nvar closestDivisors = function(num) {\n    const n1 = num + 1;\n    const n2 = num + 2;\n\n    let minDiff = Infinity;\n    let result = [];\n    for(let i = Math.floor(Math.sqrt(n2)); i >= 1; i--) {\n        if(n1 % i === 0) {\n            const diff = Math.abs(i - (n1 / i));\n            if(diff < minDiff) {\n                minDiff = diff;\n                result = [i, n1 / i]\n            }\n        }\n\n        if(n2 % i === 0) {\n            const diff = Math.abs(i - (n2 / i));\n            if(diff < minDiff) {\n                minDiff = diff;\n                result = [i, n2 / i]\n            }\n        }\n    }\n\n    return result;\n};",
        "solution_java": "class Solution {\n    public int[] closestDivisors(int num) {\n        int ans[]=new int[2];\n        double a=Math.sqrt(num+1);\n        double b=Math.sqrt(num+2);\n        if(num==1){\n            ans[0]=1;\n            ans[1]=2;\n            return ans;\n        }\n        else if(a%1==0){\n            ans[0]=(int)a;\n            ans[1]=(int)b;\n            return ans;\n        }\n        else if(b%1==0){\n            ans[0]=(int)b;\n            ans[1]=(int)b;\n             return ans;\n        }\n        else{\n            int m=(int)Math.sqrt(num);\n       int diff1=Integer.MAX_VALUE;\n       int y=0,z=0,w=0,f=0;\n       for(int i=2;i<=m;i++){\n           if((num+1)%i==0){\n               y=i;\n               z=(num+1)/y;\n               int r=Math.abs(y-z);\n               if(r<diff1){\n                   diff1=r;\n               }\n           }\n       }\n       int diff2=Integer.MAX_VALUE;\n        for(int i=2;i<=m;i++){\n           if((num+2)%i==0){\n               w=i;\n               f=(num+2)/w;\n               int r=Math.abs(w-f);\n               if(r<diff2){\n                   diff2=r;\n               }\n           }\n       }\n            if(diff1<diff2){\n                ans[0]=y;\n            ans[1]=z;\n                 return ans;\n            }\n            else{\n                ans[0]=w;\n                ans[1]=f;\n                 return ans;\n            }\n        } \n    }\n}```",
        "solution_c": "class Solution \n{\n\tpublic:\n\tvector<int> findnumbers(int num)\n\t{\n\t\tint m=sqrt(num);\n\t\twhile(num%m!=0)\n\t\t{\n\t\t\tm--;\n\t\t}\n\t\treturn {num/m,m};\n\t}\n\tvector<int> closestDivisors(int num) \n\t{\n\t\tvector<int> ans1=findnumbers(num+1);\n\t\tvector<int> ans2=findnumbers(num+2);\n\t\tif(abs(ans1[0]-ans1[1])<abs(ans2[0]-ans2[1]))\n\t\t\treturn ans1;\n\t\treturn ans2;\n\t}\n};"
    },
    {
        "title": "Longest Palindromic Subsequence",
        "algo_input": "Given a string s, find the longest palindromic subsequence's length in s.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: s = \"bbbab\"\nOutput: 4\nExplanation: One possible longest palindromic subsequence is \"bbbb\".\n\n\nExample 2:\n\nInput: s = \"cbbd\"\nOutput: 2\nExplanation: One possible longest palindromic subsequence is \"bb\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestPalindromeSubseq(self, s: str) -> int:\n        n = len(s)\n        dp = [[0 for x in range(n)] for x in range(n)]\n        for i in range(n): dp[i][i] = 1 # Single length strings are palindrome\n        for chainLength in range(2, n+1):\n            for i in range(0, n-chainLength+1): # Discarding the lower triangle\n                j = i + chainLength - 1\n                if s[i] == s[j]: \n                    if chainLength == 2: dp[i][j] = 2\n                    else: dp[i][j] = dp[i+1][j-1] + 2\n                else: dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n        return dp[0][n-1]",
        "solution_js": "var longestPalindromeSubseq = function(s) {\n    const { length } = s;\n    const dp = Array(length).fill('').map(() => Array(length).fill(0));\n\n    for (let start = 0; start < length; start++) {\n        const str = s[start];\n        dp[start][start] = 1;\n\n        for (let end = start - 1; end >= 0; end--) {\n            dp[start][end] = str === s[end]\n                ? dp[start - 1][end + 1] + 2\n                : Math.max(dp[start - 1][end], dp[start][end + 1])\n        }\n    }\n    return dp[length - 1][0];\n};",
        "solution_java": "class Solution {\n    public int longestPalindromeSubseq(String s) {\n        \tStringBuilder sb = new StringBuilder(s);\n    \t    sb.reverse();\n    \t    String s2 = sb.toString();\n        return longestCommonSubsequence(s,s2);\n    }\n     public int longestCommonSubsequence(String text1, String text2) {\n        int [][]dp = new int[text1.length()+1][text2.length()+1]; \n        for(int i= text1.length()-1;i>=0;i--){\n            for(int j = text2.length()-1;j>=0;j--){\n                char ch1 = text1.charAt(i);\n                char ch2 = text2.charAt(j);\n                if(ch1==ch2) // diagnal\n                dp[i][j]= 1+dp[i+1][j+1];\n                else// right,down considering not matchning char from s1 and skipping s2 \n                //considering not matchning char from s2 and skipping s1\n                    dp[i][j] = Math.max(dp[i][j+1],dp[i+1][j]);\n                    \n            }\n        }\n        return dp[0][0];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int longestPalindromeSubseq(string s) {\n        int n = s.size();\n        int dp[n][n];\n        memset(dp, 0, sizeof(dp));\n        for(int i = 0; i < n; i++){\n            dp[i][i] = 1;\n        }\n        int res = 1;\n        for(int j = 1; j < n; j++){\n            for(int r = 0, c = j ; r < n && c < n; r++, c++){\n                if(s[r] == s[c]){\n                    dp[r][c] = 2+dp[r+1][c-1];\n                }\n                else{\n                    dp[r][c] = max(dp[r][c-1],dp[r+1][c]);\n                }\n            }\n        }\n        return dp[0][n-1];\n    }\n};"
    },
    {
        "title": "Complement of Base 10 Integer",
        "algo_input": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\n\n\n\tFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n\n\nGiven an integer n, return its complement.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: 2\nExplanation: 5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.\n\n\nExample 2:\n\nInput: n = 7\nOutput: 0\nExplanation: 7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.\n\n\nExample 3:\n\nInput: n = 10\nOutput: 5\nExplanation: 10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt; 109\n\n\n&nbsp;\nNote: This question is the same as 476: https://leetcode.com/problems/number-complement/\n",
        "solution_py": "class Solution:\n    def bitwiseComplement(self, n: int) -> int:\n        cnt=0\n        ans=0\n        if n==0:\n            return 1\n        while n>0:\n            if n&1:\n                cnt+=1\n            else:\n                ans =ans +(2**cnt)\n                cnt+=1\n            n=n>>1\n        return ans",
        "solution_js": "var bitwiseComplement = function(n) {\n    let xor = 0b1;\n    let copy = Math.floor(n / 2);\n    while (copy > 0) {\n        xor = (xor << 1) + 1\n        copy = Math.floor(copy / 2);\n    }\n        \n    return n ^ xor;\n};",
        "solution_java": "class Solution {\n    public int bitwiseComplement(int n) {\n        String bin = Integer.toBinaryString(n);\n        String res = \"\";\n        for(char c :bin.toCharArray())\n        {\n            if( c == '1')\n                res += \"0\";\n            else\n                res += \"1\";\n        }\n        return Integer.parseInt(res, 2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int bitwiseComplement(int num) {\n\t\t    //base case\n        if(num == 0) return 1;\n        unsigned mask = ~0;\n        while( mask & num ) mask = mask << 1;\n        return ~num ^ mask;\n    }\n};"
    },
    {
        "title": "Longest Subsequence Repeated k Times",
        "algo_input": "You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\nA subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.\n\n\n\tFor example, \"bba\" is repeated 2 times in the string \"bababcba\", because the string \"bbabba\", constructed by concatenating \"bba\" 2 times, is a subsequence of the string \"bababcba\".\n\n\nReturn the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"letsleetcode\", k = 2\nOutput: \"let\"\nExplanation: There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.\n\n\nExample 2:\n\nInput: s = \"bb\", k = 2\nOutput: \"b\"\nExplanation: The longest subsequence repeated 2 times is \"b\".\n\n\nExample 3:\n\nInput: s = \"ab\", k = 2\nOutput: \"\"\nExplanation: There is no subsequence repeated 2 times. Empty string is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == s.length\n\t2 &lt;= n, k &lt;= 2000\n\t2 &lt;= n &lt; k * 8\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n        n = len(s)\n        max_chunk_sz = n // k\n        \n        d = collections.Counter(s)\n        chars = sorted([c for c in d if d[c] >= k], reverse=True)\n        if not chars:\n            return ''\n        \n        old_cand = chars\n        for m in range(2, max_chunk_sz+1):\n            new_cand = []\n            for t in self.get_next_level(old_cand, chars):\n                if self.find(s, t*k):\n                    new_cand.append(t)\n            \n            if len(new_cand) == 0:\n                break\n            old_cand = new_cand\n        return old_cand[0]\n        \n    def get_next_level(self, cand, chars):\n        for s in cand:\n            for ch in chars:\n                yield s + ch\n        \n    def find(self, s, t):\n        # find subsequence t in s\n        j = 0\n        for i in range(len(s)):\n            if s[i] == t[j]:\n                j += 1\n            if j == len(t):\n                return True\n        return False",
        "solution_js": "// Idea comes from:\n// https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1471930/Python-Answer-is-not-so-long-explained\n\nvar longestSubsequenceRepeatedK = function(s, k) {\n  const freq = {};\n  for (const c of s) {\n    if (!freq[c]) freq[c] = 0;\n    freq[c]++;\n  }\n\n  // Find hot string\n  let hot = \"\";\n  for (const [c, cnt] of Object.entries(freq)) {\n    const repeat = Math.floor(cnt / k);\n    hot += c.repeat(repeat);\n  }\n\n  // Find all subset and permutation of hot string\n  let targets = new Set();\n  const subsets = getSubset(hot);\n  for (const subset of subsets) {\n    const permutations = getPermutation(subset);\n    for (const per of permutations) targets.add(per);\n  }\n\n  // Sort targets by length and lexico\n  targets = [...targets].sort((a, b) => {\n    const delta = b.length - a.length;\n    if (delta) return delta;\n    return b.localeCompare(a);\n  });\n\n  // Filter s and check subsequence\n  s = [...s].filter(c => hot.includes(c)).join(\"\");\n  for (const tar of targets) {\n    if (isSubsequence(s, tar.repeat(k))) return tar;\n  }\n\n  return \"\";\n};\n\nfunction getSubset(str) {\n  const res = [\"\"];\n  for (const c of str) {\n    res.push(...res.map((curStr) => curStr + c));\n  }\n  return [...new Set(res)];\n};\n\nfunction getPermutation(str) {\n  let res = [\"\"];\n  for (const c of str) {\n    const resT = [];\n    for (const cur of res) {\n      for (let i = 0; i <= cur.length; i++) {\n        const curT = cur.substring(0, i) + c + cur.substring(i);\n        resT.push(curT);\n      }\n    }\n    res = resT;\n  }\n  return [...new Set(res)];\n};\n\nfunction isSubsequence(s, t) {\n  let i = 0;\n  for (let j = 0; j < s.length; j++) {\n    if (t[i] === s[j]) {\n      i++;\n      if (i === t.length) return true;\n    }\n  }\n  return false;\n}",
        "solution_java": "class Solution {\n    char[] A;\n    public String longestSubsequenceRepeatedK(String s, int k) {\n        A = s.toCharArray();\n        Queue<String> queue = new ArrayDeque<>();\n        queue.offer(\"\");\n        String ans = \"\";\n        int[] count = new int[26];\n        BitSet bit = new BitSet();\n        for (char ch : A) if (++count[ch-'a'] >= k){\n            bit.set(ch-'a');\n        }\n        while(!queue.isEmpty()){\n            String sb = queue.poll();\n            for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i+1)){\n                String res = sb+(char)(i+'a');\n                if (check(k, res)){\n                    ans = res;\n                    queue.offer(res);\n                }\n            }\n        }\n        return ans;\n    }\n\n    private boolean check(int k, String s){\n        int cnt = 0;\n        for (char ch : A){\n            if (s.charAt(cnt%s.length()) == ch && ++cnt >= k * s.length()){\n                return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int Alpha=26;\n    bool find(string &s,string &p,int k)\n    {\n        int j=0;\n        int n=s.size();\n        int count=0;\n        for(int i=0;i<n;i++)\n        {\n            if(s[i]==p[j])\n            {\n                j++;\n                if(j==p.size())\n                {\n                    count++;\n                    j=0;\n                }\n                if(count==k)\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n    string longestSubsequenceRepeatedK(string s, int k) \n    {\n        queue<string>q;\n        q.push(\"\");\n        string ans=\"\";\n        while(q.size())\n        {\n            auto temp=q.front();\n            q.pop();\n            for(int i=0;i<Alpha;i++)\n            {\n                string curr=temp+char('a'+i);\n                if(find(s,curr,k))\n                {\n                    ans=curr;\n                    q.push(curr);\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Construct K Palindrome Strings",
        "algo_input": "Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: s = \"annabelle\", k = 2\nOutput: true\nExplanation: You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"\n\n\nExample 2:\n\nInput: s = \"leetcode\", k = 3\nOutput: false\nExplanation: It is impossible to construct 3 palindromes using all the characters of s.\n\n\nExample 3:\n\nInput: s = \"true\", k = 4\nOutput: true\nExplanation: The only possible solution is to put each character in a separate string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase English letters.\n\t1 &lt;= k &lt;= 105\n\n",
        "solution_py": "from collections import Counter\n\nclass Solution:\n    def canConstruct(self, s: str, k: int) -> bool:\n        if k > len(s):\n            return False\n        h = Counter(s)\n        countOdd = 0\n        for value in h.values():\n            if value % 2:\n                countOdd += 1\n        if countOdd > k:\n            return False\n        return True",
        "solution_js": "var canConstruct = function(s, k) {\n    if(s.length < k) return false;\n    // all even all even\n    // all even max k odd\n    const freq = {};\n    for(let c of s) {\n        freq[c] = (freq[c] || 0) + 1;\n    }\n\n    let oddCount = 0;\n    const freqOfNums = Object.values(freq);\n    for(let cnt of freqOfNums) {\n        if(cnt & 1) oddCount++;\n    }\n\n    return oddCount <= k;\n};",
        "solution_java": "class Solution {\n    public boolean canConstruct(String s, int k) {\n        if(k==s.length())\n        {\n            return true;\n        }\n        else if(k>s.length())\n        {\n            return false;\n        }\n        Map<Character,Integer> map=new HashMap<Character,Integer>();\n        for(int i=0;i<s.length();i++)\n        {\n            if(map.containsKey(s.charAt(i)))\n            {\n                int count=map.get(s.charAt(i));\n                map.put(s.charAt(i),count+1);\n            }\n            else\n            {\n                map.put(s.charAt(i),1);\n            }\n        }\n        int odd=0;\n        for(Map.Entry<Character,Integer>ele:map.entrySet())\n        {\n            if((ele.getValue()%2)==1)\n            {\n                odd++;\n            }\n        }\n        return (odd<=k);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canConstruct(string s, int k) {\n        if(s.size() < k) return false;\n        \n        unordered_map<char, int> m;\n        for(char c : s) m[c]++;\n        \n        int oddFr = 0;\n        for(auto i : m) if(i.second % 2) oddFr++;\n        \n        return oddFr <= k;\n    }\n};"
    },
    {
        "title": "Find Closest Number to Zero",
        "algo_input": "Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.\n&nbsp;\nExample 1:\n\nInput: nums = [-4,-2,1,4,8]\nOutput: 1\nExplanation:\nThe distance from -4 to 0 is |-4| = 4.\nThe distance from -2 to 0 is |-2| = 2.\nThe distance from 1 to 0 is |1| = 1.\nThe distance from 4 to 0 is |4| = 4.\nThe distance from 8 to 0 is |8| = 8.\nThus, the closest number to 0 in the array is 1.\n\n\nExample 2:\n\nInput: nums = [2,-1,1]\nOutput: 1\nExplanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    \n    def findClosestNumber1(self, nums: List[int]) -> int:\n        return min(nums, key=lambda x: (abs(x), -x))\n    \n    def findClosestNumber2(self, nums: List[int]) -> int:\n        return min(nums, key=lambda x: abs(x - .1))\n    \n    def findClosestNumber3(self, nums: List[int]) -> int:\n        return max((-abs(x), x) for x in nums)[1]\n    \n    def findClosestNumber4(self, nums: List[int]) -> int:\n        return -min(zip(map(abs, nums), map(neg, nums)))[1]\n\n    def findClosestNumber5(self, nums: List[int]) -> int:\n        a = min(map(abs, nums))\n        return a if a in nums else -a\n\n    def findClosestNumber6(self, nums: List[int]) -> int:\n        a = abs(min(nums, key=abs))\n        return a if a in nums else -a\n\n    def findClosestNumber7(self, nums: List[int]) -> int:\n        x = min(nums, key=abs)\n        return x if x >= 0 or -x not in nums else -x\n    \n    def findClosestNumber8(self, nums: List[int]) -> int:\n        return min(sorted(nums, reverse=True), key=abs)\n    \n    def findClosestNumber9(self, nums: List[int]) -> int:        \n        a = abs(nums[0])\n        for x in nums:\n            if x < 0:\n                x = -x\n            if x < a:\n                a = x\n        return a if a in nums else -a\n        \n    def findClosestNumberA(self, nums: List[int]) -> int:        \n        pos = 999999\n        neg = -pos\n        for x in nums:\n            if x < 0:\n                if x > neg:\n                    neg = x\n            elif x < pos:\n                pos = x\n        return pos if pos <= -neg else neg\n        \n    def findClosestNumberB(self, nums: List[int]) -> int:        \n        pos = 999999\n        neg = -pos\n        for x in nums:\n            if x < pos and neg < x:\n                if x < 0:\n                    neg = x\n                else:\n                    pos = x\n        return pos if pos <= -neg else neg\n        \n    def findClosestNumberC(self, nums: List[int]) -> int:        \n        pos = 999999\n        neg = -pos\n        for x in nums:\n            if neg < x and x < pos:\n                if x < 0:\n                    neg = x\n                else:\n                    pos = x\n        return pos if pos <= -neg else neg\n        \n    def findClosestNumberD(self, nums: List[int]) -> int:        \n        pos = 999999\n        neg = -pos\n        for x in nums:\n            if neg < x < pos:\n                if x < 0:\n                    neg = x\n                else:\n                    pos = x\n        return pos if pos <= -neg else neg\n        \n    def findClosestNumber(self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]) -> int:\n        name = 'findClosestNumber'\n        solutions = [getattr(self, s)\n                     for s in dir(self)\n                     if s.startswith(name)\n                     and s != name]\n        expect = dummy = object()\n        from time import perf_counter as time\n        for i in range(10):\n            shuffle(solutions)\n            for solution in solutions:\n                start = time()\n                result = solution(nums)\n                end = time()\n                if expect is dummy:\n                    expect = result\n                assert result == expect\n                timess[solution.__name__][i] += end - start\n        testcase[0] += 1\n        if testcase[0] == 224:\n            for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):\n                print(name, *(f'{t*1e3:6.2f} ms' for t in sorted(times)[:3]))\n            return\n        return result\n\t\t",
        "solution_js": "//Solution 1\nvar findClosestNumber = function(nums) {\n    \n    let pos = Infinity;\n    let neg = -Infinity;\n    \n    for(let i = 0; i < nums.length; i++) {\n        \n        if( nums[i] > 0 ){\n           if( pos > nums[i] ) \n               pos = nums[i];               \n        } else {\n            if( neg < nums[i] )\n                neg = nums[i];\n        } \n    }\n    \n    if( -neg < pos ) {\n       return neg;\n    }\n    \n    return pos;   \n};\n\n//Solution 2\nvar findClosestNumber = function(nums) {\n    \n    let result = nums[0];\n    \n    for(let i=1; i<nums.length; i++) {\n        \n        let mod = Math.abs(nums[i]);\n        \n        if( Math.abs(result)>mod ) {            \n            result = nums[i]\n        }\n        \n        if( Math.abs(result) == mod ) {\n            if( result<nums[i] ) {\n                result = nums[i];\n            }\n        }\n    }\n    \n    return result;    \n};",
        "solution_java": "// If absolute of n is less than min, update the closest_num \n// If absolute of n is same of as min, update the bigger closest_num\n\nclass Solution {\n    public int findClosestNumber(int[] nums) {\n        int min = Integer.MAX_VALUE, closest_num = 0;\n        for(int n : nums) {\n            if(min > Math.abs(n)) {\n                min = Math.abs(n);\n                closest_num = n;\n            } else if(min == Math.abs(n) && closest_num < n) {\n                closest_num = n;\n            }\n        }\n        return closest_num;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findClosestNumber(vector<int>& nums) {\n// setting the ans to maximum value of int\n        int ans = INT_MAX ;\n        for(int i : nums){\n        // checking if each value of nums is less than the max value\n            if(abs(i) < abs(ans)){\n                ans = i ; //check for the lesser value\n            }\n            else if(abs(i) == abs(ans)){\n                ans = max (ans,i) ; // return the maximum in cases there are multiple answers\n            }\n        }\n        return ans ;\n    }\n};"
    },
    {
        "title": "Minimum Skips to Arrive at Meeting On Time",
        "algo_input": "You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.\n\nAfter you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.\n\n\n\tFor example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly&nbsp;2&nbsp;hours, you do not need to wait.\n\n\nHowever, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.\n\n\n\tFor example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.\n\n\nReturn the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.\n\n&nbsp;\nExample 1:\n\nInput: dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput: 1\nExplanation:\nWithout skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\n\n\nExample 2:\n\nInput: dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput: 2\nExplanation:\nWithout skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\n\n\nExample 3:\n\nInput: dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput: -1\nExplanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == dist.length\n\t1 &lt;= n &lt;= 1000\n\t1 &lt;= dist[i] &lt;= 105\n\t1 &lt;= speed &lt;= 106\n\t1 &lt;= hoursBefore &lt;= 107\n\n",
        "solution_py": "from math import *\nclass Solution:\n    def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n        n=len(dist)\n\t\t# Error Range 10^-9 can be ignored in ceil, so we will subtract this value before taking ceil \n        e=1e-9\n        mat=[[0 for i in range(n)]for j in range(n)]\n        mat[0][0]=dist[0]/speed\n\t\t# Initialization \n\t\t# Values where 0 skips are considered\n        for i in range(1,n):\n            mat[i][0]=ceil(mat[i-1][0]-e)+dist[i]/speed\n        for i in range(1,n):\n            for j in range(1,i):\n                mat[i][j]=min(ceil(mat[i-1][j]-e),mat[i-1][j-1])+dist[i]/speed\n            mat[i][i]=mat[i-1][i-1]+dist[i]/speed\n        for i in range(n):\n            if mat[-1][i]<=hoursBefore:\n                return i\n        return -1",
        "solution_js": "var minSkips = function(dist, speed, hoursBefore) {\n\n    // calculates the time needed to rest\n    const getRestTime = (timeFinished) => {\n        if (timeFinished === Infinity) return 0;\n        return (speed - (timeFinished % speed)) % speed;\n    }\n\n    // dp is a n x n matrix with\n    // dp[destinationIndex][numRestsSkipped] = timeTaken\n    //\n    // destinationIndex: the index of the destination being observed\n    // numRestsSkipped: number of rests taken\n    // timeTaken: minimum time taken to travel to destination taking numRests number of rests\n    const dp = [...dist].map(() => new Array(dist.length).fill(Infinity));\n\n    // start with the first stop\n    dp[0][0] = dist[0] + getRestTime(dist[0]) // took a rest at the first destination\n    dp[0][1] = dist[0]; // did not take a rest at the first destination\n\n    for (let distIdx = 1; distIdx < dist.length; distIdx++) {\n        const distance = dist[distIdx];\n        let timeToDestWithoutrest = dp[distIdx - 1][0] + distance;\n        dp[distIdx][0] = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);\n        for (let numRestsSkipped = 1; numRestsSkipped <= distIdx + 1; numRestsSkipped++) {\n            // calculate the time if taking a rest here\n            timeToDestWithoutrest = dp[distIdx - 1][numRestsSkipped] + distance;\n            const didRestTimeToDest = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);\n\n            // calculate the time without resting here\n            const didntRestTimeToDest = dp[distIdx - 1][numRestsSkipped - 1] + distance\n\n            // store the best time in the dp\n            dp[distIdx][numRestsSkipped] = Math.min(dp[distIdx][numRestsSkipped],\n                                                    didRestTimeToDest,\n                                                    didntRestTimeToDest);\n        }\n    }\n\n    // find the minimum number of rests visiting all the destinations\n    const speedHours = speed * hoursBefore;\n    for (let numRests = 0; numRests < dist.length; numRests++) {\n        if (dp[dist.length - 1][numRests] <= speedHours) {\n            return numRests;\n        }\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int minSkips(int[] dist, int speed, int hoursBefore) {\n        int N = dist.length, INF = (int)1e9;\n        int[] dp = new int[N];\n        Arrays.fill(dp, INF);\n        dp[0]=0; // before we start, we have a time of 0 for 0 cost\n        for (int i = 0 ; i<N; i++){\n            for (int j = i; j >= 0; j--){ // j (cost) is at most i (num of element-1) so we start from there.\n                dp[j]=Math.min(j==0?INF:dp[j-1]+dist[i], ceil(dp[j], speed)+dist[i]);\n            }\n        }\n        for (int i = 0; i < N; i++){ // find the min cost (i) such that the min time is no greater than hoursBefore\n            if (ceil(dp[i],speed)/speed<=hoursBefore){\n                return i;\n            }\n        }\n        return -1;\n    }\n\n    private int ceil(int n, int s){\n        return n+(s-n%s)%s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int>D;\n    long long s, last;\n    long long memo[1010][1010];\n    long long dfs_with_minimum_time_with_k_skip(int idx, int k) {\n        if (idx < 0 ) return 0;\n        long long &ret = memo[idx][k];\n        if (ret != -1 ) return ret;\n        long long d = dfs_with_minimum_time_with_k_skip(idx - 1, k) + D[idx];\n        if (d % s) d = ((d/s) + 1)*s;\n        ret = d;\n        if (k > 0 ) ret = min(ret, dfs_with_minimum_time_with_k_skip(idx - 1, k - 1) + D[idx]);\n        return ret;\n    }\n    int minSkips(vector<int>& dist, int speed, int hoursBefore) {\n        int n = dist.size();\n        D = dist, s = speed;\n        int lo = 0, hi = n;\n        long long d = 0, H = hoursBefore;\n        H *=s;\n        last = dist[n-1];\n        for (int dd : dist) d += dd;\n        memset(memo, -1, sizeof(memo));\n        if (d /s > hoursBefore) return -1;\n        while (lo < hi) {\n            int mid = (lo + hi) / 2;\n            long long h = dfs_with_minimum_time_with_k_skip(n-2, mid) + last; // we should start from second last since it is not required to rest on last road\n            if (h <= H ) hi = mid;\n            else lo = mid + 1;\n        }\n        return lo == D.size() ? -1 : lo;\n\n    }\n};"
    },
    {
        "title": "Most Common Word",
        "algo_input": "Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.\n\nThe words in paragraph are case-insensitive and the answer should be returned in lowercase.\n\n&nbsp;\nExample 1:\n\nInput: paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\", banned = [\"hit\"]\nOutput: \"ball\"\nExplanation: \n\"hit\" occurs 3 times, but it is a banned word.\n\"ball\" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as \"ball,\"), \nand that \"hit\" isn't the answer even though it occurs more because it is banned.\n\n\nExample 2:\n\nInput: paragraph = \"a.\", banned = []\nOutput: \"a\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= paragraph.length &lt;= 1000\n\tparagraph consists of English letters, space ' ', or one of the symbols: \"!?',;.\".\n\t0 &lt;= banned.length &lt;= 100\n\t1 &lt;= banned[i].length &lt;= 10\n\tbanned[i] consists of only lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    import string\n    from collections import Counter\n    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n        #sunday morning hangover solution haha\n        \n        #calling this twice seems unnecesary but whatevs\n        #replace \",\" with \" \" (apparently translate() is much quicker than replace)\n        para = paragraph.translate(str.maketrans(\",\",\" \"))\n        #strip out rest of punctuation and make it lower case\n        para = para.translate(str.maketrans(' ', ' ', string.punctuation)).lower()\n        #split on the sapces\n        para = para.split()\n        #staple counter function\n        para_count = Counter(para)\n        #loop thru banned words, if they're in para_count pop the off\n        for word in banned:\n            if word in para_count:\n                para_count.pop(word)\n        #return val from most common\n        return para_count.most_common(1)[0][0]",
        "solution_js": "var mostCommonWord = function(paragraph, banned) {\n\tparagraph = new Map(Object.entries(\n\tparagraph\n\t\t.toLowerCase()\n\t\t.match(/\\b[a-z]+\\b/gi)\n\t\t.reduce((acc, cur) => ((acc[cur] = (acc[cur] || 0) + 1), acc), {}))\n\t\t.sort((a, b) => b[1] - a[1])\n\t);\n\tfor (let i = 0; i < banned.length; i++) paragraph.delete(banned[i]);\n\treturn paragraph.entries().next().value[0];\n};",
        "solution_java": "class Solution {\n    public String mostCommonWord(String paragraph, String[] banned) {\n\n        HashMap<String, Integer> hm = new HashMap<>();\n        String[] words = paragraph.replaceAll(\"[!?',;.]\",\" \").toLowerCase().split(\"\\\\s+\");\n        for(int i=0; i<words.length; i++)\n        {\n            if(hm.containsKey(words[i]))\n                hm.replace(words[i], hm.get(words[i]), hm.get(words[i])+1);\n            else\n                hm.put(words[i], 1);\n        }\n\n        for(int i=0; i< banned.length; i++)\n            if(hm.containsKey(banned[i]))\n                 hm.remove(banned[i]);\n\n        return Collections.max(hm.entrySet(), Map.Entry.comparingByValue()).getKey();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string mostCommonWord(string paragraph, vector<string>& banned) {\n        string temp;\n        vector<string> words;\n        for(char c:paragraph){\n            if(isalpha(c) && !isspace(c)) temp+=tolower(c);\n            else{\n                if(temp.length()) words.push_back(temp);\n                temp=\"\";\n            }\n        }\n        if(temp.length()) words.push_back(temp);\n        \n        map<string,int> mp;\n        for(string i:words) mp[i]++;\n        for(string i:banned) mp[i]=0;\n        string ans;\n        int maxUsedFreq=0;\n        for(auto i:mp){\n            if(i.second>maxUsedFreq){ \n                ans=i.first;\n                maxUsedFreq=i.second;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Teemo Attacking",
        "algo_input": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.\n\nYou are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.\n\nReturn the total number of seconds that Ashe is poisoned.\n\n&nbsp;\nExample 1:\n\nInput: timeSeries = [1,4], duration = 2\nOutput: 4\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\n\n\nExample 2:\n\nInput: timeSeries = [1,2], duration = 2\nOutput: 3\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= timeSeries.length &lt;= 104\n\t0 &lt;= timeSeries[i], duration &lt;= 107\n\ttimeSeries is sorted in non-decreasing order.\n\n",
        "solution_py": "class Solution:\n    def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n        \n        \"\"\"\n        timeDur = (timeSeries[0], timeSeries[0] + duration - 1)\n        i = 1\n        total = 0\n        while i < len(timeSeries):\n            if timeSeries[i] > timeDur[1]:\n                total += (timeDur[1] - timeDur[0] + 1)\n            else:\n                total += (timeSeries[i] - timeDur[0])\n            timeDur = (timeSeries[i], timeSeries[i] + duration - 1)\n            i += 1\n        total += (timeDur[1] - timeDur[0] + 1)\n        return total\n        \n        \"\"\"\n        # Between two interval, Ashe can be poisoned only for max duration time,\n        # if time differece is less than duranton, then we that value\n        total = 0\n        for i in range(len(timeSeries)-1):\n            total += min(duration, timeSeries[i+1] - timeSeries[i])\n        return total + duration\n            ",
        "solution_js": "var findPoisonedDuration = function(timeSeries, duration) {\n    let totalTime=duration\n\n    for(let i=0;i+1<timeSeries.length;i++){\n        let diff=timeSeries[i+1]-timeSeries[i]\n        totalTime+= diff>duration ? duration : diff\n    }\n    return totalTime\n\n};",
        "solution_java": "// Teemo Attacking\n// https://leetcode.com/problems/teemo-attacking/\n\nclass Solution {\n    public int findPoisonedDuration(int[] timeSeries, int duration) {\n        int sum = 0;\n        for (int i = 0; i < timeSeries.length; i++) {\n            if (i == 0) {\n                sum += duration;\n            } else {\n                sum += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);\n            }\n        }\n        return sum;       \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findPoisonedDuration(vector<int>& timeSeries, int duration) {\n        int ans=0;\n        int n=timeSeries.size();\n        for(int i=0;i<n;i++){\n            ans+=min(duration,(i==n-1?duration:timeSeries[i+1]-timeSeries[i]));\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Cousins in Binary Tree",
        "algo_input": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.\n\nTwo nodes of a binary tree are cousins if they have the same depth with different parents.\n\nNote that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4], x = 4, y = 3\nOutput: false\n\n\nExample 2:\n\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput: true\n\n\nExample 3:\n\nInput: root = [1,2,3,null,4], x = 2, y = 3\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 100].\n\t1 &lt;= Node.val &lt;= 100\n\tEach node has a unique value.\n\tx != y\n\tx and y are exist in the tree.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    ans = False\n    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:\n        def dfs(node, depth):\n            if self.ans or not node: return 0\n            if node.val == x or node.val == y: return depth\n            l = dfs(node.left, depth+1)\n            r = dfs(node.right, depth+1)\n            if not (l and r): return l or r\n            if l == r and l != depth + 1: self.ans = True\n            return 0\n        \n        dfs(root, 0)\n        return self.ans",
        "solution_js": "var isCousins = function(root, x, y) {\n    let xHeight = 1;\n    let xParent = null;\n    let yHeight = 1;\n    let yParent = null;\n    \n    const helper = (node, depth, parent) => {\n        if(node === null)\n            return null;\n        \n        helper(node.left, depth + 1, node);\n        helper(node.right, depth + 1, node);\n        \n        let val = node.val;\n        \n        if(val === x) {\n            xHeight = depth;\n            xParent = parent;\n        }\n        \n        if(val === y) {\n            yHeight = depth;\n            yParent = parent;\n        }\n    }\n    \n    helper(root, 0);\n    \n    return xHeight === yHeight && xParent !== yParent ? true : false;\n};",
        "solution_java": "class Solution {\n    public boolean isCousins(TreeNode root, int x, int y) {\n        Set<TreeNode> parentSet = new HashSet<>();\n        Queue<TreeNode> q = new LinkedList<>();\n        q.add(root);\n\n        while (!q.isEmpty()) {\n            int len = q.size();\n\n            for (int i = 0; i < len; i++) {\n                TreeNode parent = q.remove();\n\n                for (TreeNode child : new TreeNode[]{parent.left, parent.right}) {\n                    if(child != null) {\n                        q.add(child);\n                        if (child.val == x || child.val == y)\n                            parentSet.add(parent);\n                    }\n                }\n            }\n            if (parentSet.size() > 0)\n                return parentSet.size() == 2; //if same parent -> set size wil be 1\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isCousins(TreeNode* root, int x, int y) {\n        if(root -> left == NULL || root -> right == NULL) return false;\n        //to store node with parent\n        queue<pair<TreeNode*, TreeNode*> > q;\n        //push root\n        q.push({root, NULL});\n        //push NULL for level seperation\n        q.push({NULL, NULL});\n        //boolean val to know if we found x or y yet during traversal of tree\n        pair<bool, TreeNode*> foundx = {false, NULL}, foundy = {false, NULL};\n        \n        //start the level order traversal\n        while(!q.empty()){\n            TreeNode* top = q.front().first;\n            TreeNode* parent = q.front().second;\n            q.pop();\n            \n            //when a level is completely traversed\n            if(top == NULL){\n                //if we found both x and y and if their parent are not same we found cousins\n                if(foundx.first && foundy.first && foundx.second != foundy.second) return true;\n                //if one of them found when other not, or when both were found and their parent were equal\n                if(foundx.first || foundy.first) return false;\n                //push another NULL for further level seperation, if there are any.\n                if(!q.empty()) q.push({NULL, NULL});\n            }\n            else{\n                //find x and y\n                if(top -> val == x) foundx = {true, parent};\n                if(top -> val == y) foundy = {true, parent};\n                \n                //push current node's childs with parent as current node.\n                if(top -> left) q.push({top -> left, top});\n                if(top -> right) q.push({top -> right, top});\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Decrease Elements To Make Array Zigzag",
        "algo_input": "Given an array nums of integers, a move&nbsp;consists of choosing any element and decreasing it by 1.\n\nAn array A is a&nbsp;zigzag array&nbsp;if either:\n\n\n\tEvery even-indexed element is greater than adjacent elements, ie.&nbsp;A[0] &gt; A[1] &lt; A[2] &gt; A[3] &lt; A[4] &gt; ...\n\tOR, every odd-indexed element is greater than adjacent elements, ie.&nbsp;A[0] &lt; A[1] &gt; A[2] &lt; A[3] &gt; A[4] &lt; ...\n\n\nReturn the minimum number of moves to transform the given array nums into a zigzag array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: We can decrease 2 to 0 or 3 to 1.\n\n\nExample 2:\n\nInput: nums = [9,6,1,6,2]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def solve(self,arr,n,x):\n        idx = 1\n        ans = 0\n        while idx < n:\n            if idx == 0: idx += 1\n            if idx % 2 == x:\n                if arr[idx-1] >= arr[idx]:\n                    ans += arr[idx-1] - arr[idx] + 1\n                    arr[idx-1] = arr[idx] - 1\n                    idx = idx-1\n                else:\n                    idx = idx+1\n            else:\n                if arr[idx-1] <= arr[idx]:\n                    ans += arr[idx] - arr[idx - 1] + 1\n                    arr[idx] = arr[idx-1] - 1\n                idx += 1               \n        return ans\n    \n    def movesToMakeZigzag(self, nums: List[int]) -> int:\n        ans1 = self.solve([x for x in nums],len(nums),0)\n        ans2 = self.solve([x for x in nums],len(nums),1)\n        return min(ans1,ans2)",
        "solution_js": "var movesToMakeZigzag = function(nums) {\n    const n = nums.length;\n\n    let lastEvenRight = Number.MIN_SAFE_INTEGER;\n    let evenMoves = 0;\n\n    let lastOddRight = nums[0];\n    let oddMoves = 0;\n\n    for (let i = 0; i < n; i++) {\n        const currNum = nums[i];\n        const nextNum = i < n - 1 ? nums[i + 1] : Number.MIN_SAFE_INTEGER;\n\n        if (i % 2 === 0) {\n            if (lastEvenRight >= currNum) evenMoves += lastEvenRight - currNum + 1;\n\n            if (currNum <= nextNum) {\n                evenMoves += nextNum - currNum + 1;\n            }\n\n            lastEvenRight = Math.min(currNum - 1, nextNum);\n        }\n        else {\n            if (lastOddRight >= currNum) oddMoves += lastOddRight - currNum + 1;\n\n            if (currNum <= nextNum) {\n                oddMoves += nextNum - currNum + 1;\n            }\n\n            lastOddRight = Math.min(currNum - 1, nextNum);\n        }\n    }\n\n    return Math.min(oddMoves, evenMoves);\n};",
        "solution_java": "class Solution {\n    /*\n        firstly, check elements in odd indices are greater than its neighbours.\n        if not, decrease its neigbours and update the cost.\n        \n        do same thing for even indices, because there can be two combinations as indicated in question.\n    */\n    \n    private int calculateCost(int[] nums, int start){\n        int res = 0;\n        int n = nums.length;\n        int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.\n        \n        for(int i=start;i<n;i+=2){\n            int prev = (i==0) ? Integer.MIN_VALUE : arr[i-1]; \n            int cur = arr[i];\n            int next = (i == n-1) ? Integer.MIN_VALUE : arr[i+1];\n            \n            if(prev < cur && next < cur)\n                continue;\n        \n            if(prev >= cur){\n                res += prev-cur +1;\n                arr[i-1] = cur-1;\n            } \n            \n            if(next >= cur){\n                res += next-cur +1;\n                arr[i+1] = cur-1;\n            }\n        }\n        return res;\n    }\n        \n    public int movesToMakeZigzag(int[] nums) {\n        return Math.min(calculateCost(nums, 0), calculateCost(nums,1));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int movesToMakeZigzag(vector<int>& nums) {\n        int oddSum = 0, evenSum = 0;\n        int n = nums.size();\n        for(int i=0; i<n; i++){\n            if(i%2 == 0){\n                int left = i==0?INT_MAX:nums[i-1];\n                int right = i==n-1?INT_MAX:nums[i+1];\n                evenSum += max(nums[i]-min(left,right)+1,0);\n            }else{\n                int left = i==0?INT_MAX:nums[i-1];\n                int right = i==n-1?INT_MAX:nums[i+1];\n                oddSum += max(nums[i]-min(left,right)+1,0);\n            }\n        }\n        return min(evenSum,oddSum);\n    }\n};"
    },
    {
        "title": "Binary Tree Maximum Path Sum",
        "algo_input": "A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.\n\nThe path sum of a path is the sum of the node's values in the path.\n\nGiven the root of a binary tree, return the maximum path sum of any non-empty path.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3]\nOutput: 6\nExplanation: The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6.\n\n\nExample 2:\n\nInput: root = [-10,9,20,null,null,15,7]\nOutput: 42\nExplanation: The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 3 * 104].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def maxPathSum(self, root: Optional[TreeNode]) -> int:\n        self.res=root.val\n        def solving(root):\n            if not root:\n                return 0\n            current=root.val\n            sleft,sright=float('-inf'),float('-inf')\n            if root.left:\n                sleft=solving(root.left)\n                if(sleft>=0):\n                    current+=sleft\n            if root.right:\n                sright=solving(root.right)\n                if(sright>=0):\n                    current+=sright\n            if(current>self.res):\n                self.res=current\n            return max(root.val, root.val+sleft, root.val+sright)\n        solving(root)\n        return self.res",
        "solution_js": "var maxPathSum = function(root) {\n    let res = -Infinity;\n    function solve(root){\n        if(!root){\n            return 0;\n        }\n        \n        let left = solve(root.left);\n        let right = solve(root.right);\n        //ignore the values with negative sum\n        let leftVal = Math.max(left, 0);\n        let rightVal = Math.max(right,0);\n        \n        let localMax = leftVal + rightVal + root.val;\n        res = Math.max(localMax,res);\n        return Math.max(leftVal, rightVal) + root.val;\n        \n    }\n    solve(root);\n    return res;\n    \n};",
        "solution_java": "class Solution {\n\n    int[] ans = new int[1];\n    public int maxPathSum(TreeNode root) {\n        ans[0]=root.val; //Handle edge case\n        dfs(root);\n        return ans[0];\n    }\n\n    public int dfs(TreeNode root){\n\n        if(root==null)\n            return 0;\n\n        int left=Math.max(0,dfs(root.left)); //Check on the left subtree and if returned negative take 0\n        int right=Math.max(0,dfs(root.right)); //Check on the right subtree and if returned negative take 0\n\n        int maxInTheNode=root.val+left+right; //Calculating the max while including the root its left and right child.\n        ans[0]=Math.max(ans[0],maxInTheNode); //Keeping max globally\n\n        return root.val+Math.max(left,right); //Since only one split is allowed returning the one split that returns max value\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int rec(TreeNode* root,int& res ){\n        if(root==nullptr) return 0;\n        // maximum value from left\n        int l = rec(root->left,res);\n        //maximum value from right\n        int r = rec(root->right,res);\n\n        //check if path can go through this node ,if yes upadte the result value\n        res = max(res,root->val+l+r);\n\n        // return the maximum non-negative path value\n        return max({l+root->val,r+root->val,0});\n    }\n    int maxPathSum(TreeNode* root) {\n        int res = INT_MIN;\n        int x = rec(root,res);\n        return res;\n    }\n};"
    },
    {
        "title": "Max Chunks To Make Sorted II",
        "algo_input": "You are given an integer array arr.\n\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\n\nReturn the largest number of chunks we can make to sort the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n\n\nExample 2:\n\nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 2000\n\t0 &lt;= arr[i] &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def maxChunksToSorted(self, arr: List[int]) -> int:\n        sortedArr = sorted(arr)\n\n        posMap = defaultdict(list)\n        for i in range(len(sortedArr)):\n            posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position\n\n        idx = len(arr) - 1\n        cnt = 0\n        for i in range(len(arr) - 1, -1, -1):\n            idx = min(idx, posMap[arr[i]][-1]) # the smallest position need to move arr[i] to correct position\n            posMap[arr[i]].pop()\n            if i == idx:\n                cnt += 1\n                idx -= 1\n        return cnt",
        "solution_js": "var maxChunksToSorted = function(arr) {\n    var rmin = new Array(arr.length).fill(0);\n    rmin[arr.length] = Number.MAX_SAFE_INTEGER;\n    \n    for(var i=arr.length-1; i>=0; i--) {\n        rmin[i] = Math.min(arr[i], rmin[i+1]);\n    }\n    \n    var lmax = Number.MIN_SAFE_INTEGER;\n    var count = 0;\n    \n    for(var i=0; i<arr.length; i++) {\n        lmax = Math.max(arr[i], lmax);\n        \n        if(lmax <= rmin[i+1]) {\n            count++;\n        }\n    }\n    \n    return count;\n};``",
        "solution_java": "/*\n\n1. Generate Right min\n2. Generate Left Max\n3. Count chunks\n\nPos -->. 0 1 2 3 4 5 6 7\n\nInput --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70\n             <------------> <--> <-------> <------->\nLeft Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75\n\nRight Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max\n\n1. At pos 2 , left_max 30 is smaller than right_min 40 at pos 3\n2. That means , all the elements in the right side of 30 are bigger than all the elements of left side of 30 , including 30\n3. Hence we can break it at pos 2 into a chunk and sort this whole sub-array( 0 - 2 )\n\n*/\n\nclass Solution {\n\n    public int maxChunksToSorted(int[] arr) {\n\n        // 1. Generate Right min\n\n        int[] min_from_right = new int[arr.length+1] ;\n        min_from_right[arr.length] = Integer.MAX_VALUE ;\n\n        for(int i=arr.length-1 ; i>=0 ; i--){\n            min_from_right[i] = Math.min(arr[i] , min_from_right[i+1]);\n        }\n\n        // 2. Generate Left Max and Count chunks\n        int chunk_count = 0 ;\n        int max_cur = Integer.MIN_VALUE ;\n\n        for(int i=0 ; i<arr.length ; i++){\n            max_cur = Math.max(max_cur , arr[i]);\n            if(max_cur <= min_from_right[i+1]){\n                chunk_count++ ;\n            }\n        }\n\n        return chunk_count ;\n    }\n}",
        "solution_c": "class BIT {\n public:\n  BIT(int capacity) : nodes(capacity + 1, 0) {}\n  BIT(const vector<int>& nums) : nodes(nums.size() + 1, 0) {\n    for (int i = 0; i < nums.size(); ++i) {\n      update(i + 1, nums[i]);\n    }\n  }\n\n  void update(int idx, int val) {\n    for (int i = idx; i < nodes.size(); i += i & -i) {\n      nodes[i] += val;\n    }\n  }\n\n  int query(int idx) {\n    int ans = 0;\n    for (int i = idx; i > 0; i -= i & -i) {\n      ans += nodes[i];\n    }\n    return ans;\n  }\n\n private:\n  vector<int> nodes;\n};\n\nclass Solution {\n public:\n  int maxChunksToSorted(vector<int>& arr) {\n    int n = arr.size();\n    BIT bit(n);\n    unordered_map<int, int> h;\n    vector<int> sorted = arr;\n    sort(sorted.begin(), sorted.end());\n    for (int i = 0; i < n; ++i) {\n      if (i == 0 || sorted[i - 1] != sorted[i]) h[sorted[i]] = i + 1;\n    }\n\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n      bit.update(h[arr[i]], 1);\n      ++h[arr[i]];\n      if (bit.query(i + 1) == i + 1) ans += 1;\n    }\n    return ans;\n  }\n};"
    },
    {
        "title": "Largest Divisible Subset",
        "algo_input": "Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:\n\n\n\tanswer[i] % answer[j] == 0, or\n\tanswer[j] % answer[i] == 0\n\n\nIf there are multiple solutions, return any of them.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: [1,2]\nExplanation: [1,3] is also accepted.\n\n\nExample 2:\n\nInput: nums = [1,2,4,8]\nOutput: [1,2,4,8]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 2 * 109\n\tAll the integers in nums are unique.\n\n",
        "solution_py": "class Solution:\n    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n        nums.sort()\n        n = len(nums)\n        dp = [1 for i in range(n)]\n        hashh = [i for i in range(n)]\n        ans_ind = 0\n        \n        for i in range(1, n):\n            for j in range(0,i):\n                if nums[i]%nums[j] == 0 and dp[j]+1 > dp[i]:            \n                    dp[i] = dp[j]+1\n                    hashh[i] = j\n                    \n                    # print(dp)\n                    # print(hashh)\n        out = []\n        maxi = dp[0]\n        \n        for i in range(len(nums)):\n            if dp[i] > maxi:\n                ans_ind = i\n                maxi = dp[i]\n        \n        while(hashh[ans_ind]!=ans_ind):\n            out.append(nums[ans_ind])\n            ans_ind = hashh[ans_ind]\n        out.append(nums[ans_ind])\n        return(out)\n        \n        \n        ",
        "solution_js": "/** https://leetcode.com/problems/largest-divisible-subset/\n * @param {number[]} nums\n * @return {number[]}\n */\nvar largestDivisibleSubset = function(nums) {\n  // Memo\n  this.memo = new Map();\n  \n  // Sort the array so we can do dynamic programming from last number\n  // We want to start from last number because it will be the largest number, the largest number will yield the largest subset because it can be divided many times\n  nums.sort((a, b) => a - b);\n  \n  let out = [];\n  \n  // Perform dynamic programming on every numbers start from the last number\n  for (let i = nums.length - 1; i >= 0; i--) {\n    let curr = dp(nums, i);\n    \n    // Update the subset output if the current subset is larger\n    if (curr.length > out.length) {\n      out = curr;\n    }\n  }\n  \n  return out;\n};\n\nvar dp = function(nums, currIdx) {\n  // Return from memo\n  if (this.memo.has(currIdx) === true) {\n    return this.memo.get(currIdx);\n  }\n  \n  let currSubset = [];\n  \n  // Look up all numbers before `currIdx`\n  for (let i = currIdx - 1; i >= 0; i--) {\n    // Check if the number at `currIdx` can be divided by number at `i`\n    if (nums[currIdx] % nums[i] === 0) {\n      // If they can be divided, perform dynamic programming on `i` to get the subset at `i`\n      let prevSubset = dp(nums, i);\n      \n      // If the subset at `i` is longer than current subset, update current subset\n      if (prevSubset.length > currSubset.length) {\n        currSubset = prevSubset;\n      }\n    }\n  }\n  \n  // Create the output which include number at `currIdx`\n  let out = [...currSubset, nums[currIdx]];\n  \n  // Set memo\n  this.memo.set(currIdx, out);\n  \n  return out;\n};",
        "solution_java": "class Solution {\n    public List<Integer> largestDivisibleSubset(int[] nums) {\n        Arrays.sort(nums);\n        int N = nums.length;\n        List<Integer> ans =new ArrayList<Integer>();\n        int []dp =new int[N];\n        Arrays.fill(dp,1);\n        int []hash =new int[N];\n        for(int i=0;i<N;i++){\n            hash[i]=i;\n        }\n        int lastindex=0;\n        int maxi =1;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<i;j++){\n                if(nums[i]%nums[j] == 0 && dp[j]+1 >dp[i]){\n                    dp[i] = dp[j]+1;\n                    hash[i] = j;\n                }\n                if(dp[i] > maxi){\n                    maxi = dp[i];\n                    lastindex = i;\n                }\n            }\n        }//for ends\n        ans.add(nums[lastindex]);\n        while(hash[lastindex] != lastindex){\n            lastindex = hash[lastindex];\n            ans.add(nums[lastindex]);\n        }\n        return ans;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> largestDivisibleSubset(vector<int>& nums) {\n        \n        int n = nums.size();\n        sort(nums.begin(), nums.end());\n        \n        vector<int> ans;        \n        for(int i = 0; i < n; i++)\n        {                \n            vector<int> tmp;\n            tmp.push_back(nums[i]);\n            \n            // Checking the prev one\n            int j = i - 1;\n            while(j >= 0)\n            {\n                if(tmp.back() % nums[j] == 0)\n                    tmp.push_back(nums[j]);\n                    \n                j--;\n            }\n            \n            // Reversing the order to make it in increasing order\n            reverse(tmp.begin(), tmp.end());\n            \n            // Checking the forward one\n            j = i + 1;\n            while(j < n)\n            {\n                if(nums[j] % tmp.back() == 0)\n                    tmp.push_back(nums[j]);\n                \n                j++;\n            }\n            \n            // updating the ans\n            if(ans.size() < tmp.size())\n                ans = tmp;\n        }\n        \n        return ans;        \n    }\n};"
    },
    {
        "title": "House Robber II",
        "algo_input": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.\n\n\nExample 2:\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def rob(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        if len(nums) == 1:\n            return nums[0]\n        def helper(nums):\n            one, two = 0, 0\n            for i in nums:\n                temp = max(i + one, two)\n                one = two\n                two = temp\n            return two\n        \n        return max(helper(nums[:-1]), helper(nums[1:]))",
        "solution_js": "var rob = function(nums) {\n\n    let dp = []\n    dp[0] = [0,0]\n    dp[1] = [nums[0],0]\n\n    for(let i=2; i<=nums.length;i++){\n        let val = nums[i-1]\n\n        let rob = dp[i-2][0] + val\n        let dont = dp[i-1][0]\n        let noFirst = dp[i-2][1] + val\n\n        let best = (rob>=dont)?rob:dont\n\n        if(dp[i-1][1]>noFirst) noFirst=dp[i-1][1]\n\n        if(i!=nums.length){\n            dp[i] = [best,noFirst]\n        }else{\n            dp[i] = [dont,noFirst]\n        }\n\n    }\n    return (dp[nums.length][0]>=dp[nums.length][1]) ? dp[nums.length][0]:dp[nums.length][1]\n\n};",
        "solution_java": "class Solution {\n    public int rob(int[] nums) {\n        if(nums.length==1){\n            return nums[0];\n        }\n        int[] t = new int[nums.length];\n        for(int i = 0 ; i < t.length;i++){\n            t[i] = -1;\n        }\n        int[] k = new int[nums.length];\n        for(int i = 0 ; i < k.length;i++){\n            k[i] = -1;\n        }\n        return Math.max(helper(nums,0,0,t),helper(nums,1,1,k));\n    }\n    static int helper(int[] nums, int i,int start , int[] t){\n        if(start==0 && i==nums.length-2){\n            return nums[i];\n        }\n        if(start==1 && i==nums.length-1){\n            return nums[i];\n        }\n        if(start==0 && i>=nums.length-1){\n            return 0;\n        }\n        if(start==1 && i>=nums.length){\n            return 0;\n        }\n        if(t[i] != -1){\n            return t[i];\n        }\n        int pick = nums[i]+helper(nums,i+2,start,t);\n        int notpick = helper(nums,i+1,start,t);\n        t[i] = Math.max(pick,notpick);\n        return t[i];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int rob(vector<int>& nums) \n    {\n        int n = nums.size();  \n        if(n == 1)\n        {\n            return nums[0];\n        }\n        //dp[n][2][1]\n        vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(2, vector<int>(2, -1)));\n        \n        int maxm = 0;\n        for(int i = 0; i < n; i++)\n        {\n            for(int j = 0; j < 2; j++)\n            {\n                for(int k = 0; k < 2; k++)\n                {\n                    maxm = max(maxm, dp_fun(dp, i, j, k, nums));\n                }\n            }\n        }\n        \n        return maxm;\n        \n    }\n    \n    int dp_fun(vector<vector<vector<int>>> &dp, int ind, int num, int last, vector<int> &ar)\n    {\n        int n = ar.size();\n        if(dp[ind][num][last] == -1)\n        {\n            if(ind == 0)\n            {\n                if(last == 1)\n                {\n                    dp[ind][num][last] = 0;\n                }\n                else \n                {\n                    if(num == 1)\n                    {\n                        dp[ind][num][last] = ar[ind];\n                    }\n                    else \n                    {\n                        dp[ind][num][last] = 0;\n                    }\n                }\n            }\n            else if (ind == n-1)\n            {\n                if(num == 0)\n                {\n                    dp[ind][num][last] = 0;\n                }\n                else \n                {\n                    if(last == 0)\n                    {\n                        dp[ind][num][last] = dp_fun(dp, ind-1, 1, 0, ar);    \n                    }\n                    else \n                    {\n                        dp[ind][num][last] = ar[ind] + dp_fun(dp, ind-1, 0, 1, ar);\n                    }\n                }\n            }\n            else \n            {\n                if(num == 1)\n                {\n                    dp[ind][num][last] = max(ar[ind] + dp_fun(dp, ind-1, 0, last, ar), dp_fun(dp, ind-1, 1, last, ar));\n                }\n                else \n                {\n                    dp[ind][num][last] = dp_fun(dp, ind-1, 1, last, ar);\n                }\n            }\n        }\n        return dp[ind][num][last];\n    }\n};"
    },
    {
        "title": "Largest Triangle Area",
        "algo_input": "Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput: 2.00000\nExplanation: The five points are shown in the above figure. The red triangle is the largest.\n\n\nExample 2:\n\nInput: points = [[1,0],[0,0],[0,1]]\nOutput: 0.50000\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= points.length &lt;= 50\n\t-50 &lt;= xi, yi &lt;= 50\n\tAll the given points are unique.\n\n",
        "solution_py": "from itertools import combinations\nclass Solution:\n    def largestTriangleArea(self, points: List[List[int]]) -> float:\n        maxA = 0\n        for p1, p2, p3 in combinations(points, 3):\n            x1, y1 = p1\n            x2, y2 = p2\n            x3, y3 = p3\n            A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y1 - y2))\n            if A > maxA: maxA = A\n        return maxA",
        "solution_js": "var largestTriangleArea = function(points) {\n    const n = points.length;\n    let maxArea = 0;\n    \n    for (let i = 0; i < n; i++) {\n        for (let j = i + 1; j < n; j++) {\n            for (k = j + 1; k < n; k++) {\n                const area = calcArea(points[i], points[j], points[k]);\n                maxArea = Math.max(maxArea, area);\n            }\n        }\n    }\n\n    return maxArea;\n};\n\n\nfunction calcArea(coordA, coordB, coordC){\n    const [xCoordA, yCoordA] = coordA;\n    const [xCoordB, yCoordB] = coordB;\n    const [xCoordC, yCoordC] = coordC;\n    \n    const sideA = xCoordA * (yCoordB - yCoordC);\n    const sideB = xCoordB * (yCoordC - yCoordA);\n    const sideC = xCoordC * (yCoordA - yCoordB);\n    \n    return Math.abs((sideA + sideB + sideC) / 2);\n}",
        "solution_java": "class Solution {\n    public double largestTriangleArea(int[][] points) {\n        double ans = 0;\n        int n = points.length;\n        for(int i=0;i<n;i++){\n            for(int j=i+1;j<n;j++){\n                for(int k=j+1;k<n;k++){\n                    ans = Math.max(ans,0.5*Math.abs(points[i][0]*(points[j][1] - points[k][1]) + points[j][0]*( points[k][1] - points[i][1]) + points[k][0]*(points[i][1] - points[j][1])));\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double largestTriangleArea(vector<vector<int>>& points) {\n        double ans = 0.00000;\n        for(int i = 0; i<points.size(); ++i)\n            for(int j = 0; j<points.size(); ++j)\n                if(i!=j)\n                    for(int k = 0; k<points.size(); ++k)\n                        if(k!=i and k!=j)\n                        {\n                            //For triangle formed by 3 points a,b and c: the area will be = 1/2 * [(xa*yb + xb*yc + xc*ya) - (ya*xb + yb*xc + yc*xa)]\n                            ans = max(ans, 0.50000 * (points[i][0]*points[j][1] + points[j][0]*points[k][1] + points[k][0]*points[i][1] - points[i][1]*points[j][0] - points[j][1]*points[k][0] - points[k][1]*points[i][0]));\n                        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Solve the Equation",
        "algo_input": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation.\n\nIf there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.\n\n&nbsp;\nExample 1:\n\nInput: equation = \"x+5-3+x=6+x-2\"\nOutput: \"x=2\"\n\n\nExample 2:\n\nInput: equation = \"x=x\"\nOutput: \"Infinite solutions\"\n\n\nExample 3:\n\nInput: equation = \"2x=x\"\nOutput: \"x=0\"\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= equation.length &lt;= 1000\n\tequation has exactly one '='.\n\tequation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.\n\n",
        "solution_py": "    def solveEquation(self, equation: str) -> str:\n    \"\"\" O(N)TS \"\"\"\n    x, y, p = 0, 0, 1\n    for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n        g = i.group()\n        if g == '=':\n            p = -1\n        elif g[-1] == 'x':\n            x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n        else:\n            y += -p * int(g)\n\n    if x == 0 == y:\n        return 'Infinite solutions'\n    elif x == 0:\n        return \"No solution\"\n    return f'x={y // x}'",
        "solution_js": "    def solveEquation(self, equation: str) -> str:\n    \"\"\" O(N)TS \"\"\"\n    x, y, p = 0, 0, 1\n    for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n        g = i.group()\n        if g == '=':\n            p = -1\n        elif g[-1] == 'x':\n            x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n        else:\n            y += -p * int(g)\n\n    if x == 0 == y:\n        return 'Infinite solutions'\n    elif x == 0:\n        return \"No solution\"\n    return f'x={y // x}'",
        "solution_java": "class Solution {\n    public int[] simplifyEqn(String eqn){\n        int prevSign = 1;\n        int sumX = 0;\n        int sumNums = 0;\n        for(int i=0;i<eqn.length();){\n            int coEff = 0;\n            int j = i;\n            while(j<eqn.length() && Character.isDigit(eqn.charAt(j))){\n                coEff = coEff*10 + (eqn.charAt(j)-'0');\n                j++;\n            }\n            if(j<eqn.length() && eqn.charAt(j)=='x'){\n                if(i==j)\n                    coEff = 1;\n                sumX += prevSign*coEff;\n                j++;\n            }\n            else{\n                sumNums += prevSign*coEff; \n            }\n            if(j<eqn.length() && eqn.charAt(j)=='+')\n                prevSign = 1;\n            else if(j<eqn.length() && eqn.charAt(j)=='-')\n                prevSign = -1;\n            i=++j;\n        }\n        return new int[] {sumX, sumNums};\n    }\n    public String solveEquation(String equation) {\n        String[] leftNRight = equation.split(\"=\");\n        String left = leftNRight[0], right = leftNRight[1];\n        int[] leftEqn = simplifyEqn(left);\n        int[] rightEqn = simplifyEqn(right);\n        int x = leftEqn[0]-rightEqn[0];\n        int num = rightEqn[1]-leftEqn[1];\n        if(x==0)\n            if(num==0)\n                return \"Infinite solutions\";\n            else\n                return \"No solution\";\n        return \"x=\"+num/x;\n    }\n}",
        "solution_c": "    def solveEquation(self, equation: str) -> str:\n    \"\"\" O(N)TS \"\"\"\n    x, y, p = 0, 0, 1\n    for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n        g = i.group()\n        if g == '=':\n            p = -1\n        elif g[-1] == 'x':\n            x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n        else:\n            y += -p * int(g)\n\n    if x == 0 == y:\n        return 'Infinite solutions'\n    elif x == 0:\n        return \"No solution\"\n    return f'x={y // x}'"
    },
    {
        "title": "Random Point in Non-overlapping Rectangles",
        "algo_input": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.\n\nAny integer point inside the space covered by one of the given rectangles should be equally likely to be returned.\n\nNote that an integer point is a point that has integer coordinates.\n\nImplement the Solution class:\n\n\n\tSolution(int[][] rects) Initializes the object with the given rectangles rects.\n\tint[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\nOutput\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\nExplanation\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= rects.length &lt;= 100\n\trects[i].length == 4\n\t-109 &lt;= ai &lt; xi &lt;= 109\n\t-109 &lt;= bi &lt; yi &lt;= 109\n\txi - ai &lt;= 2000\n\tyi - bi &lt;= 2000\n\tAll the rectangles do not overlap.\n\tAt most 104 calls will be made to pick.\n\n",
        "solution_py": "class Solution:\n    \"\"\"\n    1 <= rects.length <= 100\n    rects[i].length == 4\n    -10^9 <= ai < xi <= 10^9\n    -10^9 <= bi < yi <= 10^9\n    xi - ai <= 2000\n    yi - bi <= 2000\n    All the rectangles do not overlap.\n    At most 10^4 calls will be made to pick.\n    \"\"\"\n\n    def __init__(self, rects: List[List[int]]):\n        self.rects = rects\n        self.n_range = list(range(len(self.rects)))\n        self.weights = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]\n\n    def pick(self) -> List[int]:\n        rect = self.rects[choices(self.n_range, self.weights, k=1)[0]]\n        return [randint(rect[0], rect[2]), randint(rect[1], rect[3])]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(rects)\n# param_1 = obj.pick()",
        "solution_js": "/**\n /**\n * @param {number[][]} rects\n */\nvar Solution = function(rects) {\n    this.rects = rects;\n    this.map = {};\n    this.sum = 0;\n    // we put in the map the number of points that belong to each rect\n    for(let i in rects) {\n        const rect = rects[i];\n        // the number of points can be picked in this rectangle\n        this.sum += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1);\n        this.map[this.sum] = i;\n    }\n    this.keys = Object.keys(this.map);\n};\n\n/**\n * @return {number[]}\n */\nSolution.prototype.pick = function() {\n    // random point pick between [1, this.sum]\n    const randomPointPick = Math.floor(Math.random() * this.sum) + 1;\n    \n    // we look for the randomPointPick in the keys of the map\n    let pointInMap;\n    // the keys exists in map\n    if(this.map[randomPointPick]) pointInMap = randomPointPick;\n    // the key is the first in the map (we do this check before doing binary search because its out of boundery)\n    else if(randomPointPick < this.keys[0]) pointInMap = this.keys[0];\n    let high = this.keys.length;\n    let low = 1;\n    // binary search to find the closest key that bigger than randomPointPick\n    while(low <= high && !pointInMap) {\n        const mid = Math.floor((low + (high-low)/2));\n        if(randomPointPick > this.keys[mid-1] && randomPointPick < this.keys[mid]) {\n            pointInMap = this.keys[mid];\n            break;\n        } else if (randomPointPick > this.keys[mid]){\n            low = mid+1;\n        } else {\n            high = mid-1;\n        }\n    }\n    \n    // we have the point, now we can get which rect belong to that point\n    const pointInRects = this.map[pointInMap];\n    const chosen = this.rects[pointInRects];\n    const rightX = chosen[2];\n    const leftX = chosen[0];\n    const topY = chosen[3];\n    const bottomY = chosen[1];\n    const pickX = Math.floor(Math.random() * (rightX-leftX+1)) + leftX;\n    const pickY = Math.floor(Math.random() * (topY-bottomY+1)) + bottomY;\n    return [pickX, pickY]\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(rects)\n * var param_1 = obj.pick()\n */",
        "solution_java": "class Solution {\n    \n    int[][] rects;\n    TreeMap<Integer, Integer> weightedRectIndex = new TreeMap<>();\n    int nPoints = 0;\n    \n    Random rng = new Random();\n\n    public Solution(int[][] rects) {\n        this.rects = rects;\n        int index = 0;\n        for (int[] rect : rects) {\n\t\t    // inserts cumulative weight key pointing to rectangle index\n            weightedRectIndex.put(nPoints, index++);\n            nPoints += width(rect) * height(rect);\n        }\n    }\n    \n    public int[] pick() {\n\t    // generates random point within total weight\n        int point = rng.nextInt(nPoints);\n\t\t// finds appropriate rectangle\n        var entry = weightedRectIndex.floorEntry(point);\n\t\t// find point within the current rectangle\n        int rectPoint = point - entry.getKey();\n        int[] rect = rects[entry.getValue()];\n        return new int[]{\n            rect[0] + rectPoint % width(rect), \n            rect[1] + rectPoint / width(rect)};\n    }\n    \n    private int width(int[] rect) {\n        return rect[2] - rect[0] + 1;\n    }\n    \n    private int height(int[] rect) {\n        return rect[3] - rect[1] + 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> prefix_sum;\n    vector<vector<int>> rects_vec;\n    int total = 0;\n    \n    Solution(vector<vector<int>>& rects) {\n        int cur = 0;\n        for (int i = 0; i < rects.size(); ++i) {\n            cur += (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1);\n            prefix_sum.push_back(cur);\n        }\n        rects_vec = rects;\n        total = cur;\n    }\n    \n    vector<int> pick() {\n        int l = 0, r = prefix_sum.size() - 1, mid = 0;\n        int rand_num = rand();\n        int target = (rand_num % total) + 1;\n\t\t\n        while (l <= r) {\n            mid = l + (r - l) / 2;\n            if (prefix_sum[mid] < target) l = mid + 1;\n            else r = mid - 1;\n        }\n \n        return {rand_num % (rects_vec[l][2] - rects_vec[l][0] + 1) + rects_vec[l][0],\n                rand_num % (rects_vec[l][3] - rects_vec[l][1] + 1) + rects_vec[l][1]};\n    }\n};"
    },
    {
        "title": "Shortest Path in Binary Matrix",
        "algo_input": "Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.\n\nA clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:\n\n\n\tAll the visited cells of the path are 0.\n\tAll the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).\n\n\nThe length of a clear path is the number of visited cells of this path.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,1],[1,0]]\nOutput: 2\n\n\nExample 2:\n\nInput: grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput: 4\n\n\nExample 3:\n\nInput: grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput: -1\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 &lt;= n &lt;= 100\n\tgrid[i][j] is 0 or 1\n\n",
        "solution_py": "'''\nfrom collections import deque\nclass Solution:\n\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\t\tL=len(grid)\n\t\tdef generate_next_state(i,j):\n\t\t\treturn [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]\n\t\tdef valid_state(states):\n\t\t\tres=[]\n\t\t\tfor (i,j) in states:\n\t\t\t\tif i>L-1:continue\n\t\t\t\tif i<0:continue\n\t\t\t\tif j<0:continue\n\t\t\t\tif j>L-1:continue\n\t\t\t\tif grid[i][j]==0:\n\t\t\t\t\tres.append((i,j))\n\t\t\treturn res\n\t\tqueue=deque([(0,0)])\n\t\tres=1\n\t\twhile queue:\n\t\t\tfor _ in range(len(queue)):\n\t\t\t\ti,j=queue.popleft()\n\t\t\t\tval=grid[i][j]\n\t\t\t\tgrid[i][j]=1\n\t\t\t\tif not val:\n\t\t\t\t\tif i==L-1 and j==L-1:\n\t\t\t\t\t\treturn res\n\n\t\t\t\t\tnext_state=valid_state(generate_next_state(i,j))\n\t\t\t\t\tfor (ki,kj) in next_state:\n\t\t\t\t\t\tqueue.append((ki,kj))\n\t\t\tres+=1\n\t\treturn -1\n                \n        \n        \n    \n'''",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar shortestPathBinaryMatrix = function(grid) {\n    const n = grid.length\n    const directions = [\n        [-1, 0], [-1, 1], [0, 1], [1, 1],\n        [1, 0], [1, -1], [0, -1], [-1, -1]\n    ]\n    const visited = []\n    const distance = []\n    const predecessor = []\n    const queue = []\n\n    for (let i = 0; i < n; i++ ) {\n        visited.push(Array.from({length: n}, (v, i) => false))\n        distance.push(Array.from({length: n}, (v, i) => 9999))\n        predecessor.push(Array.from({length: n}, (v, i) => null))\n    }\n\n    const startIndex = [0, 0]\n    if(grid[startIndex[0]][startIndex[1]] !== 0) {\n        return -1\n    }\n\n    queue.push(startIndex)\n    distance[startIndex[0]][startIndex[1]] = 1\n\n    while(queue.length > 0) {\n        const current = queue.shift()\n        visited[current[0]][current[1]] = true\n\n        if (current[0] === n-1 && current[1] === n-1) {\n            break\n        }\n\n        directions.forEach(dir => {\n            const x = current[0] + dir[0]\n            const y = current[1] + dir[1]\n\n            if (x < 0 || y < 0 || x >= n || y >= n) {\n                return\n            }\n\n            if (\n                grid[x][y] === 0 &&\n                visited[x][y] === false &&\n                distance[x][y] > distance[current[0]][current[1]] + 1\n            ) {\n                distance[x][y] = distance[current[0]][current[1]] + 1\n                predecessor[x][y] = current\n                queue.push([x, y])\n            }\n        })\n    }\n\n    console.log(distance)\n    console.log(visited)\n    console.log(predecessor)\n\n    return distance[n-1][n-1] >= 999 ?\n        -1 : distance[n-1][n-1]\n};",
        "solution_java": "class Solution {\n    public int shortestPathBinaryMatrix(int[][] grid) {\n        int m = grid.length, n = grid[0].length;\n        \n        boolean [][] visited = new boolean [m][n];\n        \n        int [] up = {0, 0, 1, -1, 1, 1, -1, -1};\n        int [] down = {-1, 1, 0, 0, -1, 1, -1, 1};\n        \n        /*\n        if top-left is 1 or bottom-right is 1\n        we will return -1\n        */\n        if(grid[0][0] == 1 || grid[m-1][n-1] == 1)\n            return -1;\n        \n        ArrayDeque<int []> q = new ArrayDeque<>();\n        /*\n        we will add top-left to the deque\n        ans steps as 1\n        */\n        q.add(new int[]{0,0,1});        \n        \n        while(q.size() > 0){\n            int [] tmp = q.removeFirst();\n            int x = tmp[0];\n            int y = tmp[1];\n            int steps = tmp[2];\n            visited[x][y] = true;\n            \n            if(x == m-1 && y == n-1)\n                return steps;\n            \n            for(int i = 0; i < 8; i++){\n                int x_new = x + up[i];\n                int y_new = y + down[i];\n                /*\n                we will traverse level wise using bfs\n                and those which can be directly reach via\n                current level will be considered as the same\n                level and we will return the level of \n                bottom-right as result\n                */\n                if(x_new >= 0 && x_new < m && y_new >= 0 && y_new < n){\n                    if(visited[x_new][y_new] == false && grid[x_new][y_new] == 0){\n                        q.add(new int[]{x_new,y_new,steps+1});\n                        visited[x_new][y_new] = true;\n                    }\n                }\n            }\n        }\n        \n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {\n        int m = grid.size(),n = grid[0].size();\n        if(grid[0][0]!=0 || grid[m-1][n-1]!=0) return -1;\n        vector<vector<int>> dist(m,vector<int>(n,INT_MAX));\n        int ans = INT_MAX;\n        queue<pair<int,int>> q;\n        dist[0][0]=1;\n        q.push({0,0});\n        \n        int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};\n        while(!q.empty()){\n            auto curr = q.front();\n            q.pop();\n            for(int i = 0;i<8;i++){\n                int newi = curr.first + dir[i][0];\n                int newj = curr.second + dir[i][1];\n                if(newi>=0 && newi<m && newj>=0 && newj<n && grid[newi][newj]==0){\n                    if(dist[newi][newj]>dist[curr.first][curr.second]+1){\n                        dist[newi][newj] = dist[curr.first][curr.second]+1;\n                        q.push({newi,newj});\n                    }\n                }\n            }\n        }\n            \n        return dist[m-1][n-1]==INT_MAX?-1:dist[m-1][n-1]; \n    }\n};"
    },
    {
        "title": "Spiral Matrix IV",
        "algo_input": "You are given two integers m and n, which represent the dimensions of a matrix.\n\nYou are also given the head of a linked list of integers.\n\nGenerate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.\n\nReturn the generated matrix.\n\n&nbsp;\nExample 1:\n\nInput: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation: The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.\n\n\nExample 2:\n\nInput: m = 1, n = 4, head = [0,1,2]\nOutput: [[0,1,2,-1]]\nExplanation: The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 105\n\t1 &lt;= m * n &lt;= 105\n\tThe number of nodes in the list is in the range [1, m * n].\n\t0 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n        num = m * n\n        res = [[-1 for j in range(n)] for i in range(m)]\n        x, y = 0, 0\n        dx, dy = 1, 0\n        while head:\n            res[y][x] = head.val\n            if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m or res[y+dy][x+dx] != -1:\n                dx, dy = -dy, dx\n            x = x + dx\n            y = y + dy\n            head = head.next\n        return res",
        "solution_js": " var spiralMatrix = function(m, n, head) {\n    var matrix = new Array(m).fill().map(()=> new Array(n).fill(-1))\n    var row=0, col=0;\n    var direction=\"right\";\n    while(head)\n        {\n            matrix[row][col]=head.val;\n            if(direction==\"right\")\n                {\n                    if(col+1 == n || matrix[row][col+1] != -1)\n                        {\n                            direction=\"down\"\n                            row++;\n                        }\n                    else\n                        col++\n                }\n            else if(direction==\"down\")\n                {\n                    if(row+1 == m || matrix[row+1][col] != -1)\n                        {\n                            direction=\"left\"\n                            col--;\n                        }\n                    else\n                        row++\n                }\n            else if(direction==\"left\")\n                {\n                    if(col == 0 || matrix[row][col-1] != -1)\n                        {\n                            direction=\"up\"\n                            row--;\n                        }\n                    else\n                        col--\n                }\n            else if(direction==\"up\")\n                {\n                    if(row == 0 || matrix[row-1][col] != -1)\n                        {\n                            direction=\"right\"\n                            col++;\n                        }\n                    else\n                        row--\n                }\n            head = head.next;\n        }\n    return matrix;\n};",
        "solution_java": "class Solution {\n    public int[][] spiralMatrix(int m, int n, ListNode head) {\n        int[][] ans=new int[m][n];\n        for(int[] arr:ans){\n            Arrays.fill(arr,-1);\n        }\n        \n        int rowBegin=0;\n        int rowEnd=m-1;\n        int columnBegin=0;\n        int columnEnd=n-1;\n        ListNode cur=head;\n        \n      \n        while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){\n            \n            for(int i=columnBegin;i<=columnEnd && cur!=null;i++){\n                if(cur!=null){\n                    ans[rowBegin][i]=cur.val;\n                }\n               \n                    cur=cur.next;\n                \n                \n            }\n            rowBegin++;\n            for(int i=rowBegin;i<=rowEnd && cur!=null;i++){\n               if(cur!=null){\n                ans[i][columnEnd]=cur.val;\n               }\n                \n                    cur=cur.next;\n                \n\n            }\n            columnEnd--;\n            if(rowBegin<=rowEnd){\n                for(int i=columnEnd;i>=columnBegin && cur!=null;i--){\n                if(cur!=null){\n                ans[rowEnd][i]=cur.val;\n                }\n                 \n                    cur=cur.next;\n                \n\n            }\n           \n            }\n             rowEnd--;\n            if(columnBegin<=columnEnd){\n                for(int i=rowEnd;i>=rowBegin && cur!=null;i--){\n                  if(cur!=null){\n                ans[i][columnBegin]=cur.val;\n                  }\n                 \n                    cur=cur.next;\n                \n\n            }\n            \n            }\n            columnBegin++;\n           \n        }\n        return ans;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> spiralMatrix(int n, int m, ListNode* head) \n    {\n\t\t// Create a matrix of n x m with values filled with -1.\n        vector<vector<int>> spiral(n, vector<int>(m, -1));\n        int i = 0, j = 0;\n\t\t// Traverse the matrix in spiral form, and update with the values present in the head list.\n\t\t// If head reacher NULL pointer break out from the loop, and return the spiral matrix.\n        while (head != NULL)\n        {\n            if (j < m)\n            {\n                while (head != NULL && j < m && spiral[i][j] == -1)\n                {\n                    spiral[i][j] = head->val;\n                    head = head->next;\n                    j++;\n                }\n                if (head == NULL)\n                    break;\n                i++;\n                j--;\n            }\n            if (i < n)\n            {\n                while (head != NULL && i < n && spiral[i][j] == -1)\n                {\n                    spiral[i][j] = head->val;\n                    head = head->next;\n                    i++;\n                }\n                i--;\n                j--;\n            }\n            if (j >= 0)\n            {\n                while (head != NULL && j >= 0 && spiral[i][j] == -1)\n                {\n                    spiral[i][j] = head->val;\n                    head = head->next;\n                    j--;\n                }\n                j++;\n                i--;\n            }\n            if (i >= 0)\n            {\n                while (head != NULL && i >= 0 && spiral[i][j] == -1)\n                {\n                    spiral[i][j] = head->val;\n                    head = head->next;\n                    i--;\n                }\n                i++;\n                j++;\n            }\n            n--;\n            m++;\n        }\n\t\t// Rest values are itself -1.\n        return spiral;\n    }\n};"
    },
    {
        "title": "Reverse Words in a String",
        "algo_input": "Given an input string s, reverse the order of the words.\n\nA word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.\n\nReturn a string of the words in reverse order concatenated by a single space.\n\nNote that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.\n\n&nbsp;\nExample 1:\n\nInput: s = \"the sky is blue\"\nOutput: \"blue is sky the\"\n\n\nExample 2:\n\nInput: s = \"  hello world  \"\nOutput: \"world hello\"\nExplanation: Your reversed string should not contain leading or trailing spaces.\n\n\nExample 3:\n\nInput: s = \"a good   example\"\nOutput: \"example good a\"\nExplanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts contains English letters (upper-case and lower-case), digits, and spaces ' '.\n\tThere is at least one word in s.\n\n\n&nbsp;\nFollow-up:&nbsp;If the string data type is mutable in your language, can&nbsp;you solve it&nbsp;in-place&nbsp;with&nbsp;O(1)&nbsp;extra space?\n",
        "solution_py": "class Solution:\n    def split(self, s: str, delimiter=\" \") -> List[str]:\n        start, end = 0, 0\n\n        res = []\n        for ch in s:\n            if ch == delimiter:\n                if start == end:\n                    start += 1\n                else:\n                    res.append(s[start:end])\n                    start  = end + 1\n            \n            end += 1\n        \n        if start != end:\n            res.append(s[start:end])\n\n        return res\n\n    def reverse_list(self, ll: List[str]) -> List[str]:\n        l, r = 0, len(ll) - 1\n\n        while l < r:\n            ll[l], ll[r] = ll[r], ll[l]\n            l += 1\n            r -= 1\n        \n        return ll\n\n    def reverseWords(self, s: str) -> str:\n\n        # split first\n        splitted_str_list = self.split(s)\n\n        # reverse splitted list\n        reversed_str_list = self.reverse_list(splitted_str_list)\n\n        # join an return\n        return \" \".join(reversed_str_list)",
        "solution_js": "var reverseWords = function(s) {\n    return s.split(\" \").filter(i => i).reverse().join(\" \");\n};",
        "solution_java": "class Solution {\n    public String reverseWords(String s) {\n        String[] arr = s.replaceAll(\"\\\\s{2,}\", \" \").split(\" \"); \n        // splitting based on while spaces by replaceing spaces by single gap \n        int n = arr.length;\n        String temp = \"\";\n        for(int i =0;i<n/2;i++){\n            temp = arr[i];\n            arr[i] = arr[n-i-1];\n            arr[n-i-1]=temp;\n        }\n        String result =\"\";\n        for(int i =0;i<n-1;i++){\n            result+=arr[i]+\" \";\n        }\n        result+=arr[n-1];\n        return result.trim();\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reverseWords(string s) {\n        int i=0;\n        string res = \"\";\n        while(i<s.length())\n        {\n            while(i<s.length() && s[i]==' ')\n                i++;\n\n            if(i>=s.length())\n                break;\n\n            int j=i+1;\n\n            while(j<s.length() && s[j]!=' ')\n                j++;\n\n            string tmp = s.substr(i,j-i);\n            if(res.length()==0)\n            {\n                res = tmp;\n            }\n            else\n            {\n                res = tmp + \" \" + res;\n            }\n            i=j+1;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Maximum Number of Removable Characters",
        "algo_input": "You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).\n\nYou want to choose an integer k (0 &lt;= k &lt;= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 &lt;= i &lt; k, then remove all marked characters and check if p is still a subsequence.\n\nReturn the maximum k you can choose such that p is still a subsequence of s after the removals.\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&nbsp;\nExample 1:\n\nInput: s = \"abcacb\", p = \"ab\", removable = [3,1,0]\nOutput: 2\nExplanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.\n\n\nExample 2:\n\nInput: s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\nOutput: 1\nExplanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".\n\n\nExample 3:\n\nInput: s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\nOutput: 0\nExplanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= p.length &lt;= s.length &lt;= 105\n\t0 &lt;= removable.length &lt; s.length\n\t0 &lt;= removable[i] &lt; s.length\n\tp is a subsequence of s.\n\ts and p both consist of lowercase English letters.\n\tThe elements in removable are distinct.\n\n",
        "solution_py": "class Solution:\n    def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n        \n        def check(m):\n            i = j = 0\n            remove = set(removable[:m+1])\n            while i < len(s) and j < len(p):\n                if i in remove:\n                    i += 1\n                    continue\n                if s[i] == p[j]:\n                    i += 1\n                    j += 1\n                else:\n                    i += 1\n            \n            return j == len(p)\n            \n                \n        # search interval is [lo, hi)\n        lo, hi = 0, len(removable)+1\n        \n        while lo < hi:\n            mid = (lo + hi) // 2\n            if check(mid):\n                lo = mid + 1\n            else:\n                hi = mid\n                \n        return lo if lo < len(removable) else lo-1",
        "solution_js": "var maximumRemovals = function(s, p, removable) {\n    let arr = s.split('');\n    \n    const stillFunctions = (k) => {\n        let result = [...arr];\n        for(let i = 0; i < k; i++) {\n            result[removable[i]] = '';\n        }\n\n        const isSubset = () => {\n            let idx = 0;\n            for(let c = 0; c < p.length; c++) {\n                if(idx > result.length) return false;\n                const next = result.indexOf(p[c], idx);\n                if(next === -1) {\n                    return false;\n                }\n                idx = next + 1;\n            }\n            return true;\n        }\n        \n        return isSubset();\n    }\n\n    let left = 0;\n    let right = removable.length;\n    \n    while(left < right) {\n        // Need to round up the midpoint since we are returning operation LENGTH i.e. ops+1\n        const mid = Math.ceil((left+right) / 2);\n        if(!stillFunctions(mid)) {\n            right = mid -1;\n        } else {\n            left = mid;\n        }\n    }\n    return left;\n};",
        "solution_java": "class Solution {\n    public int maximumRemovals(String s, String p, int[] removable) {\n        int left = 0, right = removable.length;\n\n        while (left < right) {\n            int middle = (right + left + 1) / 2;\n            String afterRemoval = remove(s, removable, middle);\n            if (isSubsequence(p, afterRemoval, p.length(), afterRemoval.length()))\n                left = middle;\n            else\n                right = middle - 1;\n        }\n\n        return left;\n    }\n\n    private String remove(String s, int[] removable, int k) {\n        char[] symbols = s.toCharArray();\n        for (int i = 0; i < k; i++) {\n            symbols[removable[i]] = Character.MIN_VALUE;\n        }\n        return String.valueOf(symbols);\n    }\n\n    private boolean isSubsequence(String subSequence, String word, int subSequenceChar, int wordChar) {\n        if (subSequenceChar == 0) return true;\n        if (wordChar == 0) return false;\n\n        if (subSequence.charAt(subSequenceChar - 1) == word.charAt(wordChar - 1))\n            return isSubsequence(subSequence, word, subSequenceChar - 1, wordChar - 1);\n\n        return isSubsequence(subSequence, word, subSequenceChar, wordChar - 1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isSubSequence(string str1, string str2){\n        int j = 0,m=str1.size(),n=str2.size();\n        for (int i = 0; i < n && j < m; i++)\n            if (str1[j] == str2[i])\n                j++;\n        return (j == m);\n    }\n    int maximumRemovals(string s, string p, vector<int>& removable) {\n        string copy=s;\n        int left = 0, right =removable.size();\n        while (left <= right) {\n            int mid = (left+right)/2;\n            for(int i=0;i<mid;i++) copy[removable[i]]='*';\n            if (isSubSequence(p,copy))\n\t\t\t //if p is subsequence of string after mid number of removals then we should look for if it's possible to remove more characters \n                left = mid+1;\n            else {\n\t\t\t//if p is not a subsequence of string it means that we have certainly removed more characters from string \n\t\t\t//so we must decrease our size of removal characters and hence we  add all characters we removed earlier.\n                for(int i=0;i<mid;i++) copy[removable[i]] = s[removable[i]];\n                right = mid-1;\n            }\n        }\n        return right;\n    }\n};"
    },
    {
        "title": "Student Attendance Record II",
        "algo_input": "An attendance record for a student can be represented as a string 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\nAny 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\nGiven an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 8\nExplanation: There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).\n\n\nExample 2:\n\nInput: n = 1\nOutput: 3\n\n\nExample 3:\n\nInput: n = 10101\nOutput: 183236316\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def checkRecord(self, n: int) -> int:\n        if n == 1:\n            return 3\n        if n==2:\n            return 8\n        \"\"\"\n        Keep track of last 2 digits\n        ways to get ll = last combinations ending with p,l (l,l not allowed)\n        ways to get lp = last combinations ending with l,p + p,l\n        and so on\n        \n        finally account for adding A by the usual loop.\n        \"\"\"\n        \n        combos_l_l = 1\n        combos_l_p = 1\n        combos_p_l = 1\n        combos_p_p = 1\n\n        MOD = 1000000007\n        \n        f = [0]*(n+1)\n        f[0] = 1\n        f[1] = 2\n        f[2] = 4\n        for i in range(2, n):\n            combos_l_l_new = combos_p_l\n            combos_l_p_new = combos_l_l + combos_p_l\n            combos_p_l_new = combos_l_p + combos_p_p \n            combos_p_p_new = combos_l_p + combos_p_p\n            \n            combos_l_l, combos_l_p, combos_p_l, combos_p_p = combos_l_l_new%MOD, combos_l_p_new%MOD, combos_p_l_new%MOD, combos_p_p_new  %MOD\n            \n            f[i+1] = (combos_l_l + combos_l_p + combos_p_l + combos_p_p)%MOD\n            \n\n        total = f[-1]\n        # print(f)\n        for i in range(1,n+1):\n            total += (f[i-1]*f[n-i]) \n            \n        return ( total ) % (MOD)\n            ",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar checkRecord = function(n) {\n  /**\n   * P(n) = A(n - 1) + P(n - 1) + L(n - 1), n ≥ 2.\n   * L(n) = A(n - 1) + P(n - 1) + A(n - 2) + P(n - 2), n ≥ 3.\n   * A(n) = A(n - 1) + A(n - 2) + A(n - 3), n ≥ 4.\n   */\n  const m = 1000000007;\n  const P = Array(n);\n  const A = Array(n);\n  const L = Array(n);\n  A[0] = 1;\n  L[0] = 1;\n  P[0] = 1;\n  A[1] = 2;\n  A[2] = 4;\n  L[1] = 3;\n  for (let i = 1; i < n; i++) {\n    P[i] = (A[i - 1] + L[i - 1] + P[i - 1]) % m;\n    if (i >= 3) A[i] = (A[i - 1] + A[i - 2] + A[i - 3]) % m;\n    if (i >= 2) L[i] = (A[i - 1] + P[i - 1] + A[i - 2] + P[i - 2]) % m;\n  }\n  return (P[n - 1] + A[n - 1] + L[n - 1]) % m;\n};",
        "solution_java": "class Solution {\n    int mod=1000000000+7;\n    public int checkRecord(int n) {\n        int[][][] cache=new int[n+1][2][3];\n        for(int i=0; i<=n; i++){\n            for(int j=0; j<2; j++){\n                for(int k=0; k<3; k++)cache[i][j][k]=-1;\n            }\n        }\n        return populate(n, 0, 1, 2, cache);\n    }\n    public int populate(int n, int ptr, int aCount, int lCount, int[][][] cache){\n        if(ptr>=n)return 1;\n        if(cache[ptr][aCount][lCount]!=-1)return cache[ptr][aCount][lCount];\n        long count=0;\n        // Late\n        if(lCount>0){\n            count=populate(n, ptr+1, aCount, lCount-1, cache)%mod;\n        }\n        // Present\n        count=(count+populate(n, ptr+1, aCount, 2, cache))%mod;\n        // Absent\n        if(aCount==1)count=(count+populate(n, ptr+1, aCount-1, 2, cache))%mod;\n        cache[ptr][aCount][lCount]=(int)(count%mod);\n        return cache[ptr][aCount][lCount];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = 1e9+7;\n    int dp[100001][10][10];\n    int recur(int abs,int late,int n){\n        if(abs > 1){\n            return 0;\n        }\n        if(late >= 3){\n            return 0;\n        }\n        if(n == 0){\n            return 1;\n            \n        }\n        if(dp[n][late][abs] != -1) return dp[n][late][abs];\n        \n        int ans = 0;\n        ans = (ans%mod + recur(abs+1,0,n-1)%mod)%mod;\n        \n        ans = (ans%mod + recur(abs,late+1,n-1)%mod)%mod;\n        \n        ans = (ans%mod + recur(abs,0,n-1)%mod)%mod;\n       //This dp is running from n to 0 and is cut off if\n        //absent is greater than 1 or late of consecutive is greater than\n        //equal to 3.\n        //Here in the first recursion i.e line 19 & line 23 late is made 0\n        //to signify that the consecutive lates are stopped.***\n\n        return dp[n][late][abs] = ans;\n    }\n    int checkRecord(int n) {\n        for(int i=0;i<=100000;i++){\n            for(int j=0;j<10;j++){\n                for(int k=0;k<10;k++){\n                    dp[i][j][k] = -1;\n                }\n            }\n        }\n        return recur(0,0,n);\n    }\n};"
    },
    {
        "title": "Design HashSet",
        "algo_input": "Design a HashSet without using any built-in hash table libraries.\n\nImplement MyHashSet class:\n\n\n\tvoid add(key) Inserts the value key into the HashSet.\n\tbool contains(key) Returns whether the value key exists in the HashSet or not.\n\tvoid remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\nOutput\n[null, null, null, true, false, null, true, null, false]\n\nExplanation\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1);      // set = [1]\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2);   // set = [1]\nmyHashSet.contains(2); // return False, (already removed)\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= key &lt;= 106\n\tAt most 104 calls will be made to add, remove, and contains.\n\n",
        "solution_py": "class MyHashSet:\n\n    def __init__(self):\n        self.hash_list = [0]*10000000\n\n    def add(self, key: int) -> None:\n        self.hash_list[key]+=1\n\n    def remove(self, key: int) -> None:\n        self.hash_list[key] = 0\n\n    def contains(self, key: int) -> bool:\n        if self.hash_list[key] > 0:\n            return True\n        return False",
        "solution_js": "var MyHashSet = function() {\n  \n    // Really you should just \n    // Make your own object, but instead\n    // we have attached ourself to the \n    // `this` object which then becomes our hashmap.\n    \n    // What you should instead do is this:\n    // this.hash_map = {}\n    // And then update our following functions\n};\n\nMyHashSet.prototype.add = function(key) {\n    \n    // Constant Time\n    // Linear Space | To the size of the input key\n    // You can access objects using array notation\n\n    this[key] = null;\n};\n\nMyHashSet.prototype.remove = function(key) {\n    \n    // Constant Time\n    // Constant Space\n    // You can access objects using array notation\n    // Here we use the delete keyword.\n\n    delete this[key]\n};\n\nMyHashSet.prototype.contains = function(key) {\n    \n    // Constant Time\n    // Constant Space\n    // This just asks if the property exists\n\n    return this.hasOwnProperty(key)\n};",
        "solution_java": "class MyHashSet {\n\tArrayList<LinkedList<Integer>> list;\n\tint size = 100;\n\n\tpublic MyHashSet() {\n\t\tlist = new ArrayList<>(size);\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tlist.add(new LinkedList<Integer>());\n\t\t}\n\t}\n\n\tpublic int hash(int key) {\n\t\treturn key % list.size();\n\t}\n\n\tpublic int search(int key) {\n\t\tint i = hash(key);\n\n\t\tLinkedList<Integer> temp = list.get(i);\n\t\tint ans = -1;\n\n\t\tfor (int j = 0; j < temp.size(); j++) {\n\t\t\tif (key == temp.get(j)) {\n\t\t\t\treturn j;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\n\tpublic void add(int key) {\n\t\tif (search(key) == -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).add(key);\n\t\t}\n\t}\n\n\tpublic void remove(int key) {\n\t\tif (search(key) != -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).remove(Integer.valueOf(key));\n\t\t}\n\t}\n\n\tpublic boolean contains(int key) {\n\t\treturn search(key) != -1;\n\t}\n}",
        "solution_c": "class MyHashSet {\n    vector<int> v;\npublic:\n    MyHashSet() {\n\n    }\n\n    void add(int key) {\n        auto it = find(v.begin(), v.end(), key);\n        if(it == v.end()){\n            v.push_back(key);\n        }\n\n    }\n\n    void remove(int key) {\n        auto it = find(v.begin(), v.end(), key);\n        if(it != v.end()){\n            v.erase(it);\n        }\n    }\n\n    bool contains(int key) {\n        return find(v.begin(), v.end(), key) != v.end();\n    }\n};"
    },
    {
        "title": "Minimum Sum of Four Digit Number After Splitting Digits",
        "algo_input": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.\n\n\n\tFor example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].\n\n\nReturn the minimum possible sum of new1 and new2.\n\n&nbsp;\nExample 1:\n\nInput: num = 2932\nOutput: 52\nExplanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\n\n\nExample 2:\n\nInput: num = 4009\nOutput: 13\nExplanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n\n\n&nbsp;\nConstraints:\n\n\n\t1000 &lt;= num &lt;= 9999\n\n",
        "solution_py": "class Solution:\n    def minimumSum(self, num: int) -> int:\n        s=list(str(num))\n        s.sort()\n        return int(s[0]+s[2])+int(s[1]+s[3])",
        "solution_js": "var minimumSum = function(num) {\n   let numbers = []\n    for(let i = 0; i<4; i++){\n        numbers.push(~~num % 10)\n        num /= 10\n    }\n    const sorted = numbers.sort((a,b) => b - a)\n    return sorted[0] + sorted[1] + (10 *( sorted[2] + sorted[3]))\n};",
        "solution_java": "class Solution\n{\n    public int minimumSum(int num)\n    {\n        int[] dig = new int[4]; // For each digit\n        int cur = 0;\n        while(num > 0) // Getting each digit\n        {\n            dig[cur++] = num % 10;\n            num /= 10;\n        }\n        Arrays.sort(dig); // Ascending order\n        int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit\n        int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit\n        return num1 + num2;\n    }\n}",
        "solution_c": "class Solution{\npublic:\n    int minimumSum(int num){\n        string s = to_string(num);\n        sort(s.begin(), s.end());\n        int res = (s[0] - '0' + s[1] - '0') * 10 + s[2] - '0' + s[3] - '0';\n        return res;\n    }\n};"
    },
    {
        "title": "Can Make Arithmetic Progression From Sequence",
        "algo_input": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.\n\nGiven an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,5,1]\nOutput: true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.\n\n\nExample 2:\n\nInput: arr = [1,2,4]\nOutput: false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 1000\n\t-106 &lt;= arr[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n        arr.sort()\n        check = arr[0] - arr[1]\n        for i in range(len(arr)-1):\n            if arr[i] - arr[i+1] != check:\n                return False\n        return True",
        "solution_js": "var canMakeArithmeticProgression = function(arr) {\n    arr.sort(function(a,b){return a-b});\n    var dif = arr[1] - arr[0];\n    for(var i=2;i<arr.length;i++){\n        if(arr[i]-arr[i-1] !== dif){\n            return false;\n        }\n    }\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean canMakeArithmeticProgression(int[] arr) {\n        if(arr.length < 1)\n            return false;\n        Arrays.sort(arr);\n        int diff = arr[1]-arr[0];\n        for(int i=1;i<arr.length-1;i++){\n            if(arr[i+1]-arr[i]!=diff){\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canMakeArithmeticProgression(vector<int>& arr) {\n        sort(arr.begin() , arr.end());\n        int diff = arr[1] - arr[0];\n        for(int i=1;i<arr.size();i++){\n            if(diff != arr[i] - arr[i-1]){\n                return false;\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Missing Number",
        "algo_input": "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,0,1]\nOutput: 2\nExplanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.\n\n\nExample 2:\n\nInput: nums = [0,1]\nOutput: 2\nExplanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.\n\n\nExample 3:\n\nInput: nums = [9,6,4,2,3,5,7,0,1]\nOutput: 8\nExplanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= nums[i] &lt;= n\n\tAll the numbers of nums are unique.\n\n\n&nbsp;\nFollow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?\n",
        "solution_py": "class Solution:\n    def missingNumber(self, nums: List[int]) -> int:\n        # T.C = O(n) S.C = O(1)\n        actualsum = 0\n        currentsum = 0\n        i = 1\n        for num in nums:\n            currentsum += num\n            actualsum += i\n            i += 1\n        \n        return actualsum - currentsum",
        "solution_js": "var missingNumber = function(nums) {\n    return ((1 + nums.length)*nums.length/2) - nums.reduce((a,b) => a+b)\n};",
        "solution_java": "// Approach 1: Find diff\n\nclass Solution {\n    public int missingNumber(int[] nums) {\n        int n = nums.length;\n        int expectedSum = (n * (n + 1)) / 2;\n        for (int num : nums)\n            expectedSum -= num;\n        return expectedSum;\n    }\n}\n\n// Approach 2: XOR\nclass Solution {\n    public int missingNumber(int[] nums) {\n        int xor1 = 0;\n        for (int i = 1; i <= nums.length; i++)\n            xor1 = xor1 ^ i;\n\n        int xor2 = 0;\n        for (int num : nums)\n            xor2 = xor2 ^ num;\n        return xor1 ^ xor2;\n    }\n}\n\n// Approach 3: Cyclic sort\nclass Solution {\n    public int missingNumber(int[] nums) {\n        \n        int i = 0;\n        while (i < nums.length) {\n\n            if (nums[i] != i && nums[i] < nums.length)\n                swap(i, nums[i], nums);\n            else\n                i += 1;\n        }\n        \n        for (int j = 0; j < nums.length; j++) {\n            if (nums[j] != j)\n                return j;\n        }\n        return nums.length;\n    }\n    \n    private void swap(int i, int j, int[] nums) {\n        int temp = nums[i];\n        nums[i] = nums[j];\n        nums[j] = temp;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int missingNumber(vector<int>& nums) {\n      int n=nums.size();\n        long sum=n*(n+1)/2;\n        long temp=0;\n        for(int i=0;i<n;i++)\n        {\n            temp+=nums[i];\n\n        }\n        return sum-temp;\n    }\n};"
    },
    {
        "title": "Pacific Atlantic Water Flow",
        "algo_input": "There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.\n\nThe island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).\n\nThe island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.\n\nReturn a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.\n\n&nbsp;\nExample 1:\n\nInput: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\nOutput: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\n\n\nExample 2:\n\nInput: heights = [[2,1],[1,2]]\nOutput: [[0,0],[0,1],[1,0],[1,1]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == heights.length\n\tn == heights[r].length\n\t1 &lt;= m, n &lt;= 200\n\t0 &lt;= heights[r][c] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n        # Purpose: find the cells that allow rain flow into the ocean\n        # Method: DFS\n        # Intuition: start from each border, check cell and neb, if OK, append to res\n            \n        # init: res, vis (pac, atl), ROW, COL\n        res = []\n        pac = set()\n        atl = set()\n        ROW = len(heights)\n        COL = len(heights[0])\n\n        # top and bottom row\n        for col in range(COL):\n            self.dfs(0, col, pac, heights[0][col], heights)\n            self.dfs(ROW-1, col, atl, heights[ROW-1][col], heights)\n\n        # left and right col\n        for row in range(ROW):\n            self.dfs(row, 0, pac, heights[row][0], heights)\n            self.dfs(row, COL-1, atl, heights[row][COL-1], heights)\n\n        # append to res\n        for row in range(ROW):\n            for col in range(COL):\n                if (row, col) in pac and (row, col) in atl:\n                    res.append([row, col])\n\n        # return\n        return res\n\n    \n    def dfs(self, row, col, vis, prev, heights):\n        # hard-code definition\n        try:\n            cur = heights[row][col]\n        except:\n            pass\n\n        # inbound, unvisited, increase from ocean\n        if (0<=row<len(heights) and 0<=col<len(heights[0])) \\\n            and (cur >= prev) \\\n                and ((row, col) not in vis):\n\n            # add to visited \n            vis.add((row, col))\n\n            # check nebs\n            self.dfs(row+1, col, vis, cur, heights)\n            self.dfs(row-1, col, vis, cur, heights)\n            self.dfs(row, col+1, vis, cur, heights)\n            self.dfs(row, col-1, vis, cur, heights)",
        "solution_js": "`/**\n * @param {number[][]} heights\n * @return {number[][]}\n */\nvar pacificAtlantic = function(heights) {\n    let atlantic = new Set();\n    let pacific = new Set();\n    let rows = heights.length;\n    let cols = heights[0].length;\n\n    for (let c = 0; c < cols; c++) {\n        explore(heights, 0, c, pacific, heights[0][c]); // dfs from top row\n        explore(heights, rows - 1, c, atlantic, heights[rows - 1][c]); // dfs from bottom row\n    }\n\n    for (let r = 0; r < rows; r++) {\n        explore(heights, r, 0, pacific, heights[r][0]); // dfs from left most column\n        explore(heights, r, cols - 1, atlantic, heights[r][cols - 1]); // dfs from right most column\n    }\n\n    // check if water can flow to both atlantic and pacific ocean.\n    let res = [];\n    for (let r = 0; r < rows; r++) {\n        for (let c = 0; c < cols; c++) {\n            let pos = r + ',' + c;\n            if (atlantic.has(pos) && pacific.has(pos)) {\n                res.push([r, c]);\n            }\n        }\n    }\n\n    return res;\n};\n\nfunction explore(heights, r, c, visited, prevHeight) {\n    let rowInbound = 0 <= r && r < heights.length;\n    let colInbound = 0 <= c && c < heights[0].length;\n    if (!rowInbound || !colInbound) return;\n\n    // height must be higher than prev height. water can only flow downwards not upwards. duh.\n    // if it's the first value then it's just the same value so it's not less than so it will not return.\n    if (heights[r][c] < prevHeight) return;\n\n    let pos = r + ',' + c;\n    if (visited.has(pos)) return;\n    visited.add(pos)\n\n    explore(heights, r + 1, c, visited, heights[r][c]) // below\n    explore(heights, r - 1, c, visited, heights[r][c]) // above\n    explore(heights, r, c + 1, visited, heights[r][c]) // right\n    explore(heights, r, c - 1, visited, heights[r][c]) // left\n}`",
        "solution_java": "class Solution {\n    public List<List<Integer>> pacificAtlantic(int[][] heights) {\n        if (heights == null) return null;\n        if (heights.length == 0) return null;\n        if (heights[0].length == 0) return null;\n\n        /** */\n        boolean [][] po = new boolean[heights.length][heights[0].length];\n        boolean [][] ao = new boolean[heights.length][heights[0].length];\n\n        for (int i = 0; i < heights[0].length; i ++) {\n            dfs(heights, i, 0, 0, po); // top\n            dfs(heights, i, heights.length - 1, 0, ao); // bottom\n        }\n\n        for (int i = 0; i < heights.length; i ++) {\n            dfs(heights, 0, i, 0, po); // left\n            dfs(heights, heights[0].length - 1, i, 0, ao); // right\n        }\n\n        List<List<Integer>> ans = new ArrayList<>();\n        for (int i = 0; i < heights.length; i ++) {\n            for (int j = 0; j < heights[i].length; j ++) {\n                if (ao[i][j] && po[i][j]) {\n                    ArrayList<Integer> ar = new ArrayList<>();\n                    ar.add(i);\n                    ar.add(j);\n                    ans.add(ar);\n                }\n            }\n        }\n\n        return ans;\n    }\n\n    private void dfs(int[][] heights, int x, int y, int h, boolean[][] v) {\n        if (x < 0 || y < 0 || x >= heights[0].length || y >= heights.length) return;\n        if (v[y][x] || heights[y][x] < h) return;\n        v[y][x] = true;\n        /** left */\n        dfs(heights, x - 1, y, heights[y][x], v);\n\n        /** right */\n        dfs(heights, x + 1, y, heights[y][x], v);\n\n        /** up */\n        dfs(heights, x, y - 1, heights[y][x], v);\n\n        /** down */\n        dfs(heights, x, y + 1, heights[y][x], v);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    void dfs(vector<vector<int>>& heights,vector<vector<bool>>&v,int i,int j)\n    {\n        int m=heights.size();\n        int n=heights[0].size();\n        v[i][j]=true;\n        if(i-1>=0&&v[i-1][j]!=true&&heights[i-1][j]>=heights[i][j])\n        {\n            dfs(heights,v,i-1,j);\n        }\n         if(i+1<m&&v[i+1][j]!=true&&heights[i+1][j]>=heights[i][j])\n        {\n            dfs(heights,v,i+1,j);\n        }\n         if(j-1>=0&&v[i][j-1]!=true&&heights[i][j-1]>=heights[i][j])\n        {\n            dfs(heights,v,i,j-1);\n        }\n         if(j+1<n&&v[i][j+1]!=true&&heights[i][j+1]>=heights[i][j])\n        {\n            dfs(heights,v,i,j+1);\n        }\n    }\n    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n        int m=heights.size();\n        vector<vector<int>>ans;\n        if(m==0)\n        {\n            return ans;\n        }\n        int n=heights[0].size();\n        if(n==0)\n        {\n            return ans;\n        }\n        vector<vector<bool>>pa(m,vector<bool>(n));\n        vector<vector<bool>>at(m,vector<bool>(n));\n        for(int i=0;i<m;i++)\n        {\n            dfs(heights,pa,i,0);\n            dfs(heights,at,i,n-1);\n        }\n        for(int j=0;j<n;j++)\n        {\n             dfs(heights,pa,0,j);\n            dfs(heights,at,m-1,j);\n        }\n        for(int i=0;i<m;i++)\n        {\n            vector<int>p;\n            for(int j=0;j<n;j++)\n            {\n                if(pa[i][j]&&at[i][j])\n                {\n\n                    p.push_back(i);\n                    p.push_back(j);\n                    ans.push_back(p);\n                    p.clear();\n                }\n\n            }\n\n        }\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Check if Number Has Equal Digit Count and Digit Value",
        "algo_input": "You are given a 0-indexed string num of length n consisting of digits.\n\nReturn true if for every index i in the range 0 &lt;= i &lt; n, the digit i occurs num[i] times in num, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: num = \"1210\"\nOutput: true\nExplanation:\nnum[0] = '1'. The digit 0 occurs once in num.\nnum[1] = '2'. The digit 1 occurs twice in num.\nnum[2] = '1'. The digit 2 occurs once in num.\nnum[3] = '0'. The digit 3 occurs zero times in num.\nThe condition holds true for every index in \"1210\", so return true.\n\n\nExample 2:\n\nInput: num = \"030\"\nOutput: false\nExplanation:\nnum[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\nnum[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\nnum[2] = '0'. The digit 2 occurs zero times in num.\nThe indices 0 and 1 both violate the condition, so return false.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == num.length\n\t1 &lt;= n &lt;= 10\n\tnum consists of digits.\n\n",
        "solution_py": "from collections import Counter\n\nclass Solution:\n    def digitCount(self, num: str) -> bool:\n        d = Counter(num)\n        for i in range(len(num)):\n            if int(num[i])!=d.get(str(i), 0):\n                return False\n        return True",
        "solution_js": "var digitCount = function(num) {    \n    const res = [...num].filter((element, index) => {\n        const reg = new RegExp(index, \"g\");\n        const count = (num.match(reg) || []).length;\n        \n        return Number(element) === count\n    })\n    \n    return res.length === num.length    \n};",
        "solution_java": "class Solution {\n    public boolean digitCount(String num) {\n        int[] freqArr = new int[10];  // n = 10 given in constraints;\n        \n        \n        for(char ch : num.toCharArray()){\n            freqArr[ch-'0']++;\n        }\n        \n        for(int i=0;i<num.length();i++){\n            int freq = num.charAt(i)-'0';  //freq of each indexValue;\n            freqArr[i] = freqArr[i] - freq; \n        }\n        for(int i=0;i<10;i++){\n            if(freqArr[i]!=0){\n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool digitCount(string num) {\n        unordered_map<int,int> mpp;\n        int n= num.length();\n        for(auto it:num){\n            int x = it - '0';\n            mpp[x]++; // Store the frequency of the char as a number\n        }\n        for(int i=0;i<n;i++){\n            int x = num[i] - '0'; // get the char as number\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(mpp[i] != x) // f the number is not equal to its frequency we return false\n                return false;\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Reformat The String",
        "algo_input": "You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).\n\nYou have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.\n\nReturn the reformatted string or return an empty string if it is impossible to reformat the string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"a0b1c2\"\nOutput: \"0a1b2c\"\nExplanation: No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.\n\n\nExample 2:\n\nInput: s = \"leetcode\"\nOutput: \"\"\nExplanation: \"leetcode\" has only characters so we cannot separate them by digits.\n\n\nExample 3:\n\nInput: s = \"1229857369\"\nOutput: \"\"\nExplanation: \"1229857369\" has only digits so we cannot separate them by characters.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of only lowercase English letters and/or digits.\n\n",
        "solution_py": "class Solution:\n    def reformat(self, s: str) -> str:\n        # Store the alphabets and the numerics from the string in a seperat arrays\n        alpha = []\n        num = []\n        # Initiate a res variable to store the resultant string\n        res = ''\n        \n        for i in s:\n            if i.isalpha():\n                alpha.append(i)\n            else:\n                num.append(i)\n                \n        # It's not possible to create a permutation if the absolute difference b/w len(alpha) and len(num) > 1.\n        if abs(len(alpha)-len(num)) > 1: return ''\n        \n        # Use Zip to create list of tuples.\n        # For ex:- if alpha = ['a','b'] and num = ['1', '2'] then,\n        # zip(alpha, num) = [('a', '1'), ('b', '2')]\n        for ch, n in zip(alpha, num):\n            res += (ch+n)\n            \n        if len(alpha) > len(num):\n            res += alpha[-1]\n        if len(num) > len(alpha):\n            res = num[-1] + res\n            \n        return res",
        "solution_js": "var reformat = function(s) {\n    let letter=[], digit=[];\n    for(let i=0; i<s.length; i++){\n        s[i]>=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]);\n    }\n\t// impossible to reformat\n    if(Math.abs(letter.length-digit.length)>=2){return \"\"}\n    \n    let i=0, output=\"\";\n    while(i<letter.length && i<digit.length){\n        output=output+letter[i]+digit[i]; i++;\n    }\n    if(i<letter.length){output=output+letter[i]}; // add in the END\n    if(i<digit.length){output=digit[i]+output}; // add in the FRONT\n    return output;\n};",
        "solution_java": "class Solution {\n    public String reformat(String s) {\n        \n        List<Character> ch = new ArrayList<>();\n        List<Character> d = new ArrayList<>();\n        \n        for(char c : s.toCharArray()){\n            if(c >= 'a' && c <= 'z')ch.add(c);\n            else d.add(c);\n        }\n        \n        if(Math.abs(d.size() - ch.size()) > 1)  return \"\";\n        \n        StringBuilder str = new StringBuilder();\n        \n        for(int i = 0; i < s.length(); i++){\n            \n            if(!ch.isEmpty() || !d.isEmpty()){\n                if(ch.size() > d.size())\n                    str.append(appender(ch,d));\n                else \n                    str.append(appender(d,ch));\n            }\n            else{\n                break;\n            }\n        }\n        \n        return new String(str);\n        \n    }\n    \n    public String appender(List<Character> first,List<Character> second){\n        \n        StringBuilder str = new StringBuilder();\n        \n        if(!first.isEmpty()){\n            str.append(first.get(0));\n            first.remove(0);\n        }\n        if(!second.isEmpty()){\n            str.append(second.get(0));\n            second.remove(0);\n        }\n        \n        return new String(str);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reformat(string s) {\n        string dg,al;\n        for(auto&i:s)isdigit(i)?dg+=i:al+=i;\n        if(abs((int)size(dg)-(int)size(al))>1) return \"\";\n        int i=0,j=0,k=0;\n        string ans(size(s),' ');\n        bool cdg=size(dg)>size(al);\n        while(k<size(s)){\n            if(cdg)ans[k++]=dg[i++];\n            else ans[k++]=al[j++];\n            cdg=!cdg;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Max Consecutive Ones",
        "algo_input": "Given a binary array nums, return the maximum number of consecutive 1's in the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,0,1,1,1]\nOutput: 3\nExplanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.\n\n\nExample 2:\n\nInput: nums = [1,0,1,1,0,1]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\tnums[i] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n        \n        count = maxCount = 0\n        \n        for i in range(len(nums)):\n            if nums[i] == 1:\n                count += 1\n            else:\n                maxCount = max(count, maxCount)\n                count = 0\n                \n        return max(count, maxCount)",
        "solution_js": "var findMaxConsecutiveOnes = function(nums) {\n    let count =0\n    let max =0\n    for(let i=0; i<nums.length; i ++){\n        if(nums[i]==1){\n            count ++\n        }\n        if(nums[i]==0 || i==nums.length-1){\n            max = Math.max(count,max)\n            count = 0\n        }\n    }\n    return max\n};",
        "solution_java": "class Solution {\n    public int findMaxConsecutiveOnes(int[] nums) {\n        int max = 0;\n        int new_max = 0;\n        for(int i=0;i<nums.length;i++){\n            if(nums[i]==1)\n            {\n                max++;\n            }\n            else{\n                if(max>new_max){\n                    new_max = max;\n                }\n                max = 0;\n            }\n        }\n        if(max<new_max)\n            return new_max;\n        else\n            return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findMaxConsecutiveOnes(vector<int>& nums)\n    {\n        int curr_count = 0;\n        int max_count = 0;\n        int i = 0;\n        while(i < nums.size())\n        {\n            if(nums[i] == 1)\n            {\n                curr_count += 1;\n                if(max_count < curr_count)\n                    max_count = curr_count;                        \n            }\n            \n            else\n                curr_count = 0;\n            i++;\n        }\n        return max_count;\n    }\n};"
    },
    {
        "title": "Monotonic Array",
        "algo_input": "An array is monotonic if it is either monotone increasing or monotone decreasing.\n\nAn array nums is monotone increasing if for all i &lt;= j, nums[i] &lt;= nums[j]. An array nums is monotone decreasing if for all i &lt;= j, nums[i] &gt;= nums[j].\n\nGiven an integer array nums, return true if the given array is monotonic, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,2,3]\nOutput: true\n\n\nExample 2:\n\nInput: nums = [6,5,4,4]\nOutput: true\n\n\nExample 3:\n\nInput: nums = [1,3,2]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-105 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def isMonotonic(self, nums: List[int]) -> bool:\n        counter = 0\n        for i in range(len(nums) - 1):\n            if nums[i] >= nums[i + 1]:\n                counter += 1\n        if counter == len(nums) - 1:\n            return True\n        counter = 0\n        for i in range(len(nums) - 1):\n            if nums[i] <= nums[i + 1]:\n                counter += 1\n        if counter == len(nums) - 1:\n            return True\n        return False",
        "solution_js": "var isMonotonic = function(nums) {\n    let increasingCount = 0;\n    let decreasingCount = 0;\n    for(let i = 1; i < nums.length; i++){\n        if(nums[i] > nums[i-1]){\n            increasingCount++;\n        }else if(nums[i] < nums[i-1]){\n            decreasingCount++;\n        }\n    }\n    \n    return !(increasingCount && decreasingCount);\n};",
        "solution_java": "class Solution {\n    public boolean isMonotonic(int[] nums) {\n        if(nums[0]<nums[nums.length-1]){\n            for(int i=0;i<nums.length-1;i++){\n            if(!(nums[i]<=nums[i+1])) return false;\n        }\n        }else{\n            for(int i=0;i<nums.length-1;i++){\n            if(!(nums[i]>=nums[i+1])) return false;\n        }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isMonotonic(vector<int>& nums) {\n        auto i = find_if_not(begin(nums), end(nums), [&](int a) {return a == nums.front();});\n        auto j = find_if_not(rbegin(nums), rend(nums), [&](int a) {return a == nums.back();});\n        return is_sorted(--i, end(nums)) or is_sorted(--j, rend(nums));\n    }\n};"
    },
    {
        "title": "Maximum Ascending Subarray Sum",
        "algo_input": "Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.\n\nA subarray is defined as a contiguous sequence of numbers in an array.\n\nA subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l &lt;= i &lt; r, numsi  &lt; numsi+1. Note that a subarray of size 1 is ascending.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,20,30,5,10,50]\nOutput: 65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n\n\nExample 2:\n\nInput: nums = [10,20,30,40,50]\nOutput: 150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n\n\nExample 3:\n\nInput: nums = [12,17,15,13,10,11,12]\nOutput: 33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def maxAscendingSum(self, nums: List[int]) -> int:\n        count=nums[0]\n        final=nums[0]\n        for i in range(1,len(nums)):\n            if nums[i]>nums[i-1]:\n                count+=nums[i]\n            else:\n                count=nums[i]\n            final=max(final,count)\n        return final",
        "solution_js": "var maxAscendingSum = function(nums) {\n    const subarray = nums.reduce((acc, curr, index) => {\n        curr > nums[index - 1] ? acc[acc.length - 1] += curr : acc.push(curr);\n        return acc;\n    }, []);\n\n    return Math.max(...subarray);\n};",
        "solution_java": "class Solution {\n    public int maxAscendingSum(int[] nums) {\n        int res = nums[0],temp = nums[0];\n        for(int i = 1;i<nums.length;i++){\n            if(nums[i] > nums[i-1])\n                temp+=nums[i];\n            else\n                temp = nums[i];\n            res = Math.max(res,temp);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxAscendingSum(vector<int>& nums) {\n        int max_sum = nums[0], curr = nums[0];\n        for (int i = 1; i < nums.size(); i++) {\n            if (nums[i-1] < nums[i]) {\n                curr += nums[i];\n            }\n            else {\n                max_sum = max(max_sum, curr);\n                curr = nums[i];\n            }\n        }\n        return max(max_sum, curr);\n    }\n};"
    },
    {
        "title": "Maximum Trailing Zeros in a Cornered Path",
        "algo_input": "You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.\n\nA cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.\n\nThe product of a path is defined as the product of all the values in the path.\n\nReturn the maximum number of trailing zeros in the product of a cornered path found in grid.\n\nNote:\n\n\n\tHorizontal movement means moving in either the left or right direction.\n\tVertical movement means moving in either the up or down direction.\n\n\n&nbsp;\nExample 1:\n\nInput: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput: 3\nExplanation: The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.\n\n\nExample 2:\n\nInput: grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput: 0\nExplanation: The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.\n\n\n&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;= grid[i][j] &lt;= 1000\n\n",
        "solution_py": "import numpy as np\n\nclass Solution:\n    def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n        A = np.array(grid)\n        def cumdivs(d):\n            D = sum(A % d**i == 0 for i in range(1, 10))\n            return D.cumsum(0) + D.cumsum(1) - D\n        return max(np.minimum(cumdivs(2), cumdivs(5)).max()\n                   for _ in range(4)\n                   if [A := np.rot90(A)])",
        "solution_js": "var maxTrailingZeros = function(grid) {\n    const m = grid.length;\n    const n = grid[0].length;\n\n    const postfixCols = [];\n\n    for (let i = 0; i < m; ++i) {\n        for (let j = 0; j < n; ++j) {\n            const num = grid[i][j];\n\n            if (postfixCols[j] == null) postfixCols[j] = { 2: 0, 5: 0 };\n\n            postfixCols[j][\"2\"] += getCount(num, 2);\n            postfixCols[j][\"5\"] += getCount(num, 5);\n        }\n    }\n\n    const prefixCols = [];\n\n    for (let j = 0; j < n; ++j) {\n        prefixCols[j] = { 0: 0, 2: 0, 5: 0 };\n    }\n\n    let maxZeros = 0;\n\n    for (let i = 0; i < m; ++i) {\n        const postfixRow = { 0: 0, 2: 0, 5: 0 };\n\n        for (let j = n - 1; j >= 0; --j) {\n            const num = grid[i][j];\n\n            postfixRow[\"2\"] += getCount(num, 2);\n            postfixRow[\"5\"] += getCount(num, 5);\n        }\n\n        let prefixRow = { 0: 0, 2: 0, 5: 0 };\n\n        for (let j = 0; j < n; ++j) {\n            const num = grid[i][j];\n\n            const twoCount = getCount(num, 2);\n            const fiveCount = getCount(num, 5);\n\n            postfixRow[\"2\"] -= twoCount;\n            postfixCols[j][\"2\"] -= twoCount;\n\n            postfixRow[\"5\"] -= fiveCount;\n            postfixCols[j][\"5\"] -= fiveCount;\n\n            // down-right => prefixCol + postfixRow\n            const downRight = calculateTrailingZeros(prefixCols[j], postfixRow, num);\n            // down-left => prefixCol + prefixRow\n            const downLeft = calculateTrailingZeros(prefixCols[j], prefixRow, num);\n            // up-right => postfixCols + postfixRow\n            const upRight = calculateTrailingZeros(postfixCols[j], postfixRow, num);\n            // up-left => postfixCols + prefixRow\n            const upLeft = calculateTrailingZeros(postfixCols[j], prefixRow, num);\n\n            maxZeros = Math.max(maxZeros, downRight, downLeft, upRight, upLeft);\n\n            prefixRow[\"2\"] += twoCount;\n            prefixCols[j][\"2\"] += twoCount;\n\n            prefixRow[\"5\"] += fiveCount;\n            prefixCols[j][\"5\"] += fiveCount;\n        }\n    }\n\n    return maxZeros;\n\n    function calculateTrailingZeros(col, row, currNum) {\n        let twosCount = 0;\n        let fivesCount = 0;\n        let zerosCount = 0;\n\n        twosCount = row[\"2\"] + col[\"2\"];\n        fivesCount = row[\"5\"] + col[\"5\"];\n\n        twosCount += getCount(currNum, 2);\n        fivesCount += getCount(currNum, 5);\n        return Math.min(twosCount, fivesCount);\n    }\n\n    function getCount(num, divisor) {\n        let count = 0;\n\n        while (num % divisor === 0) {\n            ++count;\n            num /= divisor;\n        }\n\n        return count;\n    }\n};",
        "solution_java": "class Solution {\n    public int maxTrailingZeros(int[][] grid) {\n        int m = grid.length;\n        int n = grid[0].length;\n        int[][][] dph = new int[m][n][3];\n        int[][][] dpv = new int[m][n][3];\n        int hmax0 = 0;\n        int vmax0 = 0;\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                int curr = grid[i][j];\n                int two = 0;\n                int five = 0;\n                if (j >= 1) {\n                    two = dph[i][j-1][1];\n                    five = dph[i][j-1][2];\n                }\n                while (curr > 0 && curr % 2 == 0) {\n                    two++;\n                    curr /= 2;\n                }\n                while (curr > 0 && curr % 5 == 0) {\n                    five++;\n                    curr /= 5;\n                }\n                dph[i][j][1] = two;\n                dph[i][j][2] = five;\n                dph[i][j][0] = Math.min(dph[i][j][1], dph[i][j][2]);\n            }\n            hmax0 = Math.max(hmax0, dph[i][n-1][0]);\n        }\n        \n        for (int j = 0; j < n; j++) {\n            for (int i = 0; i < m; i++) {\n                int curr = grid[i][j];\n                int two = 0;\n                int five = 0;\n                if (i >= 1) {\n                    two = dpv[i-1][j][1];\n                    five = dpv[i-1][j][2];\n                }\n                while (curr > 0 && curr % 2 == 0) {\n                    two++;\n                    curr /= 2;\n                }\n                while (curr > 0 && curr % 5 == 0) {\n                    five++;\n                    curr /= 5;\n                }\n                dpv[i][j][1] = two;\n                dpv[i][j][2] = five;\n                dpv[i][j][0] = Math.min(dpv[i][j][1], dpv[i][j][2]);\n            }\n            vmax0 = Math.max(vmax0, dpv[m-1][j][0]);\n        }\n\t\t\n        int res = Math.max(vmax0, hmax0);\n\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                int otwo = dph[i][j][1];\n                int ofive = dph[i][j][2];\n                \n                int res1 = 0;\n                if (i >= 1) {\n                    int ntwo = otwo + dpv[i-1][j][1];\n                    int nfive = ofive + dpv[i-1][j][2];\n                    res1 = Math.min(ntwo, nfive);\n                }\n                \n                int res2 = 0;\n                if (i < m - 1) {\n                    int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];\n                    int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];\n                    res2 = Math.min(ntwo, nfive);\n                }\n                res = Math.max(res, res1);\n                res = Math.max(res, res2);\n            }\n\t\t\t\n\t\t\tfor (int j = n - 1; j >= 0; j--) {\n                int otwo = 0;\n                int ofive = 0;\n                if (j >= 1) {\n                    otwo = dph[i][n-1][1] - dph[i][j-1][1];\n                    ofive = dph[i][n-1][2] - dph[i][j-1][2];\n                } else {\n                    otwo = dph[i][n-1][1];\n                    ofive = dph[i][n-1][2];\n                }\n                \n                int res1 = 0;\n                if (i >= 1) {\n                    int ntwo = otwo + dpv[i-1][j][1];\n                    int nfive = ofive + dpv[i-1][j][2];\n                    res1 = Math.min(ntwo, nfive);\n                }\n                \n                int res2 = 0;\n                if (i < m - 1) {\n                    int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];\n                    int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];\n                    res2 = Math.min(ntwo, nfive);\n                }\n                \n                res = Math.max(res, res1);\n                res = Math.max(res, res2);\n            }\n        }\n\t\t\n        return res;\n    }\n}",
        "solution_c": "array<int, 2> operator+(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] + r[0], l[1] + r[1] }; }\narray<int, 2> operator-(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] - r[0], l[1] - r[1] }; }\nint pairs(const array<int, 2> &p) { return min(p[0], p[1]); }\n\nclass Solution {\npublic:\nint factors(int i, int f) {\n    return i % f ? 0 : 1 + factors(i / f, f);\n}\nint maxTrailingZeros(vector<vector<int>>& grid) {\n    int m = grid.size(), n = grid[0].size(), res = 0;\n    vector<vector<array<int, 2>>> h(m, vector<array<int, 2>>(n + 1)), v(m + 1, vector<array<int, 2>>(n));\n    for (int i = 0; i < m; ++i)\n        for (int j = 0; j < n; ++j) {\n            array<int, 2> f25 = { factors(grid[i][j], 2), factors(grid[i][j], 5) };\n            v[i + 1][j] = v[i][j] + f25;\n            h[i][j + 1] = h[i][j] + f25;\n        }\n    for (int i = 0; i < m; ++i)\n        for (int j = 0; j < n; ++j) {\n            auto v1 = v[i + 1][j], v2 = v[m][j] - v[i][j];\n            auto h1 = h[i][j], h2 = h[i][n] - h[i][j + 1];\n            res = max({res, pairs(v1 + h1), pairs(v1 + h2), pairs(v2 + h1), pairs(v2 + h2)});\n        }\n    return res;\n}\n};"
    },
    {
        "title": "Path Sum II",
        "algo_input": "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.\n\nA root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: [[5,4,11,2],[5,8,4,5]]\nExplanation: There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n\n\nExample 2:\n\nInput: root = [1,2,3], targetSum = 5\nOutput: []\n\n\nExample 3:\n\nInput: root = [1,2], targetSum = 0\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 5000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\t-1000 &lt;= targetSum &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\n        res = []\n        def dfs(v, path, pathsum):\n            if not v:\n                return\n            path.append(v.val)\n            pathsum += v.val\n            if not v.left and not v.right and pathsum == targetSum:\n                res.append(path[:])\n            dfs(v.left, path, pathsum)\n            dfs(v.right, path, pathsum)\n            path.pop()\n        dfs(root, [], 0)\n        return res",
        "solution_js": "var pathSum = function(root, targetSum) {\n  const paths = [];\n\n  function dfs(root, sum, curr = []) {\n    if (!root) return;\n\n    const newCurr = [...curr, root.val];\n    if (!root.left && !root.right && sum === root.val) return paths.push(newCurr);\n\n    dfs(root.left, sum - root.val, newCurr);\n    dfs(root.right, sum - root.val, newCurr);\n  }\n\n  dfs(root, targetSum);\n  return paths;\n};",
        "solution_java": "class Solution \n{\n    public List<List<Integer>> pathSum(TreeNode root, int targetSum) \n    {\n        List<List<Integer>> ans = new ArrayList<>();\n        pathSum(root, targetSum, new ArrayList<>(), ans);\n        return ans;\n    }\n    \n    public void pathSum(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> ans)\n    {\n        if(root == null)\n            return;\n        path.add(root.val);\n        if(root.left == null && root.right == null && targetSum == root.val)//leaf node that completes path\n        {\n            ans.add(new ArrayList(path));// we use new ArrayList because if we don't the originaly List is added which is mutable, if we add a copy that's not mutable.\n        }\n        else\n        {\n            pathSum(root.left, targetSum-root.val, path, ans);\n            pathSum(root.right, targetSum-root.val, path, ans);\n        }\n        path.remove(path.size()-1); //removal of redundant nodes\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int>> v;\n    void helper(vector<int>& t, int target, TreeNode* root){\n        if(root==NULL){\n            return;\n        }\n        if(root->left==NULL&&root->right==NULL&&target==root->val){\n            t.push_back(root->val);\n            v.push_back(t);\n            t.pop_back();\n            return;\n        }\n        target=target-root->val;\n        t.push_back(root->val);\n        helper(t,target,root->left);\n        helper(t,target,root->right);\n        t.pop_back();\n\n        //cout<<root->val<<\" \"<<target<<endl;\n        return;\n    }\n    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {\n        vector<int> t;\n        helper(t,targetSum,root);\n        return v;\n    }\n};"
    },
    {
        "title": "Gas Station",
        "algo_input": "There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].\n\nYou have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.\n\nGiven two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique\n\n&nbsp;\nExample 1:\n\nInput: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput: 3\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n\n\nExample 2:\n\nInput: gas = [2,3,4], cost = [3,4,3]\nOutput: -1\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == gas.length == cost.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= gas[i], cost[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n        deltas = [x-y for x, y in zip(gas, cost)]\n        n = len(deltas)\n        deltas = deltas + deltas\n        cursum, curi = 0, 0\n        maxsum, maxi = 0, 0\n        for i, delta in enumerate(deltas):\n            cursum = max(0, cursum + delta)\n            if cursum == 0:\n                curi = i+1\n            if cursum > maxsum:\n                maxi = curi\n                maxsum = cursum\n        cursum = 0\n        for i in range(n):\n            cursum += deltas[(maxi+i)%n]\n            if cursum < 0: return -1\n        return maxi",
        "solution_js": "var canCompleteCircuit = function(gas, cost) {\n    const len = gas.length;\n    // scan forward from the current index\n    const scan = (i) => {\n        let numTries = 0;\n        let tank = 0;\n        let c = 0;\n        while (numTries <= len) {\n            tank -= c;\n            if (tank < 0) return -1;\n            // if we made it back around, and we have gas, return the index, we made it!\n            if (numTries === len && tank >= 0) {\n                return i;\n            }\n            tank += gas[i];\n            c = cost[i];\n            i++;\n            if (i === len) i = 0; // if we hit the end, bounce back to zero\n            numTries++;\n        }\n        return -1;\n    }\n\n    for (let i = 0; i < len; i++) {\n        if (!gas[i]) continue; // no gas / zero gas so let's just move on\n        let index = scan(i);\n        if (~index) return index; // if it's not -1, return it\n    }\n\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int canCompleteCircuit(int[] gas, int[] cost) {\n       // *Upvote will be appreciated*\n        int totalFuel = 0;\n        int totalCost = 0;\n        int n = gas.length;\n        for(int i = 0; i < n; i++) {\n            totalFuel += gas[i];\n        }\n        for(int i = 0; i < n; i++) {\n            totalCost += cost[i];\n        }\n        // if totalfuel < totalCost then It is not possible to tavel\n        if(totalFuel < totalCost) {\n            return -1;\n        }\n\n        // It is greather then There may be an Answer\n        int start = 0;\n        int currFuel = 0;\n        for(int i = 0; i < n; i++) {\n            currFuel += (gas[i]-cost[i]);\n            if(currFuel < 0) { // It Current Fuel is less than 0 mean we can't star from that index\n                start = i+1; // so we start from next index\n                currFuel = 0;\n            }\n        }\n        return start;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {\n        int n = gas.size();\n        int start = -1;\n\n        int sum = 0 , gastillnow = 0;\n        for(int i = 0 ; i < 2*n ; i++){\n            if(start == i%n){\n                return i%n;\n            }\n            if(gas[i%n] + gastillnow >= cost[i%n]){ // we can start from this index\n                if(start==-1) start = i;\n                gastillnow += gas[i%n]-cost[i%n];\n            }else if(gastillnow + gas[i%n] < cost[i%n]){ // previous start index was wrong we have to start from another\n                start = -1;\n                gastillnow = 0;\n            }\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Number of Segments in a String",
        "algo_input": "Given a string s, return the number of segments in the string.\n\nA segment is defined to be a contiguous sequence of non-space characters.\n\n&nbsp;\nExample 1:\n\nInput: s = \"Hello, my name is John\"\nOutput: 5\nExplanation: The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]\n\n\nExample 2:\n\nInput: s = \"Hello\"\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= s.length &lt;= 300\n\ts consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&amp;*()_+-=',.:\".\n\tThe only space character in s is ' '.\n\n",
        "solution_py": "class Solution:\n    def countSegments(self, s: str) -> int:\n        return len(s.split())",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar countSegments = function(s) {\n    return s.trim() ? s.trim().split(/\\s+/).length : 0\n};",
        "solution_java": "class Solution {\n    public int countSegments(String s) {\n        int length = 0;\n        boolean flag = false;\n\n        for(Character c : s.toCharArray()) {\n            if(c == ' ' && flag) {\n                length++;\n                flag = !flag;\n            } else if(c != ' ') {\n                flag = true;\n            }\n        }\n\n        return flag ? length + 1 : length;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countSegments(string s) {\n        if(s==\"\")\n            return 0;\n        int res=0,flag=0;\n        for(int i=0;i<size(s);i++){\n            if(s[i]!=' '){\n                i++;\n                while(i<size(s) and s[i]!=' '){\n                    i++;\n                }\n                res++;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Divide Array in Sets of K Consecutive Numbers",
        "algo_input": "Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.\n\nReturn true if it is possible. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,3,4,4,5,6], k = 4\nOutput: true\nExplanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\n\n\nExample 2:\n\nInput: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput: true\nExplanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\n\n\nExample 3:\n\nInput: nums = [1,2,3,4], k = 3\nOutput: false\nExplanation: Each array should be divided in subarrays of size 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\n\n&nbsp;\nNote: This question is the same as&nbsp;846:&nbsp;https://leetcode.com/problems/hand-of-straights/",
        "solution_py": "class Solution(object):\n    def isPossibleDivide(self, nums, k):\n        \"\"\"\n        :type nums: List[int]\n        :type k: int\n        :rtype: bool\n        \"\"\"\n        if len(nums) % k != 0:\n            return False\n        \n        freq = collections.defaultdict(int)\n        for v in nums:\n            freq[v] += 1\n            \n        nums.sort()\n        while sum(freq.values()) > 0:\n\t\t\t# smallest number in sorted nums with freq > 0 to start a sequence [v, v+1, v+2 ... , v+k-1]\n            for v in nums: \n                if freq[v] > 0: \n                    for i in range(k):\n                        if freq[v+i] <= 0:\n                            return False\n                        else:\n                            freq[v+i] -= 1\n        return True",
        "solution_js": "var isPossibleDivide = function(nums, k) {\n    if(nums.length % k) {\n        return false;\n    }\n\n    nums.sort((a, b) => a - b);\n\n    let numberOfArrays = nums.length / k, index = 0, dp = Array(numberOfArrays).fill(null).map(() => []);\n\n    dp[0].push(nums[0]);\n\n    for(let i = 1; i < nums.length; i++) {\n        if(nums[i] === nums[i - 1]) {\n            if(index === numberOfArrays - 1) {\n                return false;\n            }\n            index++;\n        }\n        else {\n            index = 0;\n            while(dp[index].length === k) {\n                index++;\n            }\n        }\n        if(dp[index].length && dp[index].at(-1) + 1 != nums[i]) {\n            return false;\n        }\n        dp[index].push(nums[i])\n    }\n\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean isPossibleDivide(int[] nums, int k) {\n        if (nums.length % k != 0) return false;\n        Map<Integer, Integer> countMap = new HashMap<>();\n        for (int num : nums) {\n            int count = countMap.getOrDefault(num, 0);\n            countMap.put(num , count + 1);\n        }\n        Arrays.sort(nums);\n        for (int num : nums) {\n            if (!countMap.containsKey(num)) continue;\n            int count = countMap.get(num);\n            if (count == 1) countMap.remove(num);\n            else countMap.put(num, count - 1);\n            for (int i = 1; i < k; i++) {\n                int next = num + i;\n                if (!countMap.containsKey(next)) return false;\n                count = countMap.get(next);\n                if (count == 1) countMap.remove(next);\n                else countMap.put(next, count - 1);\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPossibleDivide(vector<int>& nums, int k) {\n        if(nums.size() % k) return false;\n        \n        map<int, int> m;\n        for(int i : nums) m[i]++;\n        \n        int n = m.size();\n        while(n) {\n            int a = m.begin() -> first;\n            m[a]--;\n            if(!m[a]) m.erase(a), n--;\n            for(int i=1; i<k; i++) {\n                if(m.find(a + i) == m.end()) return false;\n                m[a + i]--;\n                if(!m[a + i]) m.erase(a + i), n--;\n            }\n        }\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Top K Frequent Words",
        "algo_input": "Given an array of strings words and an integer k, return the k most frequent strings.\n\nReturn the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\nOutput: [\"i\",\"love\"]\nExplanation: \"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.\n\n\nExample 2:\n\nInput: words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\nOutput: [\"the\",\"is\",\"sunny\",\"day\"]\nExplanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 500\n\t1 &lt;= words[i].length &lt;= 10\n\twords[i] consists of lowercase English letters.\n\tk is in the range [1, The number of unique words[i]]\n\n\n&nbsp;\nFollow-up: Could you solve it in O(n log(k)) time and O(n) extra space?\n",
        "solution_py": "import heapq\nclass Solution:\n    def topKFrequent(self, words: List[str], k: int) -> List[str]:\n        \n        li = {}\n        for i in words:\n            if i in li:\n                li[i]+=1\n            else:\n                li[i]=1\n        \n        heap = []\n        for i in li:\n            heap.append([-li[i],i])\n        \n        heapq.heapify(heap)\n        \n        ans = []\n        for i in range(k):\n            ans.append(heapq.heappop(heap)[1])\n        \n        return ans",
        "solution_js": "var topKFrequent = function(words, k) {\n    let map=new Map()\n    let res=[]\n    for(let i of words){\n        if(map.has(i)){\n            map.set(i,map.get(i)+1)\n        }else{\n            map.set(i,1)\n        }\n    }\n    \n    res=[...map.keys()].sort((a,b)=>{\n        if(map.get(a)===map.get(b)){\n            return b < a ? 1:-1\n        }\n        return map.get(b)-map.get(a)\n    }).slice(0,k)\n    \n    return res\n};",
        "solution_java": "class Solution {\n    public List<String> topKFrequent(String[] words, int k) {\n        Map<String,Integer> map=new LinkedHashMap<>();\n        for(String word:words) \n            map.put(word,map.getOrDefault(word,0)+1);\n        PriorityQueue<Pair<String,Integer>> queue=new PriorityQueue<>(new Comparator<Pair<String,Integer>>(){\n            @Override\n            public int compare(Pair<String,Integer> a,Pair<String,Integer> b){\n                if(a.getValue()!=b.getValue()) return b.getValue()-a.getValue();\n                return a.getKey().compareTo(b.getKey());\n            }\n        });\n        map.forEach((key,val)->{\n            queue.add(new Pair(key,val));\n        });\n        List<String> list=new ArrayList<>();\n        while(k>0){\n            list.add(queue.poll().getKey());\n            k--;\n        }\n        return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool static comp(pair<string, int> a, pair<string, int> b){\n        if(a.second > b.second) return true;\n        else if(a.second < b.second) return false;\n        else{\n            return a.first < b.first;\n        }\n    }\n    vector<string> topKFrequent(vector<string>& words, int k) {\n        unordered_map<string, int> m;\n        for(auto i : words){\n            m[i]++;\n        }\n        vector<pair<string, int>> v;\n        for(auto i : m){\n            v.push_back(i);\n        }\n        sort(v.begin(), v.end(), comp);\n        vector<string> ans;\n        for(int i=0; i<k; i++){\n            ans.push_back(v[i].first);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Detect Cycles in 2D Grid",
        "algo_input": "Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.\n\nA cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\n\nAlso, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -&gt; (1, 2) -&gt; (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.\n\nReturn true if any cycle of the same value exists in grid, otherwise, return false.\n\n&nbsp;\nExample 1:\n\n\n\nInput: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\nOutput: true\nExplanation: There are two valid cycles shown in different colors in the image below:\n\n\n\nExample 2:\n\n\n\nInput: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\nOutput: true\nExplanation: There is only one valid cycle highlighted in the image below:\n\n\n\nExample 3:\n\n\n\nInput: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 500\n\tgrid consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def containsCycle(self, grid: List[List[str]]) -> bool:\n        \n        def getNeighbours(row,col,char):\n            neighbours = []\n            if row > 0 and grid[row-1][col] == char and not visited[row-1][col]:\n                neighbours.append([row-1,col])\n            if col > 0 and grid[row][col-1] == char and not visited[row][col-1]:\n                neighbours.append([row,col-1])\n            if row < len(grid)-1 and grid[row+1][col] == char and not visited[row+1][col]:\n                neighbours.append([row+1,col])\n            if col < len(grid[0])-1 and grid[row][col+1] == char and not visited[row][col+1]:\n                neighbours.append([row,col+1])\n            return neighbours\n        \n        def dfs(row,col,char,cyclePresent):\n            if visited[row][col] or cyclePresent:\n                cyclePresent = True\n                return cyclePresent\n            visited[row][col] = True\n            neighbours = getNeighbours(row,col,char)\n            for r,c in neighbours:\n                cyclePresent = dfs(r,c,char,cyclePresent)\n            return cyclePresent\n        \n        visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\n        cyclePresent = False\n        for row in range(len(grid)):\n            for col in range(len(grid[0])):\n                if cyclePresent:\n                    return True\n                if visited[row][col]:\n                    continue\n                cyclePresent = dfs(row,col,grid[row][col],cyclePresent)\n        \n        return cyclePresent",
        "solution_js": "/**\n * @param {character[][]} grid\n * @return {boolean}\n */\nvar containsCycle = function(grid) {\n    const m = grid.length;\n    const n = grid[0].length;\n    const visited = [...Array(m)].map(i => Array(n).fill(0));\n    const dir = [[-1,0],[1,0],[0,-1],[0,1]];\n    \n    const dfs = (x,y,lx,ly) => {        \n        visited[x][y] = 1;\n        for (const [a, b] of dir) {\n            const nx = x + a;\n            const ny = y + b;\n            \n            if (nx < 0 || nx > m - 1 || ny < 0 || ny > n - 1)\n                continue;\n            \n            if (visited[nx][ny] === 1 && (nx !== lx || ny !== ly) && grid[x][y] === grid[nx][ny]) { // !!! grid[nx][ny] === grid[x][y]\n                return true;\n            }\n            \n            if (visited[nx][ny] === 0 && grid[x][y] === grid[nx][ny]) {\n                if (dfs(nx,ny,x,y))\n                    return true;\n            }\n        }\n        return false;\n    }\n    \n    for (let i = 0; i < m; i++) {\n        for (let j = 0; j < n; j++) {\n            if (visited[i][j] === 0 && dfs(i,j,-1,-1)) // !!!\n                return true;\n        }\n    }\n    \n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean containsCycle(char[][] grid) {\n        int rows = grid.length, cols = grid[0].length;\n\n\t\t// Create a boolean array of same dimensions to keep track of visited cells\n        boolean[][] visited = new boolean[rows][cols];\n        \n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < cols; j++) {\n                if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {\n                    return true;\n                }\n            }\n        }\n\n        return false;\n    }\n    \n    public boolean dfs(\n        char[][] grid,\n        boolean[][] visited,\n        int i,\n        int j,\n        int prevI,\n        int prevJ,\n        char c\n    ) {\n\t\t// Check for out of bounds\n        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;\n\n\t\t// Check whether the current char matches the previous char\n        if (grid[i][j] != c) return false;\n\t\t\n\t\t// If we stumble upon the same cell, we're guaranteed to have found a cycle!\n        if (visited[i][j]) {\n            return true;\n        }\n        \n\t\t// Mark the cell as visited\n        visited[i][j] = true;\n        \n\t\t// We want to search in the south direction ONLY IF we didn't come from north\n\t\t// Do the same for all four directions\n        boolean south = i - prevI != -1;\n        boolean north = i - prevI != 1;\n        boolean east = j - prevJ != -1;\n        boolean west = j - prevJ != 1;\n        return\n            (south && dfs(grid, visited, i + 1, j, i, j, c)) ||\n            (north && dfs(grid, visited, i - 1, j, i, j, c)) ||\n            (east && dfs(grid, visited, i, j + 1, i, j, c)) ||\n            (west && dfs(grid, visited, i, j - 1, i, j, c));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int dx[4]={-1,1,0,0};\n    int dy[4]={0,0,1,-1};\n    bool solve(vector<vector<char>>& grid,int i,int j,int m,int n,int x,int y,vector<vector<int>>&vis,char startChar){\n        vis[i][j]=1;\n        for(int k=0;k<4;k++){\n            int xx=i+dx[k];\n            int yy=j+dy[k];\n            if(xx>=0 && yy>=0 && xx<m && yy<n && grid[xx][yy]==startChar && !(x == xx && y == yy)){\n              if(vis[xx][yy] || solve(grid, xx , yy , m , n, i, j,vis,startChar))\n                    return true;\n            }\n        }\n        return false;\n    }\n\n    bool containsCycle(vector<vector<char>>& grid) {\n     int m=grid.size();\n     int n=grid[0].size();\n     vector<vector<int>>vis(m,vector<int>(n,0));\n     for(int i=0;i<m;i++){\n         for(int j=0;j<n;j++){\n             if(!vis[i][j] && solve(grid,i,j,m,n,-1,-1,vis,grid[i][j])){\n                 return true;\n             }\n         }\n     }\n        return false;\n    }\n};"
    },
    {
        "title": "Minimum Total Space Wasted With K Resizing Operations",
        "algo_input": "You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).\n\nThe size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at&nbsp;time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 &lt;= t &lt; nums.length.\n\nReturn the minimum total space wasted if you can resize the array at most k times.\n\nNote: The array can have any size at the start and does not count towards the number of resizing operations.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,20], k = 0\nOutput: 10\nExplanation: size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.\n\n\nExample 2:\n\nInput: nums = [10,20,30], k = 1\nOutput: 10\nExplanation: size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.\n\n\nExample 3:\n\nInput: nums = [10,20,15,30,20], k = 2\nOutput: 15\nExplanation: size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t1 &lt;= nums[i] &lt;= 106\n\t0 &lt;= k &lt;= nums.length - 1\n\n",
        "solution_py": "class Solution:\n    def minSpaceWastedKResizing(self, A: List[int], K: int) -> int:\n        def waste(i, j, h):\n            sumI = sums[i-1] if i > 0 else 0\n            return (j-i+1)*h - sums[j] + sumI\n        \n        def dp(i, k):\n            if i <= k:\n                return 0\n            if k < 0:\n                return MAX\n            if (i, k) in memoize:\n                return memoize[(i, k)]\n            \n            _max = A[i]\n            r = MAX\n            for j in range(i-1, -2, -1):\n                r = min(r, dp(j, k-1) + waste(j+1, i,  _max))\n                _max = max(_max, A[j])\n\n            memoize[(i, k)] = r\n            return r\n        \n        sums = list(accumulate(A))\n        n = len(A)\n        MAX = 10**6*200\n        memoize = {}\n\n        return dp(n-1, K)",
        "solution_js": "var minSpaceWastedKResizing = function(nums, k) {\n    var prefixSum = []; // prefix is index 1 based\n    var rangeMax = []; // index 0 based\n    var sum = 0;\n    prefixSum[0] = 0; \n    for (var i = 0; i < nums.length; i++) {\n        sum += nums[i];\n        prefixSum[i + 1] = sum;\n    }\n    for (var i = 0; i < nums.length; i++) {\n        var max = -Infinity;\n        rangeMax[i] = [];\n        for (var j = i; j < nums.length; j++) {\n            max = Math.max(nums[j], max);\n            rangeMax[i][j] = max;\n        }\n    }\n    var f = []; // f[i][j] is resize i times to get minimun with index j - 1 to get minimum space.\n    f[0] = [];\n    for (var i = 0; i <= k; i++) {\n        f[i] = [];\n        f[i][0] = 0;\n    }\n    for (var j = 1; j <= nums.length; j++) {\n        f[0][j] = rangeMax[0][j - 1] * j - prefixSum[j];\n    }\n\n    for (var i = 1; i <= k; i++) {\n        for (var j = 1; j <= nums.length; j++) {\n            f[i][j] = Infinity;\n            for (var m = 1; m <= j; m++) {\n                f[i][j] = Math.min(f[i][j], f[i - 1][m - 1] + rangeMax[m - 1][j - 1] * (j - m + 1) - (prefixSum[j] - prefixSum[m - 1]));\n            }\n        }\n    }\n    return f[k][nums.length];\n};",
        "solution_java": "class Solution {\n\n// dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times \n\n    int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 }\n    public int minSpaceWastedKResizing(int[] nums, int k) {\n        \n        int dp[][]=new int[nums.length+1][k+1];\n        memeset(dp, -1);\n        return f(dp, 0, k, nums);\n        \n    }\n    \n    int f(int dp[][], int idx, int k, int nums[])\n    {\n        if(idx==nums.length)\n            return 0;\n        if(k==-1)\n            return INF;\n        \n        if(dp[idx][k] != -1)\n            return dp[idx][k];\n        \n        int ans=INF, max=nums[idx], sum=0;\n        \n        for(int j=idx; j<nums.length; ++j)\n        {\n            max=Math.max(max, nums[j]);\n            sum+=nums[j];\n        /**    \n             total waste in between [idx...j] would be\n             summation of (max-nums[idx] + max-nums[idx+1]....max-nums[j])\n             length would be (j-idx+1) and these summation would be\n             (j-idx+1) * max upto j - (nums[idx]+nums[idx+1]....+nums[j]\n \n            as i have made one partition in between [idx...j] then remainig (k-1) partitions would be in between [j+1....n-1]\n            and that value will be calculated by the recursion and we have to take the minimum answer from all these combinations \n            and to avoid tle we are using memozization\n        **/\n            int total_waste_upto_j=(j-idx+1)*max - sum;\n            ans=Math.min(ans,  total_waste_upto_j + f(dp, j+1, k-1, nums));\n            \n        }\n        \n        return dp[idx][k]=ans;\n    }\n    \n    void memeset(int dp[][], int val)\n    {\n        for(int x[]: dp)\n            Arrays.fill(x, val);\n    }\n}\n\n// tc: O(n^2 * k) there will be total (n*k) states  because for each k there are n possibilities and for each n there will be loop running n times\n// so in total there will be O(n^2 * k) [because k<n]\n// sc: O(n*k)",
        "solution_c": "class Solution {\npublic:\n    int dp[205][205];\n    #define maxi pow(10,8)\n    #define ll long long\n    int dfs(vector<int>& nums, int idx, int k)\n    {\n        int n = nums.size();\n        if(idx==n) return 0;\n        if(k<0) return maxi;\n        if(dp[idx][k]!=-1) return dp[idx][k];\n        ll sum = 0, mx = 0, ans = maxi;\n        for(int i=idx; i<n; i++)\n        {\n            sum += nums[i];\n            mx = max(mx,(ll)nums[i]);\n            ans = min(ans,mx*(i-idx+1)-sum + dfs(nums,i+1,k-1));\n        }\n        return dp[idx][k] = ans;\n    }\n\n    int minSpaceWastedKResizing(vector<int>& nums, int k) {\n        memset(dp,-1,sizeof(dp));\n        return dfs(nums,0,k);\n    }\n};"
    },
    {
        "title": "Two Best Non-Overlapping Events",
        "algo_input": "You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.\n\nReturn this maximum sum.\n\nNote that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.\n\n&nbsp;\nExample 1:\n\nInput: events = [[1,3,2],[4,5,2],[2,4,3]]\nOutput: 4\nExplanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.\n\n\nExample 2:\n\nInput: events = [[1,3,2],[4,5,2],[1,5,5]]\nOutput: 5\nExplanation: Choose event 2 for a sum of 5.\n\n\nExample 3:\n\nInput: events = [[1,5,3],[1,5,1],[6,6,5]]\nOutput: 8\nExplanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= events.length &lt;= 105\n\tevents[i].length == 3\n\t1 &lt;= startTimei &lt;= endTimei &lt;= 109\n\t1 &lt;= valuei &lt;= 106\n\n",
        "solution_py": "class Solution:\ndef maxTwoEvents(self, events: List[List[int]]) -> int:\n    \n    events.sort()\n    heap = []\n    res2,res1 = 0,0\n    for s,e,p in events:\n        while heap and heap[0][0]<s:\n            res1 = max(res1,heapq.heappop(heap)[1])\n        \n        res2 = max(res2,res1+p)\n        heapq.heappush(heap,(e,p))\n    \n    return res2",
        "solution_js": "var maxTwoEvents = function(events) {\n    const n = events.length;\n\n    events.sort((a, b) => a[0] - b[0]);\n\n    const minHeap = new MinPriorityQueue({ priority: x => x[1] });\n\n    let maxVal = 0;\n    let maxSum = 0;\n\n    for (let i = 0; i < n; ++i) {\n        const [currStart, currEnd, currVal] = events[i];\n\n        while (!minHeap.isEmpty()) {\n            const topElement = minHeap.front().element;\n            const [topIdx, topEnd] = topElement;\n\n            if (topEnd < currStart) {\n                maxVal = Math.max(maxVal, events[topIdx][2]);\n                minHeap.dequeue();\n            }\n            else {\n                break;\n            }\n        }\n\n        const sum = maxVal + currVal;\n        maxSum = Math.max(maxSum, sum);\n        minHeap.enqueue([i, currEnd]);\n    }\n\n    return maxSum;\n};",
        "solution_java": "class Solution {\n    public int maxTwoEvents(int[][] events) {\n        Arrays.sort(events, (a, b) -> a[0] - b[0]);\n        int onRight = 0, maxOne = 0, n = events.length;\n        int[] rightMax = new int[n+1];\n        for (int i = n - 1; i >= 0; i--) {\n            int start = events[i][0], end = events[i][1], val = events[i][2];\n            maxOne = Math.max(val, maxOne);\n            rightMax[i] = Math.max(rightMax[i+1], val);\n        }\n        int two = 0;\n        for (int i = 0; i < n; i++) {\n            int start = events[i][0], end = events[i][1], val = events[i][2];\n            int idx = binarySearch(end, events);\n            if (idx < n) {\n                two = Math.max(rightMax[idx] + val, two);\n            }\n        }\n        return Math.max(two, maxOne);\n    }\n\n    public int binarySearch(int end, int[][] arr) {\n        int left = 0, right = arr.length;\n        while (left < right) {\n            int mid = left + (right - left) / 2;\n            if (arr[mid][0] > end) {\n                right = mid;\n            } else {\n                left = mid + 1;\n            }\n        }\n        return left;\n    }\n}",
        "solution_c": "#define ipair pair<int,int>\nclass Solution {\npublic:\n    int maxTwoEvents(vector<vector<int>>& events) {\n\t\n        //sort based on smaller start time\n       sort(events.begin(), events.end());\n        \n        int mx = 0, ans = 0, n = events.size();\n        priority_queue<ipair, vector<ipair>, greater<>> pq;\n        // pq conatins {event_endtime , even_value}\n        // for every event check the max-value of earlier events whose \n        // deadline is less than start time of curr event\n        for(int i=0; i<n; i++)\n        {\n            while(!pq.empty() && pq.top().first < events[i][0])\n                mx = max(mx, pq.top().second), pq.pop();\n            \n            ans = max(ans, mx+events[i][2]);\n            pq.push({events[i][1], events[i][2]});\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Guess Number Higher or Lower II",
        "algo_input": "We are playing the Guessing Game. The game will work as follows:\n\n\n\tI pick a number between&nbsp;1&nbsp;and&nbsp;n.\n\tYou guess a number.\n\tIf you guess the right number, you win the game.\n\tIf you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.\n\tEvery time you guess a wrong number&nbsp;x, you will pay&nbsp;x&nbsp;dollars. If you run out of money, you lose the game.\n\n\nGiven a particular&nbsp;n, return&nbsp;the minimum amount of money you need to&nbsp;guarantee a win regardless of what number I pick.\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 16\nExplanation: The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n&nbsp;   - If this is my number, your total is $0. Otherwise, you pay $7.\n&nbsp;   - If my number is higher, the range is [8,10]. Guess 9.\n&nbsp;       - If this is my number, your total is $7. Otherwise, you pay $9.\n&nbsp;       - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n&nbsp;       - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n&nbsp;   - If my number is lower, the range is [1,6]. Guess 3.\n&nbsp;       - If this is my number, your total is $7. Otherwise, you pay $3.\n&nbsp;       - If my number is higher, the range is [4,6]. Guess 5.\n&nbsp;           - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n&nbsp;           - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n&nbsp;           - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n&nbsp;       - If my number is lower, the range is [1,2]. Guess 1.\n&nbsp;           - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n&nbsp;           - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 0\nExplanation:&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything.\n\n\nExample 3:\n\nInput: n = 2\nOutput: 1\nExplanation:&nbsp;There are two possible numbers, 1 and 2.\n- Guess 1.\n&nbsp;   - If this is my number, your total is $0. Otherwise, you pay $1.\n&nbsp;   - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 200\n\n",
        "solution_py": "class Solution:\n    def getMoneyAmount(self, n):\n                        # For an interval [l,r], we choose a num, which if incorrect still\n                        # allows us to know whether the secret# is in either [l,num-1] or\n                        # [num+1,r]. So, the worst-case (w-c) cost is\n                        #\n                        #      num + max(w-c cost in [l,num-1], w-c cost in [num+1,r])\n                        # \n                        # We do this by recursion and binary search, starting with [1,n].\n\n        @lru_cache(None)              # <-- we cache function results to avoid recomputing them\n        def dp(l = 1, r = n)-> int:\n            if r-l < 1: return 0      # <-- base case for the recursion; one number in [l,r]       \n            ans = 1000                # <-- the answer for n = 200 is 952\n            \n            for choice in range((l+r)//2,r):\n                ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r)))\n\n            return ans\n\n        return dp()",
        "solution_js": "/** https://leetcode.com/problems/guess-number-higher-or-lower-ii/\n * @param {number} n\n * @return {number}\n */\nvar getMoneyAmount = function(n) {\n  // Memo\n  this.memo = new Map();\n  \n  return dp(n, 0, n);\n};\n\nvar dp = function(n, start, end) {\n  let key = `${start}_${end}`;\n  \n  // Base, there is only 1 node on this side of the leg, which mean our guess is always correct and it cost nothing so return 0\n  if (end - start < 2) {\n    return 0;\n  }\n  \n  // Base, there are only 2 nodes on this side of the leg, which mean we only need to pick cheapest guess\n  if (end - start === 2) {\n    // The `start` will always be smaller so pick `start`, add 1 to account for 0 index\n    return start + 1;\n  }\n  \n  // Return from memo\n  if (this.memo.has(key) === true) {\n    return this.memo.get(key);\n  }\n  \n  // Minimum cost\n  let minCost = Infinity;\n  \n  // Try to arrange the tree's left and right leg and find the cost of each leg\n  for (let i = start; i < end; i++) {\n    let left = dp(n, start, i);\n    let right = dp(n, i + 1, end);\n    \n    // Cost of current guess, add 1 to account for 0 index\n    let curr = i + 1;\n    \n    // Update cost of current guess, which is the max of left or right leg\n    curr = Math.max(left + curr, right + curr);\n    \n    // Then update the minimum cost for entire tree\n    minCost = Math.min(minCost, curr);\n  }\n  \n  // Set memo\n  this.memo.set(key, minCost);\n  \n  return minCost;\n};",
        "solution_java": "class Solution {\n    public int getMoneyAmount(int n) {\n        int dp[][]=new int[n+1][n+1];\n        for(int a[]:dp){\n            Arrays.fill(a,-1);\n        }\n        return solve(1,n,dp);\n    }\n    static int solve(int start,int end,int[][] dp){\n    if(start>=end) return 0;\n    if(dp[start][end]!=-1) return dp[start][end];\n    int min=Integer.MAX_VALUE;\n    for(int i=start;i<=end;i++){\n    min=Math.min(min,i+Math.max(solve(start,i-1,dp),solve(i+1,end,dp)));\n    }\n    dp[start][end]=min;\n    return min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> dp;\n\n    int solve(int start, int end)\n    {\n        if(start>= end)\n            return 0;\n\n        if(dp[start][end] != -1)\n            return dp[start][end];\n\n        int ans = 0;\n        int result = INT_MAX;\n        for(int i=start; i<=end; i++)\n        {\n            int left = solve(start,i-1);\n            int right = solve(i+1,end);\n            ans = max(left,right) + i; // this line gurantee to include the money that is needed to win higher values\n            result = min(ans,result);\n        }\n\n        return dp[start][end] = result;\n    }\n\n    int getMoneyAmount(int n) {\n        int ans = 0;\n        dp = vector<vector<int>>(n+1,vector<int>(n+1,-1));\n        return solve(1,n);\n    }\n};"
    },
    {
        "title": "N-th Tribonacci Number",
        "algo_input": "The Tribonacci sequence Tn is defined as follows:&nbsp;\n\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n &gt;= 0.\n\nGiven n, return the value of Tn.\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\n\nExample 2:\n\nInput: n = 25\nOutput: 1389537\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 37\n\tThe answer is guaranteed to fit within a 32-bit integer, ie. answer &lt;= 2^31 - 1.\n",
        "solution_py": "class Solution:\n    def tribonacci(self, n: int, q={}) -> int:\n        if n<3:\n            q[0]=0 #Initialize first 3 values \n            q[1]=1\n            q[2]=1\n        if n not in q:  #Have faith that last 3 calls will give the answer :)\n            q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci(n-3,q)\n        return q[n]",
        "solution_js": "// Recursive and Memoiztion approach\nvar tribonacci = function(n, cache = {}) {\n    if(n in cache) return cache[n]\n\n    //Start of Base Cases\n    if(n == 0) return 0\n    if (n == 1 || n == 2) return 1;\n    // End Of Base Cases\n    \n    // Caching the result\n    cache[n] = tribonacci(n - 1, cache) + tribonacci(n - 2, cache) + tribonacci(n - 3, cache);\n    \n    return cache[n]; \n};\n\n// Tabulation Approach\nvar tribonacci = function(n) {\n    // Create the Table;\n    const table = Array(n + 1).fill(0);\n    table[1] = 1;\n    for(let i =0;i<=n;i++){\n        //Iterate over the table and increase the values respectively\n        table[i+1] += table[i]\n        table[i+2] += table[i]\n        table[i+3] += table[i]\n    }\n    return table[n]\n};",
        "solution_java": "class Solution {\n    public int tribonacci(int n) {\n        if(n==0)\n            return 0;\n        if(n==1)\n            return 1;\n        if(n==2)\n            return 1;\n        int p1=1;\n        int p2=1;\n        int p3=0;\n        int cur=0;\n        for(int i=3;i<=n;i++)\n        {\n            cur=p1+p2+p3;\n            p3=p2;\n            p2=p1;\n            p1=cur;\n        }\n        return cur;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int tribonacci(int n) {\n        if(n<2)\n            return n;\n        \n        int prev3 = 0;\n        int prev2 = 1;\n        int prev1 = 1;\n        \n        for(int i = 3; i<= n ; i++)\n        {\n            int ans  = prev1+ prev2+prev3;\n            prev3 = prev2;\n            prev2 = prev1;\n            prev1 = ans;\n        }\n        \n        return prev1;\n    }\n};"
    },
    {
        "title": "Find Minimum in Rotated Sorted Array II",
        "algo_input": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:\n\n\n\t[4,5,6,7,0,1,4] if it was rotated 4 times.\n\t[0,1,4,4,5,6,7] if it was rotated 7 times.\n\n\nNotice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n\nGiven the sorted rotated array nums that may contain duplicates, return the minimum element of this array.\n\nYou must decrease the overall operation steps as much as possible.\n\n&nbsp;\nExample 1:\nInput: nums = [1,3,5]\nOutput: 1\nExample 2:\nInput: nums = [2,2,2,0,1]\nOutput: 0\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 5000\n\t-5000 &lt;= nums[i] &lt;= 5000\n\tnums is sorted and rotated between 1 and n times.\n\n\n&nbsp;\nFollow up: This problem is similar to&nbsp;Find Minimum in Rotated Sorted Array, but&nbsp;nums may contain duplicates. Would this affect the runtime complexity? How and why?\n\n&nbsp;\n",
        "solution_py": "class Solution:\n    def findMin(self, nums: List[int]) -> int:\n        return min(nums)\n        ",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMin = function(nums) {\n    let min = Infinity;\n    let l = 0;\n    let r = nums.length - 1;\n    while (l <= r) {\n        const m = Math.floor((l + r) / 2);\n\n        // Eliminate dupes ......................... only difference from #153\n        while (l < m && nums[l] === nums[m]) l++;\n        while (r > m && nums[r] === nums[m]) r--;\n        // .........................................\n\n        // locate the sorted side, the opposite side has the break point\n        // min should be on the side that has the break point, so continue search on that side\n        if (nums[l] <= nums[m]) {\n            // left side is sorted (or l & m are the same index)\n            // brake is on right side\n            min = Math.min(min, nums[l]);\n            l = m + 1;\n        } else {\n            // right side is sorted\n            // break is on left side\n            min = Math.min(min, nums[m]);\n            r = m - 1;\n        }\n    }\n    return min;\n};",
        "solution_java": "class Solution {\n    public int findMin(int[] nums) {\n        int l = 0;\n        int h = nums.length - 1;\n        while (l < h) {\n            while (l < h && nums[l] == nums[l + 1])\n                ++l;\n            while (l < h && nums[h] == nums[h - 1])\n                --h;\n            int mid = l + (h - l) / 2;\n            if (nums[mid] > nums[h]) { // smaller elements are in the right side\n                l = mid + 1;\n            } else {\n                h = mid;\n            }\n        }\n        return nums[l];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findMin(vector<int>& nums) {\n        int l=0,h=nums.size()-1;\n        while(l<h){\n            int m=l+(h-l)/2;\n            if(nums[m]<nums[h]) h=m;\n            else if(nums[m]>nums[h]) l=m+1;\n            else h--;\n        }\n        return nums[h];\n    }\n};"
    },
    {
        "title": "Partition Array into Disjoint Intervals",
        "algo_input": "Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:\n\n\n\tEvery element in left is less than or equal to every element in right.\n\tleft and right are non-empty.\n\tleft has the smallest possible size.\n\n\nReturn the length of left after such a partitioning.\n\nTest cases are generated such that partitioning exists.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,0,3,8,6]\nOutput: 3\nExplanation: left = [5,0,3], right = [8,6]\n\n\nExample 2:\n\nInput: nums = [1,1,1,0,6,12]\nOutput: 4\nExplanation: left = [1,1,1,0], right = [6,12]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 106\n\tThere is at least one valid answer for the given input.\n\n",
        "solution_py": "class Solution:\n    def partitionDisjoint(self, nums: List[int]) -> int:\n        prefix = [nums[0] for _ in range(len(nums))]\n        suffix = [nums[-1] for _ in range(len(nums))]\n        for i in range(1, len(nums)):\n            prefix[i] = max(prefix[i-1], nums[i-1])\n        for i in range(len(nums)-2, -1, -1):\n            suffix[i] = min(suffix[i+1], nums[i+1])\n        for i in range(0, len(nums)-1):\n            if prefix[i] <= suffix[i]:\n                return i+1",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar partitionDisjoint = function(nums) {\n    let n = nums.length;\n    let leftMax = Array(n).fill(0), rightMin = Array(n).fill(0);\n    let left = 0, right = n- 1;\n    \n    for(let i = 0, j = n - 1;i<n, j>=0 ;i++,j--){\n        leftMax[i] = Math.max(nums[i], !i ? -Infinity : leftMax[i-1]);\n        rightMin[j] = Math.min(nums[j], j === n - 1 ? Infinity : rightMin[j+1]);\n    }\n    \n    for(let i = 0;i<n-1;i++){\n        if(leftMax[i] <= rightMin[i+1]){\n            return i + 1;\n        }\n    }\n \n};",
        "solution_java": "class Solution {\n    public int partitionDisjoint(int[] nums) {\n        int mts = nums[0]; // max till scan\n        int mtp = nums[0]; // max till partition\n        int idx = 0;\n        \n        for(int i=1; i<nums.length; i++) {\n            int val = nums[i];\n            if(val < mtp) {\n                idx = i;\n                mtp = mts;\n            }\n            \n            mts = Math.max(mts, val);\n        }\n        \n        return idx + 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> tree;\n    void build(vector<int> &nums) {\n        int n=nums.size();\n        for(int i=0 ; i<nums.size(); i++) tree[i+n]=nums[i];\n        for(int i=n-1 ; i>0 ; i--) tree[i] = min(tree[i<<1],tree[i<<1|1]);\n    }\n\n    int query(int l, int r, int n) {\n        l+=n,r+=n;\n        int ans = INT_MAX;\n        while(l<r) {\n            if(l&1) ans = min(ans,tree[l++]);\n            if(r&1) ans = min(ans,tree[--r]);\n            l>>=1; r>>=1;\n        }\n        return ans;\n    }\n\n    int partitionDisjoint(vector<int>& nums) {\n        int n=nums.size();\n        int mx=-1 ;\n        tree.resize(2*n,INT_MAX); build(nums);\n        for(int left=0; left<n ; left++) {\n            mx = max(mx,nums[left]);\n            if(query(left+1,n,n) >= mx) return left+1;\n        }\n        return n;\n    }\n};"
    },
    {
        "title": "Stone Game II",
        "algo_input": "Alice and Bob continue their&nbsp;games with piles of stones.&nbsp; There are a number of&nbsp;piles&nbsp;arranged in a row, and each pile has a positive integer number of stones&nbsp;piles[i].&nbsp; The objective of the game is to end with the most&nbsp;stones.&nbsp;\n\nAlice&nbsp;and Bob take turns, with Alice starting first.&nbsp; Initially, M = 1.\n\nOn each player's turn, that player&nbsp;can take all the stones in the first X remaining piles, where 1 &lt;= X &lt;= 2M.&nbsp; Then, we set&nbsp;M = max(M, X).\n\nThe game continues until all the stones have been taken.\n\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice&nbsp;can get.\n\n&nbsp;\nExample 1:\n\nInput: piles = [2,7,9,4,4]\nOutput: 10\nExplanation:  If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. \n\n\nExample 2:\n\nInput: piles = [1,2,3,4,5,100]\nOutput: 104\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= piles.length &lt;= 100\n\t1 &lt;= piles[i]&nbsp;&lt;= 104\n\n",
        "solution_py": "class Solution:\n    def stoneGameII(self, piles: List[int]) -> int:\n        n = len(piles)\n        dp = {} \n        def recursion(index,M):\n            # if we reached to the end we cannot score any value\n            if index == n:\n                return 0\n            # we search if we have solved the same case earlier\n            if (index,M) in dp:\n                return dp[(index,M)] \n            # total remaining score is the sum of array from index to the end\n            total = sum(piles[index:])           \n            # if we can take the complete array it is the best choice\n            if index + 2*M >= n :return total\n            # my_score is the score we are getting as the player who is playing\n            my_score = 0\n            for x in range(index,index+2*M):\n                # opponent score will be calculated by next recursion\n                opponent_score = recursion(x+1,max(M,x-index+1))\n                # my_score is the remaining value of total - opponent_score\n                my_score = max(my_score,total - opponent_score)          \n            # this is memoization part\n            dp[(index,M)] = my_score\n            # return the score\n            return my_score\n        \n        return recursion(0,1)",
        "solution_js": "var stoneGameII = function(piles) {\n  const length = piles.length;\n  const dp = [...Array(length + 1).fill(null)].map((_) =>\n    Array(length + 1).fill(0)\n  );\n  const sufsum = new Array(length + 1).fill(0);\n  for (let i = length - 1; i >= 0; i--) {\n    sufsum[i] = sufsum[i + 1] + piles[i];\n  }\n  for (let i = 0; i <= length; i++) {\n    dp[i][length] = sufsum[i];\n  }\n  for (let i = length - 1; i >= 0; i--) {\n    for (let j = length - 1; j >= 1; j--) {\n      for (let X = 1; X <= 2 * j && i + X <= length; X++) {\n        dp[i][j] = Math.max(dp[i][j], sufsum[i] - dp[i + X][Math.max(j, X)]);\n      }\n    }\n  }\n  return dp[0][1];\n};",
        "solution_java": "class Solution {\n    public int stoneGameII(int[] piles) {\n        Map<String, Integer> memo = new HashMap<>();\n        int diff = stoneGame(piles,1,0,0,memo);\n        int totalSum = 0;\n        for(int ele: piles)\n            totalSum+=ele;\n        return (diff+totalSum)/2;\n    }\n\n    public int stoneGame(int[] piles, int M, int index, int turn,Map<String, Integer> memo )\n    {\n        if(index >= piles.length)\n            return 0;\n        if(memo.containsKey(index+\"-\"+M+\"-\"+turn))\n            return memo.get(index+\"-\"+M+\"-\"+turn);\n        int score=0,maxScore=Integer.MIN_VALUE;\n        // Alice's turn\n        if(turn == 0)\n        {\n            for(int X=1;X<=2*M && index+X-1<piles.length;X++)\n            {\n                score += piles[index+X-1];\n                maxScore= Math.max(maxScore,stoneGame(piles,Math.max(X,M),index+X,1,memo)+score);\n            }\n            memo.put(index+\"-\"+M+\"-\"+turn,maxScore);\n            return maxScore;\n        }\n        // Bob's turn\n        int minScore=Integer.MAX_VALUE;\n        for(int X=1;X<=2*M && index+X-1<piles.length;X++)\n        {\n            score += piles[index+X-1];\n            minScore = Math.min(minScore, stoneGame(piles,Math.max(X,M),index+X,0,memo) - score ) ;\n        }\n        memo.put(index+\"-\"+M+\"-\"+turn,minScore);\n        return minScore;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    int dp[103][103][2];\n    int rec(int i,int m,int p,vector<int>& piles){\n        if(i==piles.size()) return 0;\n        if(dp[i][m][p]!=-1) return dp[i][m][p];\n        int cnt = 0,ans=INT_MIN,n=piles.size();\n        for(int j=i;j<min(n,i+2*m);j++){\n            cnt += piles[j];\n            ans =max(ans, cnt - rec(j+1,max(j-i+1,m),1-p,piles));\n        }\n        return dp[i][m][p] = ans;\n    }\n    int stoneGameII(vector<int>& piles) {\n        int sum = 0;\n        memset(dp,-1,sizeof(dp));\n        for(auto i:piles) sum += i;\n        return (sum + rec(0,1,0,piles))/2;\n    }\n};"
    },
    {
        "title": "Substring with Concatenation of All Words",
        "algo_input": "You are given a string s and an array of strings words. All the strings of words are of the same length.\n\nA concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.\n\n\n\tFor example, if words = [\"ab\",\"cd\",\"ef\"], then \"abcdef\", \"abefcd\", \"cdabef\", \"cdefab\", \"efabcd\", and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words.\n\n\nReturn the starting indices of all the concatenated substrings in s. You can return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.\n\n\nExample 2:\n\nInput: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\nOutput: []\nExplanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.\n\n\nExample 3:\n\nInput: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\nOutput: [6,9,12]\nExplanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\t1 &lt;= words.length &lt;= 5000\n\t1 &lt;= words[i].length &lt;= 30\n\ts and words[i] consist of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def findSubstring(self, s: str, words: List[str]) -> List[int]:\n        req={}\n        for i in words:\n            req[i]=1+req.get(i,0)\n        l=0\n        r=len(words)*len(words[0])\n        ans=[]\n\n        while r<len(s)+1:\n            i=0\n            curr={}\n            left, right= l, l+len(words[0])\n            while right<l+len(words)*len(words[0])+1:\n                x=s[left:right]\n                # print(x)\n                if x in req.keys():\n                    curr[x]= 1+ curr.get(x,0)\n                left=right\n                right=right+len(words[0])\n            if req==curr:\n                ans.append(l)\n            l=l+1\n            r=r+1\n        return ans",
        "solution_js": "var findSubstring = function(s, words) {\n    \n    let res = [];\n\n    let wordLength = words[0].length;\n    let wordCount = words.length;\n    let len = wordCount * wordLength; //Length of sliding window\n    \n    let map = {}\n    \n    for (let word of words) map[word] = map[word] + 1 || 1; //Hash word freq\n\n  \tfor (let i = 0; i < s.length - len + 1; i++) {\n            let sub = s.slice(i, i + len); //Generate substring of sliding window length\n            if (isConcat(sub, map, wordLength)) res.push(i)\n        }\n    \n    return res;\n};\n\nfunction isConcat(sub,map,wordLength){\n    \n    let seen = {};\n    for (let i = 0; i < sub.length; i+=wordLength) {\n        let word = sub.slice(i,i + wordLength);\n        seen[word] = seen[word] + 1 || 1\n    }\n    \n    for(let key in map){\n        if(map[key] !== seen[key]) return false; //Word freq must match between map and seen\n    }\n    return true;\n}```",
        "solution_java": "class Solution {\n    public List<Integer> findSubstring(String s, String[] words) {\n\n        HashMap<String, Integer> input = new HashMap<>();\n        int ID = 1;\n        HashMap<Integer, Integer> count = new HashMap<>();\n        for(String word: words) {\n            if(!input.containsKey(word))\n                input.put(word, ID++);\n            int id = input.get(word);\n            count.put(id,count.getOrDefault(id,0)+1);\n\n        }\n        int len = s.length();\n        int wordLen = words[0].length();\n        int numWords = words.length;\n        int windowLen = wordLen*numWords;\n        int lastIndex = s.length()-windowLen;\n\n        int curWordId[] = new int[len];\n        String cur = \" \"+s.substring(0,wordLen-1);\n\n        //Change to int array\n        for(int i = 0; i< (len-wordLen+1); i++) {\n            cur = cur.substring(1, cur.length())+s.charAt(i+wordLen-1);\n            if(input.containsKey(cur)){\n                curWordId[i] = input.get(cur);\n            } else {\n                curWordId[i] = -1;\n            }\n        }\n        List<Integer> res = new ArrayList<>();\n\n        //compare using int make it faster 30 times in each comparison\n        for(int i = 0; i<= lastIndex; i++) {\n\n            HashMap<Integer, Integer> winMap = new HashMap<>();\n            for(int j = 0; j < windowLen && curWordId[i] != -1; j+=wordLen) {\n\n                int candidate = curWordId[j+i];\n\n                if(!count.containsKey(candidate))\n                    break;\n                else{\n                    winMap.put(candidate, winMap.getOrDefault(candidate, 0)+1);\n                }\n                if(winMap.get(candidate) > count.get(candidate))\n                    break;\n\n                if(j == (windowLen - wordLen) && winMap.size() == count.size()){\n                    res.add(i);\n\n                }\n\n            }\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findSubstring(string s, vector<string>& words) {\n        int n = words[0].length();\n        int slen = s.length();\n        int len = slen - n*words.size();\n        vector<int> ans;\n        if( len < 0) return ans;\n        string t;\n        unordered_map<string, int> mp;\n        for(auto i = 0; i < words.size(); ++i) ++mp[words[i]];\n\n        for(int i = 0; i<= len; ++i){\n            t = s.substr(i, n);\n            if(mp.find(t) != mp.end()){\n                unordered_map<string, int> smp;\n                ++smp[t];\n                int flag = 1;\n                for(int j = i+n, k = 1; k < words.size() && j+n <= slen; ++k, j = j + n){\n                    t = s.substr(j, n);\n                    if(mp.find(t) != mp.end()) ++smp[t];\n                    else {\n                        flag = 0;\n                        break;\n                    }\n                }\n                if(flag && smp == mp) ans.push_back(i);\n            }\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Happy String",
        "algo_input": "A string s is called happy if it satisfies the following conditions:\n\n\n\ts only contains the letters 'a', 'b', and 'c'.\n\ts does not contain any of \"aaa\", \"bbb\", or \"ccc\" as a substring.\n\ts contains at most a occurrences of the letter 'a'.\n\ts contains at most b occurrences of the letter 'b'.\n\ts contains at most c occurrences of the letter 'c'.\n\n\nGiven three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string \"\".\n\nA substring is a contiguous sequence of characters within a string.\n\n&nbsp;\nExample 1:\n\nInput: a = 1, b = 1, c = 7\nOutput: \"ccaccbcc\"\nExplanation: \"ccbccacc\" would also be a correct answer.\n\n\nExample 2:\n\nInput: a = 7, b = 1, c = 0\nOutput: \"aabaa\"\nExplanation: It is the only correct answer in this case.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= a, b, c &lt;= 100\n\ta + b + c &gt; 0\n\n",
        "solution_py": "class Solution:\n\tdef longestDiverseString(self, a: int, b: int, c: int) -> str:\n\t\tpq = []\n\t\tif a > 0: heapq.heappush(pq,(-a,'a'))        \n\t\tif b > 0: heapq.heappush(pq,(-b,'b'))        \n\t\tif c > 0: heapq.heappush(pq,(-c,'c'))\n\n\t\tans = ''\n\t\twhile pq:\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif len(ans)>1 and ans[-1] == ans[-2] == ch:\n\t\t\t\tif not pq: break\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\n\t\treturn ans",
        "solution_js": "var longestDiverseString = function(a, b, c) {\n    let str = '', aCount = 0, bCount = 0, cCount = 0;\n    let len = a + b + c;\n    for(let i = 0; i < len; i++) {\n        if (a >= b && a >= c && aCount != 2 || bCount == 2 && a > 0 || cCount == 2 && a > 0) {\n            adjustCounts('a', aCount+1, 0, 0);\n            a--;\n        } else if (b >= a && b >= c && bCount != 2 || aCount == 2 && b > 0 || cCount == 2 && b > 0) {\n            adjustCounts('b', 0, bCount+1, 0);\n            b--;\n        } else if (c >= a && c >= b && cCount != 2 || bCount == 2 && c > 0|| aCount == 2 && c > 0) {\n            adjustCounts('c', 0, 0 , cCount+1);\n            c--;\n        }\n    }\n\n    function adjustCounts(letter, newA, newB, newC){\n        aCount = newA;\n        bCount = newB;\n        cCount = newC;\n        str += letter;\n    }\n\n    return str;\n};",
        "solution_java": "/*\nThe idea behid this problem\n1. Here we start by taking the size as the sum of a, b, c.\n2. Then we use 3 variables A, B, C to count the occurance of a, b, c.\n3. Now we iterate until the size, and \n    -> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.\n    \n4. Finally return the string.\n*/\nclass Solution {\n    public String longestDiverseString(int a, int b, int c) {\n        int totalSize = a + b + c;\n        int A = 0;\n        int B = 0;\n        int C = 0;\n        StringBuilder sb = new StringBuilder();\n        for (int i=0; i<totalSize; i++) {\n            // checks a is largest and its count still < 2 or B and C =2 and there are still a that can be added \n            if ((a>=b && a>=c && A<2) || (B==2 && a>0) || (C==2 && a>0)) {\n                sb.append(\"a\");\n                a -= 1;\n                A += 1;\n                B = 0;\n                C = 0;\n            }\n            // check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be added\n            else if ((b>=a && b>=c && B<2) || (A==2 && b>0) || (C==2 && b>0)) {\n                sb.append(\"b\");\n                b -= 1;\n                B += 1;\n                A = 0;\n                C = 0;\n            }\n            // checks c is largest and its count still < 2 or B and A = 2 and there are still c that can be added\n            else if ((c>=a && c>=b && C<2) || (A==2 && c>0) || (B==2 && c>0)) {\n                sb.append(\"c\");\n                c -= 1;\n                C += 1;\n                A = 0;\n                B = 0;\n            }\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\t#define f first    \n\t#define s second\n\tstring longestDiverseString(int a, int b, int c) {\n\t\tpriority_queue<pair<int,char>> pq;\n\t\tif(a>0)pq.push({a,'a'});        \n\t\tif(b>0)pq.push({b,'b'});        \n\t\tif(c>0)pq.push({c,'c'});\n\n\t\tstring ans  = \"\";\n\t\twhile(!pq.empty()){\n\t\t\tauto t = pq.top(); pq.pop();\n\t\t\tint c = t.f;\n\t\t\tchar ch = t.s;\n\t\t\tif(ans.size() > 1 && ans[ans.size()-1]==ch && ch == ans[ans.size()-2]) {\n\t\t\t\tif(pq.empty())break;\n\t\t\t\tauto t = pq.top(); pq.pop();\n\t\t\t\tint c2 = t.f;\n\t\t\t\tchar ch2 = t.s;\n\t\t\t\tans += ch2;\n\t\t\t\tc2-=1;\n\t\t\t\tif(c2)pq.push({c2,ch2});\n\t\t\t}else{\n\t\t\t\tans += ch;\n\t\t\t\tc-=1;\n\t\t\t}\n\t\t\tif(c)pq.push({c,ch});\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Coordinate With Maximum Network Quality",
        "algo_input": "You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.\n\nYou are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.\n\nThe signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.\n\nReturn the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.\n\nNote:\n\n\n\tA coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:\n\n\t\n\t\tx1 &lt; x2, or\n\t\tx1 == x2 and y1 &lt; y2.\n\t\n\t\n\t⌊val⌋ is the greatest integer less than or equal to val (the floor function).\n\n\n&nbsp;\nExample 1:\n\nInput: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput: [2,1]\nExplanation: At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.\n\nExample 2:\n\nInput: towers = [[23,11,21]], radius = 9\nOutput: [23,11]\nExplanation: Since there is only one tower, the network quality is highest right at the tower's location.\n\n\nExample 3:\n\nInput: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput: [1,2]\nExplanation: Coordinate (1, 2) has the highest network quality.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= towers.length &lt;= 50\n\ttowers[i].length == 3\n\t0 &lt;= xi, yi, qi &lt;= 50\n\t1 &lt;= radius &lt;= 50\n\n",
        "solution_py": "class Solution:\n    def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n        return max(\n            (\n                (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius),\n                 [x, y]) for x in range(51) for y in range(51)\n            ),\n            key=lambda x: (x[0], -x[1][0], -x[1][1])\n        )[1]",
        "solution_js": "var bestCoordinate = function(towers, radius) {\n    const n = towers.length;\n    const grid = [];\n    \n    for (let i = 0; i <= 50; i++) {\n        grid[i] = new Array(51).fill(0);\n    }\n    \n    \n    for (let i = 0; i < n; i++) {\n        const [x1, y1, quality1] = towers[i];\n        \n        for (let x2 = 0; x2 <= 50; x2++) {\n            for (let y2 = 0; y2 <= 50; y2++) {\n                const dist = Math.sqrt((x1 - x2)**2 + (y1 - y2)**2);\n\n                if (dist > radius) continue;\n\n                const network = Math.floor(quality1 / (1 + dist));\n                \n                grid[x2][y2] += network;\n            }\n        }\n    }\n    \n\t\n    let maxX = 0;\n    let maxY = 0;\n    let maxVal = grid[0][0];\n    \n    for (let i = 0; i <= 50; i++) {\n        for (let j = 0; j <= 50; j++) {\n            const val = grid[i][j];\n            \n            if (val > maxVal) {\n                maxVal = val;\n                maxX = i;\n                maxY = j;\n            }\n            else if (val === maxVal) {\n                if (i < maxX || (i === maxX && j < maxY)) {\n                    maxVal = val;\n                    maxX = i;\n                    maxY = j;\n                }\n            }\n        }\n    }\n    \n    return [maxX, maxY];\n};",
        "solution_java": "class Solution {\n    public int[] bestCoordinate(int[][] towers, int radius) {\n        int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0;\n        int[] res = new int[2];\n        for(int[] t : towers) {\n            minX = Math.min(minX, t[0]);\n            maxX = Math.max(maxX, t[0]);\n            minY = Math.min(minY, t[1]);\n            maxY = Math.max(maxY, t[1]);\n        }\n        for(int i = minX; i <= maxX; i++) {\n            for(int j = minY; j <= maxY; j++) {\n                int sum = 0;\n                for(int[] t : towers) {\n                    int d = (t[0] - i) *(t[0] - i) + (t[1] - j) *(t[1] - j);\n                    if(d <= radius * radius) {\n                        sum += t[2] /(1+ Math.sqrt(d));    \n                    }\n                }\n                if(sum > max) {\n                    max = sum;\n                    res = new int[]{i,j};\n                }\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> bestCoordinate(vector<vector<int>>& towers, int radius) {\n        int n = towers.size();\n        int sum;\n        int ans = 0;\n        pair<int,int> ansCoor;\n\t\t// Calculate for every 'x's and 'y's \n        for(int x = 0; x <= 50; x++){\n            for(int y = 0; y <= 50; y++){\n                sum = 0;\n                for(const auto it : towers){\n                    int xa = it[0];\n                    int ya = it[1];\n                    int qa = it[2];\n\t\t\t\t\t// get the distance between the two points\n                    int distance = pow(x - xa, 2) + pow(y - ya, 2);\n                    if(distance > radius * radius) {\n                        continue;\n                    }\n\t\t\t\t\t// increment the quality value\n                    sum += (int)(qa / (1 + sqrt(distance)));\n                }\n\t\t\t\t// store the maximum ans\n                if(sum > ans){\n                    ans = sum;\n                    ansCoor = {x,y};\n                }\n            }\n        }\n        return vector<int>{{ansCoor.first, ansCoor.second}};\n    }\n};"
    },
    {
        "title": "Number of Steps to Reduce a Number in Binary Representation to One",
        "algo_input": "Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:\n\n\n\t\n\tIf the current number is even, you have to divide it by 2.\n\t\n\t\n\tIf the current number is odd, you have to add 1 to it.\n\t\n\n\nIt is guaranteed that you can always reach one for all test cases.\n\n&nbsp;\nExample 1:\n\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14.&nbsp;\nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.&nbsp; \nStep 5) 4 is even, divide by 2 and obtain 2.&nbsp;\nStep 6) 2 is even, divide by 2 and obtain 1.&nbsp; \n\n\nExample 2:\n\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.&nbsp; \n\n\nExample 3:\n\nInput: s = \"1\"\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length&nbsp;&lt;= 500\n\ts consists of characters '0' or '1'\n\ts[0] == '1'\n\n",
        "solution_py": "class Solution:\n    def numSteps(self, s: str) -> int:\n        size = len(s)\n        if size == 1:\n            return 0\n        one_group = s.split('0')\n        zero_group = s.split('1')\n\n        \n        if size - len(zero_group[-1]) == 1:\n            return size - 1\n        else:\n            return size + len(one_group) - len(zero_group[-1])",
        "solution_js": "var numSteps = function(s) {\n    let res = 0;\n    s = s.split(\"\");\n    while(s.length>1){\n        if(s[s.length-1]===\"0\") s.pop();\n        else plusone(s);\n        res++;\n    }\n    return res;\n};\nvar plusone = function(p) {\n    p.unshift(\"0\");\n    let i = p.length-1;\n    p[i] = 1+(+p[i]);\n    while(p[i]===2){\n        p[i-1] = 1+(+p[i-1]);\n        i--;\n        p[i+1] = \"0\";\n    }\n    if(p[0]===\"0\") p.shift();\n    return p;\n};",
        "solution_java": "class Solution \n{\n    public int numSteps(String s)\n    {\n        int countSteps = 0;\n        int carry = 0;\n        for(int i = s.length()-1;i>=1;i--)\n        {\n            int rightMostBit = s.charAt(i)-'0';\n            if((rightMostBit+carry) == 1)\n            {\n                carry=1;\n                countSteps += 2;\n            }\n            else\n            {\n                countSteps++;\n            }\n        }\n        return countSteps+carry;\n    }\n} ",
        "solution_c": "class Solution {\npublic:\n    int numSteps(string s) {\n        int n=0;\n        bool carry = false;\n        int steps = 0;\n        if(s == \"1\") return 0;\n        while(s.length() > 0){\n            int i = s.length()-1;\n            if(carry){\n                if(s[i] == '1'){\n                    carry = true; s[i] = '0';\n                }else{\n                    s[i] = '1'; carry = false;\n                }\n            }\n            if(s[i] == '0'){ s.pop_back(); steps++;}\n            else{carry = true; s.pop_back(); steps += 2;}\n            if(s == \"1\"){\n                if(carry) steps++;\n                break;\n            }\n        }\n        return steps;\n    }\n};"
    },
    {
        "title": "Maximum Number of Points with Cost",
        "algo_input": "You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.\n\nTo gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.\n\nHowever, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 &lt;= r &lt; m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.\n\nReturn the maximum number of points you can achieve.\n\nabs(x) is defined as:\n\n\n\tx for x &gt;= 0.\n\t-x for x &lt; 0.\n\n\n&nbsp;\nExample 1: \n\nInput: points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput: 9\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.\n\n\nExample 2:\n\nInput: points = [[1,5],[2,3],[4,2]]\nOutput: 11\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == points.length\n\tn == points[r].length\n\t1 &lt;= m, n &lt;= 105\n\t1 &lt;= m * n &lt;= 105\n\t0 &lt;= points[r][c] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def maxPoints(self, points: List[List[int]]) -> int:\n        m, n = len(points), len(points[0])\n        \n        for i in range(m - 1):\n            for j in range(1, n):\n                points[i][j] = max(points[i][j], points[i][j - 1] - 1)\n            \n            for j in range(n - 2, -1, -1):\n                points[i][j] = max(points[i][j], points[i][j + 1] - 1)\n            \n            for j in range(n):\n                points[i + 1][j] += points[i][j]\n        \n        return max(points[m - 1])",
        "solution_js": "var maxPoints = function(points) {\n    let prev = points[0];\n    let curr = Array(points[0].length);\n\n    for(let i = 1; i<points.length; i++){\n\n        // from left to right;\n        for(let j = 0, maxAdd=0; j<points[0].length;j++){\n            maxAdd = Math.max(maxAdd-1, prev[j]);\n            curr[j] = points[i][j] + maxAdd;\n        }\n\n        for(let j = points[0].length-1, maxAdd = 0; j>=0; j--){\n            maxAdd = Math.max(maxAdd-1, prev[j]);\n            curr[j] = Math.max(curr[j], points[i][j] + maxAdd)\n        }\n\n        prev = curr;\n        curr = Array(points[0].length)\n\n    }\n    return Math.max(...prev)\n};",
        "solution_java": "/* \n   -> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get \n\tadded to next values from next row.\n\n   -> conditions to update values in frame \n\t\t* we will keep only those values which will contribute maximum in next row addition\n\n\te.g-->\n\t\tpoints --->[[1,2,3]\n\t\t\t\t\t[1,5,1]\n\t\t\t\t\t[3,1,1]]\n\n\t\tfor 1st iteration frame <--- [1,2,3] rest of two loops will not affect frame so in \n\t\t2nd itreration frame <--------[2,7,4] <-------- [1,2,3] + [1,5,1]\n\t\tnow we have to update frame so it can give max values for next row addition\n\t\t 0 1 2   \n\t\t[2,7,4] \n\t\t  \\ \n\t\t[2,7,4]  check left to right--> just check value at index 0 can contribute more than curr_sum at index 1 but to do so it has to give up (1-0) a penalty,here 7 can contribute more than 2-1=1 in next sum.\n\t\t2 7 4        now check for index 2,where (7-1)>4\n\t\t   \\\n\t\t2 7 6\n\t\t\t\t\tnow do in reverse,can 6 contribute more than 7 no ( 7 >(6-1) )  \n\t\t\t\t\tcan 7 contibute more than 2 yes (2<(7-1)),so now  frame will be\n\t\t6 7 6       now we can cal optimal-frame for rest of the matrix.\n\t+   3 1 1\n ------------------- \n\t\t9 8 7  check left to right--> can 9 can contibute 8>(9-1) no; can 8 can contibute for index 2 no simlier for right to left\n*/\n\nclass Solution {\n\tpublic long maxPoints(int[][] points) {\n\t\tlong[] frame = new long[points[0].length];\n\n\t\tfor (int i = 0; i < points.length; i++) {\n\t\t\tfor (int j = 0; j <frame.length; j ++) frame[j] += points[i][j];\n\n\t\t\tfor (int j = 1; j < frame.length; j ++) frame[j] = Math.max(frame[j], frame[j - 1] - 1);\n\n\t\t\tfor (int j=frame.length-2;j>=0;j--) frame[j] = Math.max(frame[j], frame[j + 1] - 1);\n\n\t\t\tfor(long k:frame) System.out.println(k);\n\t\t}\n\n\n\t\tlong ans = 0;\n\t\tfor (int i = 0; i < frame.length; i ++) {\n\t\t\tans = Math.max(ans, frame[i]);\n\t\t}\n\t\treturn ans;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    long long maxPoints(vector<vector<int>>& points) {\n        vector<vector<long long>> dp(points.size(), vector<long long>(points[0].size(), -1));\n        \n        for (int i = 0; i < points[0].size(); ++i) {\n            dp[0][i] = points[0][i];\n        }\n        \n        for (int i = 1; i < points.size(); ++i) {\n            for (int j = 0; j < points[i].size(); ++j) {\n                for (int k = 0; k < points[i].size(); ++k) {\n                    dp[i][j] = max(dp[i][j], dp[i - 1][k] - abs(k - j) + points[i][j]);\n                }\n            }\n        }\n        \n        long long max_ans = -1;\n        for (const auto v : dp.back()) {\n            max_ans = max(max_ans, v);\n        }\n        \n        return max_ans;\n    }\n};"
    },
    {
        "title": "Monotone Increasing Digits",
        "algo_input": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x &lt;= y.\n\nGiven an integer n, return the largest number that is less than or equal to n with monotone increasing digits.\n\n&nbsp;\nExample 1:\n\nInput: n = 10\nOutput: 9\n\n\nExample 2:\n\nInput: n = 1234\nOutput: 1234\n\n\nExample 3:\n\nInput: n = 332\nOutput: 299\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def monotoneIncreasingDigits(self, n: int) -> int:\n        num = list(str(n))\n        for i in range(len(num)-1):\n            # Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return\n            # However, there is the case that num[i-1]==num[i], which will make num[i]-1<num[i-1]\n            # So, traverse back to find the num that its num[i-1] != num[i](to make sure num[i-1]<=num[i]-1), then do step1 and return\n            if num[i] > num[i+1]:\n                while i >= 1 and num[i-1] == num[i]:\n                    i -= 1\n                num[i] = chr(ord(num[i])-1)\n                return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))\n        return n",
        "solution_js": "var monotoneIncreasingDigits = function(n) {\n    let arr = String(n).split('');\n    for (let i=arr.length-2; i>=0; i--) {\n        if (arr[i]>arr[i+1]) {\n            arr[i]--;\n            for(let j=i+1; j<arr.length; j++) arr[j]='9';\n        }\n    }\n    return Number(arr.join(''));\n};",
        "solution_java": "class Solution {\n    public int monotoneIncreasingDigits(int n) {\n        int position;\n        int digitInTheNextPosition;\n        while ((position = getThePositionNotSatisfied(n)) != -1) {\n            digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;\n            n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);\n            n -= n % Math.pow(10, position);\n            n += Math.pow(10, position) - 1;\n        }\n        return n;\n    }\n\n    public int getThePositionNotSatisfied(int n) {\n        int k = 10;\n        int position = 0;\n        while (n > 0) {\n            if (k < n % 10) {\n                return position;\n            } else {\n                k = n % 10;\n                n /= 10;\n                position++;\n            }\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int monotoneIncreasingDigits(int n) {\n            if(n < 10) return n;\n\n            string s = to_string(n);\n\n            for(int i = s.size() - 2; i >= 0; i--) {\n                   if(s[i] > s[i+1]) {\n                       s[i]--;\n                       for(int j = i + 1; j < s.size(); j++) s[j] = '9';\n                   }\n            }\n        int ans = stoi(s);\n        return ans;\n    }\n};"
    },
    {
        "title": "Serialize and Deserialize Binary Tree",
        "algo_input": "Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.\n\nClarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,null,null,4,5]\nOutput: [1,2,3,null,null,4,5]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "class Codec:\n\n    def serialize(self, root):\n        if not root: return 'N'\n\n        left = self.serialize(root.left)\n        right = self.serialize(root.right)\n\n        return ','.join([str(root.val), left, right])\n\n    def deserialize(self, data):\n        data = data.split(',')\n        root = self.buildTree(data)\n        return root\n\n    def buildTree(self, data):\n        val = data.pop(0)\n        if val == 'N': return None\n        node = TreeNode(val)\n        node.left = self.buildTree(data)\n        node.right = self.buildTree(data)\n        return node",
        "solution_js": "var serialize = function (root) {\n  if (!root) return \"\";\n  let res = [];\n\n  function getNode(node) {\n    if (!node) {\n      res.push(\"null\");\n    } else {\n      res.push(node.val);\n      getNode(node.left);\n      getNode(node.right);\n    }\n  }\n\n  getNode(root);\n\n  return res.join(\",\");\n};\n\n/**\n * Decodes your encoded data to tree.\n *\n * @param {string} data\n * @return {TreeNode}\n */\nvar deserialize = function (data) {\n  if (data === \"\") return null;\n  const arr = data.split(\",\");\n\n  function buildTree(array) {\n    const nodeVal = array.shift();\n\n    if (nodeVal === \"null\") return null;\n\n    const node = new TreeNode(nodeVal);\n    node.left = buildTree(array);  //build left first\n    node.right = buildTree(array); //build right with updated array.\n\n    return node;\n  }\n\n  return buildTree(arr);\n};",
        "solution_java": "public class Codec {\n\n    // Encodes a tree to a single string.\n    public String serialize(TreeNode root) {\n        String data=\"\";\n        Queue<TreeNode> q=new LinkedList<>();\n        if(root!=null)\n        q.add(root);\n        else\n         return \"\";\n        data=Integer.toString(root.val)+\"e\";\n        while(!q.isEmpty())\n        {\n            int size=q.size();\n            for(int i=0;i<size;i++)\n            {\n                TreeNode node=q.poll();\n                if(node.left!=null)\n                {\n                    data=data+Integer.toString(node.left.val)+\"e\";\n                    q.add(node.left);\n                }\n                else\n                    data=data+\"N\"+\"e\";\n                if(node.right!=null)\n                {\n                    data=data+Integer.toString(node.right.val)+\"e\";\n                    q.add(node.right);\n                }\n                else\n                    data=data+\"N\"+\"e\";\n            }\n        }\n        return data;\n    }\n\n    // Decodes your encoded data to tree.\n    public TreeNode deserialize(String data) {\n        if(data.length()==0)\n            return null;\n        int i=0;\n        String s=\"\";\n        while(data.charAt(i)!='e')\n            s=s+data.charAt(i++);\n        int d=Integer.parseInt(s);\n        TreeNode root=new TreeNode(d);\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(root);\n        while(i<data.length() && !q.isEmpty())\n        {\n            int size=q.size();\n            for(int j=0;j<size;j++)\n            {\n                s=\"\";\n                i++;\n                TreeNode node=q.poll();\n                while(data.charAt(i)!='e')\n                   s=s+data.charAt(i++);\n                if(s.equals(\"N\"))\n                    node.left=null;\n                else\n                {\n                    TreeNode l=new TreeNode(Integer.parseInt(s));\n                    node.left=l;\n                    q.add(l);\n                }\n                s=\"\";\n                i++;\n                while(data.charAt(i)!='e')\n                   s=s+data.charAt(i++);\n                if(s.equals(\"N\"))\n                    node.right=null;\n                else\n                {\n                    TreeNode r=new TreeNode(Integer.parseInt(s));\n                    node.right=r;\n                    q.add(r);\n                }\n            }\n        }\n        return root;\n        \n    }\n}",
        "solution_c": "TreeNode* ans;\nclass Codec {\npublic:\n\n    string serialize(TreeNode* root) {\n        ans = root;\n        return \"\";\n    }\n\n    TreeNode* deserialize(string data) {\n        return ans;\n    }\n};"
    },
    {
        "title": "Check if an Original String Exists Given Two Encoded Strings",
        "algo_input": "An original string, consisting of lowercase English letters, can be encoded by the following steps:\n\n\n\tArbitrarily split it into a sequence of some number of non-empty substrings.\n\tArbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).\n\tConcatenate the sequence as the encoded string.\n\n\nFor example, one way to encode an original string \"abcdefghijklmnop\" might be:\n\n\n\tSplit it as a sequence: [\"ab\", \"cdefghijklmn\", \"o\", \"p\"].\n\tChoose the second and third elements to be replaced by their lengths, respectively. The sequence becomes [\"ab\", \"12\", \"1\", \"p\"].\n\tConcatenate the elements of the sequence to get the encoded string: \"ab121p\".\n\n\nGiven two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.\n\nNote: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.\n\n&nbsp;\nExample 1:\n\nInput: s1 = \"internationalization\", s2 = \"i18n\"\nOutput: true\nExplanation: It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n  -&gt; Split:       [\"internationalization\"]\n  -&gt; Do not replace any element\n  -&gt; Concatenate:  \"internationalization\", which is s1.\n- \"internationalization\"\n  -&gt; Split:       [\"i\", \"nternationalizatio\", \"n\"]\n  -&gt; Replace:     [\"i\", \"18\",                 \"n\"]\n  -&gt; Concatenate:  \"i18n\", which is s2\n\n\nExample 2:\n\nInput: s1 = \"l123e\", s2 = \"44\"\nOutput: true\nExplanation: It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n  -&gt; Split:      [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n  -&gt; Replace:    [\"l\", \"1\", \"2\",  \"3\",   \"e\"]\n  -&gt; Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n  -&gt; Split:      [\"leet\", \"code\"]\n  -&gt; Replace:    [\"4\",    \"4\"]\n  -&gt; Concatenate: \"44\", which is s2.\n\n\nExample 3:\n\nInput: s1 = \"a5b\", s2 = \"c5b\"\nOutput: false\nExplanation: It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s1.length, s2.length &lt;= 40\n\ts1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.\n\tThe number of consecutive digits in s1 and s2 does not exceed 3.\n\n",
        "solution_py": "from functools import lru_cache\nclass Solution:\n    def possiblyEquals(self, s1: str, s2: str) -> bool:\n\n        def getValidPrefixLength(s,start):\n            end = start\n            while end < len(s) and s[end].isdigit(): end += 1\n            return end\n\n        @lru_cache(None)\n        def possibleLengths(s):\n            \"\"\"Return all possible lengths represented by numeric string s.\"\"\"\n            ans = {int(s)}\n            for i in range(1, len(s)):\n                # add all lengths by splitting numeric string s at i\n                ans |= {x+y for x in possibleLengths(s[:i]) for y in possibleLengths(s[i:])}\n            return ans\n\n        @lru_cache(None)\n        def dp(i, j, diff):\n            \"\"\"Return True if s1[i:] matches s2[j:] with given differences.\"\"\"\n\n            # If both have reached end return true if none of them are leading\n            if i == len(s1) and j == len(s2): return diff == 0\n\n            # s1 has not reached end and s1 starts with a digit\n            if i < len(s1) and s1[i].isdigit():\n                i2 = getValidPrefixLength(s1,i)\n                for L in possibleLengths(s1[i:i2]):\n                    # substract since lead of s2 decreases by L\n                    if dp(i2, j, diff-L): return True\n\n            # s2 has not reached end and s2 starts with a digit\n            elif j < len(s2) and s2[j].isdigit():\n                j2 = getValidPrefixLength(s2,j)\n                for L in possibleLengths(s2[j:j2]):\n                    # add since lead of s2 increase by L\n                    if dp(i, j2, diff+L): return True\n\n            # if none of them have integer prefix or a lead over the other\n            elif diff == 0:\n                # if only one of them has reached end or current alphabets are not the same\n                if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False\n                # skip same alphabets\n                return dp(i+1, j+1, 0)\n\n            # if none of them have integer prefix & s2 lead over s1\n            elif diff > 0:\n                # no s1 to balance s2's lead\n                if i == len(s1): return False\n                # move s1 pointer forward and reduce diff\n                return dp(i+1, j, diff-1)\n\n            # if none of them have integer prefix & s1 lead over s2\n            else:\n                # no s2 to balance s1's lead\n                if j == len(s2): return False\n                # move s2 pointer forward and increase diff\n                return dp(i, j+1, diff+1)\n\n        # start with starts of both s1 and s2 with no lead by any of them\n        return dp(0, 0, 0)",
        "solution_js": "var possiblyEquals = function(s1, s2) {\n    // Memo array, note that we do not need to memoize true results as these bubble up\n    const dp = Array.from({length: s1.length+1}, () =>\n                          Array.from({length: s2.length+1},\n                                     () => ([])));\n\n    const backtrack = (p1, p2, count) => {\n        if(p1 === s1.length && p2 === s2.length) return count === 0;\n        // Optimization: Exit early if we have already visited here and know that it's false\n        if(dp[p1][p2][count] !== undefined) return dp[p1][p2][count];\n\n        let c1 = s1[p1];\n        let c2 = s2[p2];\n\n        // Case 1: string matches exactly\n        if(p1 < s1.length && p2 < s2.length &&\n           c1 === c2 && count === 0 &&\n           backtrack(p1+1, p2+1, count)) return true;\n\n        // Case 2: we can delete a character\n        if(p1 < s1.length && isNaN(c1) && count < 0 &&\n           backtrack(p1+1, p2, count+1)) return true;\n        if(p2 < s2.length && isNaN(c2) && count > 0 &&\n           backtrack(p1, p2+1, count-1)) return true;\n\n        // Case 3: we can start stacking numbers to delete\n        let num = 0;\n        for(let i = 0; i < 3 && p1+i < s1.length; i++) {\n            let c1 = s1[p1+i];\n            if(isNaN(c1)) break;\n            num = num * 10 + parseInt(c1);\n\n            if(backtrack(p1+i+1, p2, count + num)) return true;\n        }\n\n        num = 0;\n        for(let i = 0; i < 3 && p2+i < s2.length; i++) {\n            let c2 = s2[p2+i];\n            if(isNaN(c2)) break;\n            num = num * 10 + parseInt(c2);\n\n            if(backtrack(p1, p2+i+1, count - num)) return true;\n        }\n\n        dp[p1][p2][count] = false;\n        return false;\n    }\n\n    return backtrack(0,0,0);\n};",
        "solution_java": "/**\nCases:\n\ndiff > 0 meaning we need to pick more chars in s1\ndiff < 0 meaning we need to pick more chars in s2\n\n-1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999\n\n1. s1[i] == s2[j] and diff = 0\n    increment i+1 and j+1\n\n2. if s1[i] is not digit and diff > 0 then increment i i+1, diff\n3. if s2[j] is not digit and diff < 0 then increment j j+1, diff\n4. if s1[i] is digit then get digit value and decrement diff val as we have covered such chars in the s1 string\n    and increment i i+1, diff-val\n5. if s2[j] is digit then get digit value and increment diff val as we need to cover such chars in the s2 string and\n    increment j, j+1, diff+val\n\n     01234\ns1 = l123e\ns2 = 44\n\ni: 0\nj: 0\ndiff: 0\n    // Wildcard matching on s2[j]\n    val = 4, diff = 0+4 j = 1\n\n    i: 0\n    j: 1\n    diff: 4\n    // Literal matching on s1[i]\n    increment ith pointer as ith is a literal and we can move on to next char in s1 and decrement diff\n\n        i: 1\n        j: 1\n        diff: 3\n        // Wildcard matching on s1[i]\n        val = 1 diff = 3-1 = 2 increment i\n\n            i: 2\n            j: 1\n            diff: 2\n            // Wildcard matching on s1[i]\n            val = 2 diff = 2-2 = 0 increment i\n\n                i: 3\n                j: 1\n                diff: 0\n                // Wildcard matching on s1[i]\n                val=3 diff = 0-3 = -3, increment i\n\n                    i: 4\n                    j: 1\n                    diff: -3\n                    // Wildcard matching on s2[j]\n                    val = 4 diff = -3+4 =1 increment j\n\n                        i: 4\n                        j: 2\n                        diff: 1\n                         // Literal matching on s1[i]\n                         decrement i-1 and increment i\n\n                            i=5\n                            j=2\n                                diff==0 return true\n                        dp[4][2][1] = true\n                        return true\n                    return dp[4][1][1000-3] = true\n                return dp[3][1][0] = true\n\n            i: 2\n            j: 1\n            diff: 2\n            return dp[2][1][2] = true\n            return true\n\n        i: 0\n        j: 1\n        diff: 4\n        return dp[0][1][4] = true\n    return true\n*/\n\nclass Solution {\n    //112ms\n     public boolean possiblyEquals(String s1, String s2) {\n         return helper(s1.toCharArray(), s2.toCharArray(), 0, 0, 0, new Boolean[s1.length()+1][s2.length()+1][2001]);\n     }\n\n     boolean helper(char[] s1, char[] s2, int i, int j, int diff, Boolean[][][] dp) {\n         if(i == s1.length && j == s2.length) {\n             return diff == 0;\n         }\n\n         if(dp[i][j][diff+1000] != null)\n             return dp[i][j][diff+1000];\n\n         // if both i and j are at the same location and chars are same then simply increment both pointers\n         if(i < s1.length && j < s2.length && diff == 0 && s1[i] == s2[j]) {\n             if(helper(s1, s2, i+1, j+1, diff, dp)) {\n                 return dp[i][j][diff+1000] = true;\n             }\n         }\n\n         // if s1[i] is literal and diff > 0 then increment i and decrement diff by 1\n         if(i < s1.length && !Character.isDigit(s1[i]) && diff > 0 && helper(s1, s2, i+1, j, diff-1, dp)) {\n             return dp[i][j][diff+1000] = true;\n         }\n\n         // if s2[j] is literal and diff < 0 then increment j and increment diff by 1\n         // as we are done with the current jth char\n         if(j < s2.length && !Character.isDigit(s2[j]) && diff < 0 && helper(s1, s2, i, j+1, diff+1, dp)) {\n             return dp[i][j][diff+1000] = true;\n         }\n\n         // wildcard matching in s1\n         // if s1 contains l123\n         // then need to check with val as 1 then val as 12 and val as 123\n         for(int k = i, val = 0; k < i + 4 && k < s1.length && Character.isDigit(s1[k]); k++) {\n             val = val * 10 + s1[k] -'0';\n             if(helper(s1, s2, k+1, j, diff-val, dp)) {\n                 return dp[i][j][diff+1000] = true;\n             }\n         }\n\n         // wildcard matching in s2\n         // if s2 contains l123\n         // then need to check with val as 1 then val as 12 and val as 123\n         for(int k = j, val = 0; k < j + 4 && k < s2.length && Character.isDigit(s2[k]); k++) {\n             val = val * 10 + s2[k] -'0';\n             if(helper(s1, s2, i, k+1, diff+val, dp)) {\n                 return dp[i][j][diff+1000] = true;\n             }\n         }\n\n         return dp[i][j][diff+1000] = false;\n     }\n}",
        "solution_c": "class Solution {\npublic:\n    bool memo[50][50][2000];\n    bool comp_seqs(string& s1, string& s2, int i1, int i2, int diff){\n        // check true condition\n        if(i1 == s1.size() && i2 == s2.size())\n            return diff == 0;\n        // add 1000 to 'diff' be in range [0, 2000)\n        bool& ret = memo[i1][i2][diff+1000];\n        if(ret)\n            return false; // immediately return\n        ret = true; // check visited\n\n        // diff > 0 or diff < 0 checking to ensure the diff always be in range (-1000, 1000)\n        // in the case that s1[i1] is a digit\n        if(diff >= 0 && i1 < s1.size() && s1[i1] <= '9'){\n            int num1 = 0;\n            for(int i=0; i<min(3, (int)s1.size()-i1); i++){ // loop maximum 3 consecutive digits\n                if(s1[i1 + i] > '9')\n                    break;\n                num1 = num1*10 + s1[i1 + i] - '0';\n                if(comp_seqs(s1, s2, i1+i+1, i2, diff-num1))\n                    return true;\n            }\n        }else if(diff <= 0 && i2 < s2.size() && s2[i2] <= '9'){ // in the case that s2[i2] is a digit\n            int num2 = 0;\n            for(int i=0; i<min(3, (int)s2.size()-i2); i++){\n                if(s2[i2 + i] > '9')\n                    break;\n                num2 = num2*10 + s2[i2 + i] - '0';\n                if(comp_seqs(s1, s2, i1, i2+i+1, diff+num2))\n                    return true;\n            }\n        }else if(diff == 0){\n            if(i1 >= s1.size() || i2 >= s2.size() || s1[i1] != s2[i2]) // reject infeasible cases\n                return false;\n            return comp_seqs(s1, s2, i1+1, i2+1, 0);\n        }else if(diff > 0){\n            if(i1 >= s1.size()) // reject infeasible cases\n                return false;\n            return comp_seqs(s1, s2, i1+1, i2, diff - 1);\n        }else{\n            if(i2 >= s2.size()) // reject infeasible cases\n                return false;\n            return comp_seqs(s1, s2, i1, i2+1, diff + 1);\n        }\n        return false;\n    }\n    bool possiblyEquals(string s1, string s2) {\n        return comp_seqs(s1, s2, 0, 0, 0);\n    }\n};"
    },
    {
        "title": "Concatenation of Array",
        "algo_input": "Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 &lt;= i &lt; n (0-indexed).\n\nSpecifically, ans is the concatenation of two nums arrays.\n\nReturn the array ans.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,1]\nOutput: [1,2,1,1,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]\n\nExample 2:\n\nInput: nums = [1,3,2,1]\nOutput: [1,3,2,1,1,3,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def getConcatenation(self, nums):\n        return nums * 2",
        "solution_js": "var getConcatenation = function(nums) {\n\t//spread the nums array twice and return it\n    return [...nums,...nums]\n};",
        "solution_java": "class Solution {\n    public int[] getConcatenation(int[] nums) {\n        int[] ans = new int[2 * nums.length];\n        for(int i = 0; i < nums.length; i++){\n            ans[i] = ans[i + nums.length] = nums[i];\n        }\n\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> getConcatenation(vector<int>& nums) {\n        int n=nums.size();\n        for(int i=0;i<n;i++)\n        {\n            nums.push_back(nums[i]);\n        }\n        return nums;\n    }\n};"
    },
    {
        "title": "Detonate the Maximum Bombs",
        "algo_input": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.\n\nThe bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.\n\nYou may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.\n\nGiven the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.\n\n&nbsp;\nExample 1:\n\nInput: bombs = [[2,1,3],[6,1,4]]\nOutput: 2\nExplanation:\nThe above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.\n\n\nExample 2:\n\nInput: bombs = [[1,1,5],[10,10,5]]\nOutput: 1\nExplanation:\nDetonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.\n\n\nExample 3:\n\nInput: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\nOutput: 5\nExplanation:\nThe best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= bombs.length&nbsp;&lt;= 100\n\tbombs[i].length == 3\n\t1 &lt;= xi, yi, ri &lt;= 105\n\n",
        "solution_py": "class Solution(object):\n    def maximumDetonation(self, bombs):\n        def count(i):\n            dq, ret = [i], [i]\n            while len(dq) > 0:\n                i = dq.pop()\n                for j in adj[i]:\n                    if j not in ret and j not in dq:\n                        dq.append(j)\n                        ret.append(j)\n            return len(ret)\n\n        adj = collections.defaultdict(list)\n        for i in range(len(bombs)):\n            for j in range(i + 1, len(bombs)):\n                if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:\n                    adj[i].append(j)\n                if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:\n                    adj[j].append(i)\n        ret = 0\n        for i in range(len(bombs)):\n            ret = max(ret, count(i))\n        return ret",
        "solution_js": "/**\n * @param {number[][]} bombs\n * @return {number}\n */\nvar maximumDetonation = function(bombs) {\n    if(bombs.length <= 1) return bombs.length;\n    \n    let adj = {}, maxSize = 0;\n    const checkIfInsideRange = (x, y, center_x, center_y, radius) =>{\n        return ( (x-center_x)**2 + (y-center_y)**2 <= radius**2 ) \n    }\n\t\n\t//CREATE ADJACENCY MATRIX\n    for(let i = 0;i<bombs.length;i++){\n        for(let j = i+1;j<bombs.length;j++){\n            if(!adj[i]) adj[i] = [];\n            if(!adj[j]) adj[j] = [];\n            let bombOne = bombs[i];\n            let bombTwo = bombs[j];\n            let fir = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombOne[2]);     \n            if(fir) adj[i].push(j);\n            let sec = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombTwo[2]);\n            if(sec) adj[j].push(i);\n        }\n    }\n\t\n\t//DEPTH FIRST SEARCH TO FIND ALL BOMBS TRIGGERED BY NODE\n    const dfs = (node, visited)=>{\n        let detonated = 1;\n        visited[node] = true;\n        let childs = adj[node] || []\n        for(let child of childs){\n            if(visited[child]) continue;\n            detonated += dfs(child, visited)\n        }\n        maxSize = Math.max(maxSize, detonated)\n        return detonated;\n    }\n    \n    for(let i = 0 ;i<bombs.length;i++){\n        dfs(i, {})\n    }\n    return maxSize\n};",
        "solution_java": "class Solution {\n    /*\n    Make directed graph\n    u -> v means, v is in the range of u\n    check from which node maximum nodes can be reached and return the number of nodes reached\n    */\n    public int maximumDetonation(int[][] bombs) {\n        Map<Integer, List<Integer>> graph = new HashMap<>();\n\n        int n = bombs.length;\n        for(int i = 0; i< n; i++){\n            graph.put(i, new ArrayList<>());\n            for(int j = 0; j< n; j++){\n                if(i == j) continue;\n                if(inRange(bombs[i], bombs[j]))\n                    graph.get(i).add(j);\n            }\n        }\n\n        int max = 0;\n        for(int i = 0; i< n; i++){\n            max = Math.max(max, dfs(i, graph, new HashSet<>()));\n        }\n        return max;\n    }\n\n    private boolean inRange(int[] u, int[] v){\n        // (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border\n        // (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle\n        // (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle\n        return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);\n    }\n\n    private int dfs(int node, Map<Integer, List<Integer>> graph, Set<Integer> visited){\n        if(visited.contains(node)) return 0;\n        visited.add(node);\n        int res = 0;\n        for(int neigh: graph.get(node)){\n            res += dfs(neigh, graph, visited);\n        }\n        return res + 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double eucDis(int x1,int y1,int x2,int y2)\n    {\n        double temp=pow(x1-x2,2)+pow(y1-y2,2);\n        return sqrt(temp);\n    }\n    void dfs(int node,vector<int>&vis,vector<int>graph[],int &c)\n    {\n        c++;\n        vis[node]=1;\n        for(auto i:graph[node])\n        {\n            if(!vis[i])\n            {\n                dfs(i,vis,graph,c);\n            }\n        }\n    }\n    int maximumDetonation(vector<vector<int>>& bombs) {\n        \n        int n=bombs.size();\n        vector<int>graph[n+1];\n        int i,j;\n        for(i=0;i<n;i++)\n        {\n            bombs[i].push_back(i);\n        }\n        for(i=0;i<n;i++)\n        {\n            \n            for(j=0;j<n;j++)\n            {\n                if(i==j)\n                    continue;\n                double dis1=eucDis(bombs[i][0],bombs[i][1],bombs[j][0],\n                               bombs[j][1]);\n                \n                if(dis1<=bombs[i][2])\n                {\n                    int node1=bombs[i][3];\n                    int node2=bombs[j][3];\n                    graph[node1].push_back(node2);\n                }\n            }\n        }\n       \n        int maxi=1;\n        for(i=0;i<n;i++)\n        {\n            int c=0;\n            if(graph[i].empty())\n                continue;\n            vector<int>vis(n+1,0);\n            \n            dfs(i,vis,graph,c);   \n            maxi=max(maxi,c);\n            \n            \n        }\n        return maxi;\n    }\n};"
    },
    {
        "title": "Count Hills and Valleys in an Array",
        "algo_input": "You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].\n\nNote that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.\n\nReturn the number of hills and valleys in nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,4,1,1,6,5]\nOutput: 3\nExplanation:\nAt index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 &gt; 2 and 4 &gt; 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 &lt; 4 and 1 &lt; 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 &lt; 4 and 1 &lt; 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 &gt; 1 and 6 &gt; 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.\n\n\nExample 2:\n\nInput: nums = [6,6,5,5,4,1]\nOutput: 0\nExplanation:\nAt index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 &lt; 6 and 5 &gt; 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 &lt; 6 and 5 &gt; 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 &lt; 5 and 4 &gt; 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def countHillValley(self, nums: List[int]) -> int:\n        c = 0\n        i = 1\n        while i <len(nums)-1:\n            j = i+1\n            while j < len(nums)-1 and nums[j] == nums[i]:\n                j += 1\n            if (nums[i-1] > nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):\n                    c += 1\n            i = j\n        return c",
        "solution_js": "var countHillValley = function(nums) {\n    let previous;\n    let count = 0;\n    for (let i=0; i<nums.length; i++) {\n        if (previous === undefined) {\n            previous = i;\n            continue;\n        }\n        if (nums[i-1] === nums[i]) {\n            continue;\n        }\n        let nextCheck = i + 1;\n        while(nums[nextCheck] === nums[i]) {\n              nextCheck++;\n        }\n        if(nums[i] > nums[previous] && nums[i] > nums[nextCheck]) {\n            count++;\n        }\n        if(nums[i] < nums[previous] && nums[i] < nums[nextCheck]) {\n            count++;\n        }\n        previous = i;\n        i = nextCheck - 1;\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int countHillValley(int[] nums) {\n        int result = 0;\n    \n\t\t// Get head start. Find first index for which nums[index] != nums[index-1]\n\t\tint start = 1;\n\t\twhile(start < nums.length && nums[start] == nums[start-1])\n\t\t\tstart++;\n\n\t\tint prev = start-1; //index of prev different value num\n\t\tfor(int i=start; i<nums.length-1; i++) {\n\t\t\tif(nums[i] == nums[i+1]) //If numbers are same, simply ignore them\n\t\t\t\tcontinue;\n\t\t\telse {\n\t\t\t\tif(nums[i] > nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number\n\t\t\t\t\tresult++;\n\t\t\t\tif(nums[i] < nums[prev] && nums[i] < nums[i+1])\n\t\t\t\t\tresult++;\n\t\t\t\tprev = i;   // Now your current number will become prev number.\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    int countHillValley(vector<int>& nums) {\n\t// taking a new vector\n        vector<int>v;\n        v.push_back(nums[0]);\n\t\t//pushing unique elements into new vector\n        for(int i=1;i<nums.size();i++){\n            if(nums[i]!=nums[i-1]){\n                v.push_back(nums[i]);\n            }\n        }\n        int c=0;\n\t\t//checking for valley or hill\n        for(int i=1;i<v.size()-1;i++){\n            if(v[i]>v[i-1] and v[i]>v[i+1] or v[i]<v[i-1] and v[i]<v[i+1]){\n                c++;\n            }\n        }\n        return c;\n    }\n};"
    },
    {
        "title": "Increasing Decreasing String",
        "algo_input": "You are given a string s. Reorder the string using the following algorithm:\n\n\n\tPick the smallest character from s and append it to the result.\n\tPick the smallest character from s which is greater than the last appended character to the result and append it.\n\tRepeat step 2 until you cannot pick more characters.\n\tPick the largest character from s and append it to the result.\n\tPick the largest character from s which is smaller than the last appended character to the result and append it.\n\tRepeat step 5 until you cannot pick more characters.\n\tRepeat the steps from 1 to 6 until you pick all characters from s.\n\n\nIn each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.\n\nReturn the result string after sorting s with this algorithm.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aaaabbbbcccc\"\nOutput: \"abccbaabccba\"\nExplanation: After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"\n\n\nExample 2:\n\nInput: s = \"rat\"\nOutput: \"art\"\nExplanation: The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of only lowercase English letters.\n\n",
        "solution_py": "from collections import Counter\nclass Solution:\n    def sortString(self, s: str) -> str:\n        counter = Counter(s)\n        alphabets = \"abcdefghijklmnopqrstuvwxyz\"\n        rev_alphabets = alphabets[::-1]\n        total = len(s)\n        res = []\n        while total > 0:\n            for c in alphabets:\n                if counter[c]: \n                    res.append(c)\n                    counter[c] -= 1\n                    total -= 1\n            for c in rev_alphabets:\n                if counter[c]:\n                    res.append(c)\n                    counter[c] -= 1\n                    total -= 1\n        return \"\".join(res)",
        "solution_js": "/**\n * @param {string} s\n * @return {string}\n */\nvar sortString = function(s) {\n  const counts = [...s].reduce((acc, cur) => (acc[cur.charCodeAt() - 97] += 1, acc), new Array(26).fill(0));\n  const result = [];\n\n  const pick = (code) => {\n    if (counts[code]) {\n      result.push(String.fromCharCode(code + 97));\n      counts[code] -= 1;\n    }\n  }\n\n  while (result.length < s.length) {\n    for (let i = 0; i < counts.length; i++) pick(i);\n    for (let i = 0; i < counts.length; i++) pick(counts.length - 1 - i);\n  }\n\n  return result.join('');\n};",
        "solution_java": "class Solution {\n    public String sortString(String s) {\n        \n        StringBuilder result = new StringBuilder();\n        int[] freq  = new int[26];\n        for(char c: s.toCharArray()){\n            freq[c-'a']++;\n        }\n        int remaining = s.length();\n        while(remaining!=0){\n            for(int i=0;i<26&&remaining!=0;i++){\n                if(freq[i]!=0){\n                    freq[i]--;\n                    result.append((char)(i+'a'));\n                    remaining--;\n                }\n            }\n            for(int i=25;i>=0&&remaining!=0;i--){\n                if(freq[i]!=0){\n                    freq[i]--;\n                    result.append((char)(i+'a'));\n                    remaining--;\n                }\n            }\n        }\n        return result.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string sortString(string s) {\n       int count [26]={0};\n        for(int i =0 ;i< s.size();i++){\n            char ch = s[i];\n            count[ch-'a']++;\n        }\n        string res ;\n        while(res.size()!=s.size()){\n            for(int i = 0 ;i<26;i++){\n                if(count[i] >0) {\n                     char ch = i+'a';\n                      res += ch;\n                      count[i]--;\n                }\n           }\n            for(int i = 25 ;i>=0 ;i--){\n                if(count[i] >0){\n                     char ch= i+'a';\n                     res += ch;\n                     count[i]--;\n                    }\n              }\n         }\n        return res ;\n    }\n};"
    },
    {
        "title": "Longest Continuous Increasing Subsequence",
        "algo_input": "Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.\n\nA continuous increasing subsequence is defined by two indices l and r (l &lt; r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l &lt;= i &lt; r, nums[i] &lt; nums[i + 1].\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2]\nOutput: 1\nExplanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-109 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def findLengthOfLCIS(self, nums: List[int]) -> int:\n        count=0\n        for i in range(len(nums)):\n            a=nums[i]\n            c=1\n            for j in range(i+1, len(nums)):\n                if nums[j]>a:\n                    a=nums[j]\n                    c+=1\n                else:\n                    break\n            count=max(count, c)\n        return count",
        "solution_js": "var findLengthOfLCIS = function(nums) {\n    let res = 0;\n    let curr = 1;\n    \n    nums.forEach((num, idx) => {\n        if (num < nums[idx + 1]) {\n            curr++;\n        }\n        else curr = 1;\n        \n        res = Math.max(res, curr);\n    })\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    public int findLengthOfLCIS(int[] nums) {\n        int count = 1;\n        int maxCount = 1;\n        for (int i = 1; i < nums.length; i++) {\n            if (nums[i] > nums[i - 1]) {\n                count++;\n            } else {\n                maxCount = Math.max(count, maxCount);\n                count = 1;\n            }\n        }\n        maxCount = Math.max(count, maxCount);\n        return maxCount;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findLengthOfLCIS(vector<int>& nums) {\n        int maxLength = 1;\n        int currLength = 1;\n        int i = 0;\n        int j = 1;\n        \n        while(j<nums.size()){\n            if(nums[j] > nums[i]){\n                currLength++;\n                i++;\n                j++;\n                if(currLength > maxLength) maxLength = currLength;\n            } else{\n                currLength = 1;\n                i = j;\n                j++;\n            }\n        }\n        return maxLength;\n    }\n};"
    },
    {
        "title": "Maximum Width Ramp",
        "algo_input": "A ramp in an integer array nums is a pair (i, j) for which i &lt; j and nums[i] &lt;= nums[j]. The width of such a ramp is j - i.\n\nGiven an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.\n\n&nbsp;\nExample 1:\n\nInput: nums = [6,0,8,2,1,5]\nOutput: 4\nExplanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\n\n\nExample 2:\n\nInput: nums = [9,8,1,0,1,9,4,0,4,1]\nOutput: 7\nExplanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 5 * 104\n\t0 &lt;= nums[i] &lt;= 5 * 104\n\n",
        "solution_py": "class Solution:\n    def maxWidthRamp(self, nums: List[int]):\n        st=[]\n        n=len(nums)\n        for i in range(n):\n            if len(st)==0 or nums[st[-1]]>=nums[i]:\n                st.append(i)\n        print(st)\n        max_idx=-1\n        for j in range(n-1,-1,-1):\n            while len(st) and nums[st[-1]]<=nums[j]:\n                prev=st.pop()\n                max_idx=max(max_idx,j-prev)\n\n        return max_idx",
        "solution_js": "var maxWidthRamp = function(nums) {\n  let stack = [], ans = 0;\n  for (let i = 0; i < nums.length; i++) {\n    let index = lower_bound(stack, i);\n    ans = Math.max(ans, i - index);\n    if (!stack.length || nums[i] < nums[stack[stack.length - 1]]) stack.push(i);\n  }\n  return ans;\n  \n  function lower_bound(arr, index) {\n    if (!arr.length) return index;\n    let low = 0, high = arr.length - 1;\n    while (low < high) {\n      let mid = Math.floor((low + high) / 2);\n      if (nums[arr[mid]] <= nums[index]) high = mid;\n      else low = mid + 1;\n    }\n    return nums[arr[low]] <= nums[index] ? arr[low] : index;\n  }\n};",
        "solution_java": "class Solution {\n    public int maxWidthRamp(int[] nums) {\n        Stack<Integer> s = new Stack<>();\n        int res = 0;\n        for(int i = 0; i< nums.length; i++){\n            if(!s.isEmpty() && nums[s.peek()]<=nums[i]) {\n                res = Math.max(res, i-s.peek());\n                continue;\n            }\n            s.push(i);\n        }\n        int i = nums.length-1;\n        while(!s.isEmpty() && i>=0){\n            if(nums[s.peek()]<=nums[i]){\n                res = Math.max(res, i-s.peek());\n                s.pop();\n            }else{\n                i--;\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxWidthRamp(vector<int>& nums) {\n        int n=nums.size();\n        if(n==2){\n            if(nums[0]<=nums[1])return 1;\n            return 0;\n        }\n        stack<int>st;\n        for(int i=0;i<n;i++){\n            if(st.empty()||nums[i]<nums[st.top()]){st.push(i);}  // maintaining a monotonic decreasing stack\n        }\n        int ramp=0;\n        for(int i=n-1;i>=0;i--){\n            while(!st.empty() && nums[i]>=nums[st.top()] ){    \n                ramp=max(ramp,i-st.top());\n                st.pop();\n            }\n        }\n        return ramp;\n    }\n};"
    },
    {
        "title": "Insert Delete GetRandom O(1)",
        "algo_input": "Implement the RandomizedSet class:\n\n\n\tRandomizedSet() Initializes the RandomizedSet object.\n\tbool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.\n\tbool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.\n\tint getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.\n\n\nYou must implement the functions of the class such that each function works in&nbsp;average&nbsp;O(1)&nbsp;time complexity.\n\n&nbsp;\nExample 1:\n\nInput\n[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]\nOutput\n[null, true, false, true, 2, true, false, 2]\n\nExplanation\nRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t-231 &lt;= val &lt;= 231 - 1\n\tAt most 2 *&nbsp;105 calls will be made to insert, remove, and getRandom.\n\tThere will be at least one element in the data structure when getRandom is called.\n\n",
        "solution_py": "class RandomizedSet:\n\n    def __init__(self):\n        self.data = set() \n\n    def insert(self, val: int) -> bool:\n      if val not in self.data:\n        self.data.add(val)\n        return True \n      return False \n        \n    def remove(self, val: int) -> bool:\n        if val in self.data:\n          self.data.remove(val)\n          return True \n        return False \n\n    def getRandom(self) -> int:\n        return  random.choice(list(self.data))",
        "solution_js": "var RandomizedSet = function() {\n    this._data = [];\n    this._flatData = [];\n};\n\nRandomizedSet.prototype.hash = function(val) {\n    return val % 1e5;\n}\n\nRandomizedSet.prototype.insert = function(val) {\n    const hash = this.hash(val);\n    let basket = this._data[hash];\n    \n    for (let i = 0; i < basket?.length; i++) {\n        if (basket[i][0] === val) { return false; }\n    }\n    \n    if (!basket) {\n        this._data[hash] = [[val, this._flatData.length]];\n    } else {\n        this._data[hash].push([val, this._flatData.length]);\n    }\n    this._flatData.push(val);    \n    return true;\n};\n\nRandomizedSet.prototype.remove = function(val) {\n    const hash = this.hash(val);\n    let basket = this._data[hash];\n    if (!basket) { return false; }\n    for (let i = 0; i < basket.length; i++) {\n        const currBasket = basket[i];\n        if (currBasket[0] === val) {\n            const idxInFlat = currBasket[1];\n            const reassignedValueInFlat = del(this._flatData, idxInFlat);\n            // Write new address in _data if needed\n            if (reassignedValueInFlat) {\n                this._data[this.hash(reassignedValueInFlat)].forEach(item => {\n                    if (item[0] === reassignedValueInFlat) {\n                        item[1] = idxInFlat;\n                        return; // from forEach\n                    }\n                });\n            }\n            // Delete from _data\n            del(basket, i);\n            return true;\n        }\n    }\n    return false;\n};\n\nRandomizedSet.prototype.getRandom = function() {\n    return this._flatData[getRandomInt(0, this._flatData.length - 1)];\n};\n\nfunction getRandomInt(min, max) {\n    min = Math.ceil(min);\n    max = Math.floor(max);\n    return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nfunction del(arr, idx) {\n    if (!arr.length) { return null; }\n    if (idx === arr.length - 1) { arr.pop(); return null; }\n    arr[idx] = arr.pop();\n    return arr[idx];\n}",
        "solution_java": "class RandomizedSet {\n    HashMap<Integer, Integer> map;\n    ArrayList<Integer> list;\n    Random rand;\n    public RandomizedSet() {\n        map = new HashMap<>();\n        list = new ArrayList<>();\n        rand = new Random();\n    }\n    \n    public boolean insert(int val) {\n        if (!map.containsKey(val)){\n            map.put(val, list.size());\n            list.add(val);\n            return true;\n        }\n        return false;\n    }\n    \n    public boolean remove(int val) {\n        if (map.containsKey(val)){\n            int index = map.get(val);\n            int last = list.get(list.size() - 1);\n            if (index != list.size() - 1){\n                list.set(index, last);\n                map.put(last, index);\n            }\n            list.remove(list.size() - 1);  \n            map.remove(val);\n            return true;\n        }\n        return false;\n    }\n    \n    public int getRandom() {\n        int r = rand.nextInt(list.size());   \n        return list.get(r);\n    }\n}",
        "solution_c": "class RandomizedSet {\npublic:\n    unordered_map<int, int> mp;\n    vector<int> v;\n    RandomizedSet() {\n        \n    }\n    \n    bool insert(int val) {\n        if(mp.find(val) != mp.end()) return false;\n        mp[val] = v.size();\n        v.push_back(val);\n        return true;\n    }\n    \n    bool remove(int val) {\n        if(mp.find(val) != mp.end()){\n            v[mp[val]] = v.back();\n            mp[v.back()] = mp[val];\n            v.pop_back();\n            mp.erase(val);\n            return true;\n        } \n        return false;\n    }\n    \n    int getRandom() {\n        return v[rand()%v.size()];\n    }\n};"
    },
    {
        "title": "Sum of Two Integers",
        "algo_input": "Given two integers a and b, return the sum of the two integers without using the operators + and -.\n\n&nbsp;\nExample 1:\nInput: a = 1, b = 2\nOutput: 3\nExample 2:\nInput: a = 2, b = 3\nOutput: 5\n\n&nbsp;\nConstraints:\n\n\n\t-1000 &lt;= a, b &lt;= 1000\n\n",
        "solution_py": "class Solution(object):\n    def getSum(self, a, b):\n        \"\"\"\n        :type a: int\n        :type b: int\n        :rtype: int\n        \"\"\"\n        sol=(a,b)\n        return sum(sol)\n\t```",
        "solution_js": "/**\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nvar getSum = function(a, b) {\n    if (a==0){\n        return b;\n    }\n    else if (b==0){\n        return a;\n    }\n    else{\n        return getSum((a^b),(a&b)<<1);\n    }\n    \n};",
        "solution_java": "class Solution {\n    \n     public int getSum(int a, int b) {\n       return Integer.sum(a, b);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getSum(int a, int b) {\n        vector<int> arr = {a,b};\n        return accumulate(arr.begin(),arr.end(),0);\n    }\n};"
    },
    {
        "title": "Maximum Sum of Two Non-Overlapping Subarrays",
        "algo_input": "Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.\n\nThe array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.\n\nA subarray is a contiguous part of an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput: 20\nExplanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\n\n\nExample 2:\n\nInput: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput: 29\nExplanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\n\n\nExample 3:\n\nInput: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput: 31\nExplanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= firstLen, secondLen &lt;= 1000\n\t2 &lt;= firstLen + secondLen &lt;= 1000\n\tfirstLen + secondLen &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:\n        n = len(nums)\n        p = [0]\n        for el in nums:\n            p.append(p[-1] + el)\n        msum = 0\n        for f, s in [(firstLen, secondLen), (secondLen, firstLen)]:\n            for i in range(f - 1, n - s + 1):\n                for j in range(i + 1, n - s + 1):\n                    l = p[i + 1] - p[i - f + 1]\n                    r = p[j + s] - p[j]\n                    msum = max(msum, l + r)\n        return msum",
        "solution_js": "var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) {\n    function helper(arr, x, y)\n    {\n        const n = arr.length;\n        let sum = 0;\n        const dp1 = []; // store left x sum\n        const dp2 = []; // store right y sum\n\n        for(let i = 0; i<n; i++)\n        {\n            if(i<x) {\n                sum += arr[i];\n                dp1[i] = sum;\n            }\n            else {\n                sum += arr[i] - arr[i-x];\n                dp1[i] = Math.max(dp1[i-1], sum);\n            }\n        }\n        sum = 0;\n        for(let i = n-1; i>=0; i--)\n        {\n            if(i>=n-y)\n            {\n                sum += arr[i];\n                dp2[i] = sum;\n            }\n            else\n            {\n                sum += arr[i] - arr[i+y];\n                dp2[i] = Math.max(dp2[i+1], sum);\n            }\n        }\n        let max = -Infinity;\n        for(let i = x-1; i< n-y; i++)\n        {\n            max = Math.max(max, dp1[i] + dp2[i+1]);\n        }\n        return max;\n    }\n    return Math.max(helper(nums, firstLen, secondLen), \n                   helper(nums, secondLen, firstLen));\n};",
        "solution_java": "class Solution {\n    public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {\n        int []dp1=new int[nums.length];\n        int []dp2=new int[nums.length];\n        \n        int sum=0;\n        for(int i=0;i<nums.length;i++){\n            if(i<firstLen){\n                sum+=nums[i];\n                dp1[i]=sum;\n            }else{\n                sum+=nums[i]-nums[i-firstLen];\n                dp1[i]=Math.max(sum,dp1[i-1]);\n            }\n        }\n        \n        sum=0;\n        for(int i=nums.length-1;i>=0;i--){\n            if(i+secondLen>=nums.length){\n                sum+=nums[i];\n                dp2[i]=sum;\n            }else{\n                sum+=nums[i]-nums[i+secondLen];\n                dp2[i]=Math.max(sum,dp2[i+1]);\n            }\n        }\n        \n        int max=0;\n        \n        for(int i=firstLen-1;i<nums.length-secondLen;i++){\n            max=Math.max(max,dp1[i]+dp2[i+1]);\n        }\n        \n        int max1=max;\n        \n        dp1=new int[nums.length];\n        dp2=new int[nums.length];\n        \n        sum=0;\n        for(int i=0;i<nums.length;i++){\n            if(i<secondLen){\n                sum+=nums[i];\n                dp1[i]=sum;\n            }else{\n                sum+=nums[i]-nums[i-secondLen];\n                dp1[i]=Math.max(sum,dp1[i-1]);\n            }\n        }\n        \n        sum=0;\n        for(int i=nums.length-1;i>=0;i--){\n            if(i+firstLen>=nums.length){\n                sum+=nums[i];\n                dp2[i]=sum;\n            }else{\n                sum+=nums[i]-nums[i+firstLen];\n                dp2[i]=Math.max(sum,dp2[i+1]);\n            }\n        }\n        \n        max=0;\n        \n        for(int i=secondLen-1;i<nums.length-firstLen;i++){\n            max=Math.max(max,dp1[i]+dp2[i+1]);\n        }\n        \n        \n        int max2=max;\n        \n        return Math.max(max1,max2);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int solve(vector<int>& prefixSum, int n, int firstLen, int secondLen){\n        vector<int> dp(n, 0);\n        \n        dp[n-secondLen] = prefixSum[n]-prefixSum[n-secondLen];\n        \n        for(int i=n-secondLen-1; i>=0; i--){\n            dp[i] = max(dp[i+1], prefixSum[i+secondLen]-prefixSum[i]);\n        }\n        \n        dp[firstLen] = dp[firstLen] + prefixSum[firstLen]-prefixSum[0];\n        \n        for(int i=firstLen+1; i<=n-secondLen; i++){\n            dp[i] = max(dp[i-1], dp[i] + (prefixSum[i]-prefixSum[i-firstLen]));\n        }\n        \n        return *max_element(dp.begin(), dp.end());\n    }\n    \n    int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {\n        int n = nums.size();\n        vector<int> prefixSum(n+1, 0);\n        \n        for(int i=1; i<=n; i++){\n            prefixSum[i] = prefixSum[i-1] + nums[i-1];\n        }\n        \n        return max(solve(prefixSum, n, firstLen, secondLen), solve(prefixSum, n, secondLen, firstLen));\n    }\n};"
    },
    {
        "title": "Minimum Cost For Tickets",
        "algo_input": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.\n\nTrain tickets are sold in three different ways:\n\n\n\ta 1-day pass is sold for costs[0] dollars,\n\ta 7-day pass is sold for costs[1] dollars, and\n\ta 30-day pass is sold for costs[2] dollars.\n\n\nThe passes allow that many days of consecutive travel.\n\n\n\tFor example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.\n\n\nReturn the minimum number of dollars you need to travel every day in the given list of days.\n\n&nbsp;\nExample 1:\n\nInput: days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput: 11\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.\n\n\nExample 2:\n\nInput: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput: 17\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= days.length &lt;= 365\n\t1 &lt;= days[i] &lt;= 365\n\tdays is in strictly increasing order.\n\tcosts.length == 3\n\t1 &lt;= costs[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n        min_cost = float('inf')\n        que = deque()\n        # enqueue the possible state of day 1\n        que.append((days[0], costs[0]))\n        que.append((days[0]+7-1, costs[1]))\n        que.append((days[0]+30-1, costs[2]))\n        last_day = days[-1]\n        for i in range(1, len(days)):\n            for _ in range(len(que)):\n                node = que.popleft()\n                if node[0] < days[i]:\n                    # try taking all the three pass on that day and enqueue \n                    que.append((days[i], node[1]+costs[0]))\n                    if days[i] + 7 - 1 >= last_day:\n                        min_cost = min(min_cost, node[1] + costs[1])\n                    else:\n                        que.append((days[i]+7-1, node[1]+costs[1]))\n                    if days[i] + 30 - 1 >= last_day: \n                        min_cost = min(min_cost, node[1] + costs[2])\n                    else:\n                        que.append((days[i]+30-1, node[1]+costs[2]))\n                else:\n                    que.append(node)\n        for _ in range(len(que)):\n            node = que.popleft()\n            min_cost = min(min_cost, node[1])\n        return min_cost",
        "solution_js": "var mincostTickets = function(days, costs) {\n  let store = {};\n  for(let i of days) {\n      store[i] = true\n  }\n  let lastDay = days[days.length - 1]\n  let dp = new Array(days[days.length - 1] + 1).fill(Infinity);\n  dp[0] = 0;\n\n  for(let i = 1; i< days[days.length - 1] + 1; i++) {\n      if(!store[i]) {\n          dp[i] = dp[i-1];\n          continue;\n      }\n      dp[i] = costs[0] + dp[i-1];\n      dp[i] = Math.min(costs[1] + dp[Math.max(i - 7, 0)], dp[i]);\n      dp[i] = Math.min(costs[2] + dp[Math.max(i - 30, 0)], dp[i]);\n  }\n\n  return dp[lastDay]\n\n};",
        "solution_java": "class Solution {\n    public int mincostTickets(int[] days, int[] costs) {\n        HashSet<Integer> set = new HashSet<>();\n        for(int day: days) set.add(day);\n        int n = days[days.length - 1];\n        int[] dp = new int[n + 1];\n        Arrays.fill(dp, Integer.MAX_VALUE);\n        dp[0] = 0;\n        for(int i = 1; i <= n; i++){\n            if(!set.contains(i)){\n                dp[i] = dp[i - 1];\n                continue;\n            }\n            int a = dp[Math.max(0, i - 1)] + costs[0];\n            int b = dp[Math.max(0, i - 7)] + costs[1];\n            int c = dp[Math.max(0, i - 30)] + costs[2];\n            dp[i] = Math.min(a, Math.min(b, c));\n        }\n        return dp[n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int f(int i,int j,vector<int>& days,vector<int>& costs,vector<vector<int>>& dp) {\n        if (i==days.size()) return 0;\n        if (days[i]<j) return f(i+1,j,days,costs,dp);\n        if (dp[i][j]!=-1) return dp[i][j];\n        int x=costs[0]+f(i+1,days[i]+1,days,costs,dp);\n        int y=costs[1]+f(i+1,days[i]+7,days,costs,dp);\n        int z=costs[2]+f(i+1,days[i]+30,days,costs,dp);\n        return dp[i][j]=min(x,min(y,z));\n    }\n    int mincostTickets(vector<int>& days, vector<int>& costs) {\n        vector<vector<int>> dp(days.size(),vector<int>(days[days.size()-1]+1,-1));\n        return f(0,1,days,costs,dp);\n    }\n};"
    },
    {
        "title": "Circular Array Loop",
        "algo_input": "You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:\n\n\n\tIf nums[i] is positive, move nums[i] steps forward, and\n\tIf nums[i] is negative, move nums[i] steps backward.\n\n\nSince the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.\n\nA cycle in the array consists of a sequence of indices seq of length k where:\n\n\n\tFollowing the movement rules above results in the repeating index sequence seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...\n\tEvery nums[seq[j]] is either all positive or all negative.\n\tk &gt; 1\n\n\nReturn true if there is a cycle in nums, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,-1,1,2,2]\nOutput: true\nExplanation:\nThere is a cycle from index 0 -&gt; 2 -&gt; 3 -&gt; 0 -&gt; ...\nThe cycle's length is 3.\n\n\nExample 2:\n\nInput: nums = [-1,2]\nOutput: false\nExplanation:\nThe sequence from index 1 -&gt; 1 -&gt; 1 -&gt; ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.\n\n\nExample 3:\n\nInput: nums = [-2,1,-1,-2,-2]\nOutput: false\nExplanation:\nThe sequence from index 1 -&gt; 2 -&gt; 1 -&gt; ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t-1000 &lt;= nums[i] &lt;= 1000\n\tnums[i] != 0\n\n\n&nbsp;\nFollow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?\n",
        "solution_py": "class Solution:\n    def circularArrayLoop(self, nums: List[int]) -> bool:\n        n = len(nums)\n        for i in range(n):\n            seen = set()\n            minval = float('inf')\n            maxval = float('-inf')\n            j = i\n            while j not in seen:\n                seen.add(j)\n                minval = min(minval, nums[j])\n                maxval = max(maxval, nums[j])\n                k = 1 + abs(nums[j]) // n\n                j = (k * n + j + nums[j]) % n\n            if j == i and len(seen) > 1 and (minval > 0 or maxval < 0):\n                return True\n        return False",
        "solution_js": "var circularArrayLoop = function(nums) {\n    // cannot be a cycle if there are less than 2 elements\n    const numsLen = nums.length;\n    if (numsLen < 2) return false;\n\n    // init visited array\n    const visited = Array(numsLen).fill(false);\n\n    // check each index to see if a cycle can be produced\n    for (let i = 0; i < numsLen; i++) {\n        if (visited[i]) continue;\n        visited[i] = true;\n        // determine initial direction\n        const isPositive = nums[i] > 0;\n        \n        // reset which indices were visited after each iteration\n        const visitedPerIdx = Array(numsLen).fill(false);\n        \n        // reset cycle length and current index after each iteration\n        let cycleLen = 0,\n            currIdx = i;\n        \n        // loop while cycle is valid\n        while (true) {\n            // break if current index moves cycle in opposite direction\n            if (isPositive !== nums[currIdx] > 0) break;\n\t\t\t\n            // calc next valid index\n            let nextIdx = (currIdx + nums[currIdx]) % numsLen;\n            // map negative index to a positive index\n            if (nextIdx < 0) nextIdx += numsLen; \n          \n            // break if cycle points to same index\n            if (currIdx === nextIdx) break;\n            \n            cycleLen++; \n\t\t\t// a cycle is found when the index has already been visited in the current outer iteration, and\n\t\t\t// the cycle length is greater than 1.\n            if (visitedPerIdx[nextIdx] && cycleLen > 1) return true;\n\t\t\t\n            visitedPerIdx[nextIdx] = true;\n            visited[nextIdx] = true;\n            // set curr index to new index\n            currIdx = nextIdx;\n        }\n    }\n\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean circularArrayLoop(int[] nums) {\n        for (int i=0; i<nums.length; i++) {\n            boolean isForward = nums[i] > 0;\n            int slow = i;\n            int fast = i; \n            do {\n                slow = findNextIndex(nums, isForward, slow);\n                fast = findNextIndex(nums, isForward, fast);\n                if (fast != -1) {\n                    fast = findNextIndex(nums, isForward, fast);\n                }\n            } while (slow != -1 && fast != -1 && slow != fast);\n            if (slow != -1 && slow == fast) {\n                return true;\n            }\n        }\n        return false;\n    }\n    private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {\n        boolean direction = arr[currentIndex] >= 0;\n        if (isForward != direction) {\n            return -1;\n        }\n        int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;\n        if (nextIndex < 0) {\n            nextIndex += arr.length;\n        }\n        if (nextIndex == currentIndex) {\n            nextIndex = -1;\n        }\n        return nextIndex;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool circularArrayLoop(vector<int>& nums) {\n        unordered_set<int>us;\n        for(int i{0};i<nums.size() && us.find(i)==us.end();i++){\n            unordered_map<int,int>um;\n            int index=0;\n            int j=i;\n            um[i];\n            bool flag1=0,flag2=0;\n            while(true){\n                if(nums.at(i)<0){\n                    index=(nums.size()+nums.at(j)+j)%nums.size();\n                    flag1=1;\n                }else{\n                    index=(nums.at(j)+j)%nums.size();\n                    flag2=1;\n                }\n                if(nums.at(index)>0 && flag1==1){\n                    break;\n                }else if(nums.at(index)<0 && flag2==1){\n                    break;\n                }\n                if(um.find(index)==um.end()){\n                    um[index];\n                    us.insert(index);\n                }else{\n                    if(j==index){\n                        break;\n                    }\n                    if(um.size()>1){\n                        return true;\n                    }else{\n                        break;\n                    }\n                }\n                j=index;\n            }            \n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Repeated DNA Sequences",
        "algo_input": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.\n\n\n\tFor example, \"ACGAATTCCG\" is a DNA sequence.\n\n\nWhen studying DNA, it is useful to identify repeated sequences within the DNA.\n\nGiven a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.\n\n&nbsp;\nExample 1:\nInput: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput: [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\nExample 2:\nInput: s = \"AAAAAAAAAAAAA\"\nOutput: [\"AAAAAAAAAA\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either 'A', 'C', 'G', or 'T'.\n\n",
        "solution_py": "class Solution(object):\n    def findRepeatedDnaSequences(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: List[str]\n        \"\"\"\n        seqs = {}\n        i = 0\n        while i+10 <= len(s):\n            curr = s[i:i+10]\n            if curr in seqs:\n                seqs[curr] = seqs[curr] + 1\n            else:\n                seqs[curr] = 1\n            i += 1\n\n        repeats = []\n        for seq in list(seqs.keys()):\n            if seqs[seq] > 1:\n                repeats.append(seq)\n\n        return repeats",
        "solution_js": "// 187. Repeated DNA Sequences\nvar findRepeatedDnaSequences = function(s) {\n    let map = {};\n\tlet res = [];\n\tfor (let i = 0; i <= s.length-10; i++) {\n\t\tlet s10 = s.substring(i, i+10);\n\t\tmap[s10] = (map[s10] || 0) + 1;\n\t\tif (map[s10] === 2) res.push(s10);\n\t}\n\treturn res;\n};",
        "solution_java": "class Solution {\n    public List<String> findRepeatedDnaSequences(String s) {\n        HashMap<String,Integer> map =new HashMap();\n        int i=0;\n        int j=0;\n        int k=10;\n        StringBuilder sb=new StringBuilder(\"\");\n\n        while(j<s.length()){\n            sb.append(s.charAt(j));\n            if(j-i+1<k){\n                j++;\n            }else if(j-i+1==k){\n                if(!map.containsKey(sb.toString())){\n                    map.put(sb.toString(),1);\n                }else{\n                    map.put(sb.toString(),map.get(sb.toString())+1);\n                }\n                sb.deleteCharAt(0);\n                i++;\n                j++;\n            }\n        }\n        List<String> list=new ArrayList();\n        for(Map.Entry<String,Integer> mapElement:map.entrySet()){\n            if(mapElement.getValue()>1){\n                list.add(mapElement.getKey());\n            }\n        }\n        return list;\n    }\n}",
        "solution_c": "class Solution {\n\tpublic:\n\t\tvector<string> findRepeatedDnaSequences(string s) {\n\t\t\tunordered_map<string,int> freq;\n\t\t\tint start = 0 , end = 9;\n\t\t\twhile(end < s.size()){\n\t\t\t\tbool flag = true;\n\t\t\t\tfor(int i = start ; i <= end ; i++){\n\t\t\t\t\tif(s[i] == 'A' or s[i] == 'C' or s[i] == 'G' or s[i] == 'T') continue;\n\t\t\t\t\telse {flag = false ; break ;}\n\t\t\t\t}\n\t\t\t\tif(flag){\n\t\t\t\t\tstring temp = s.substr(start , 10);\n\t\t\t\t\tfreq[temp]++;\n\t\t\t\t}\n\t\t\t\tstart++;\n\t\t\t\tend++;\n\t\t\t}\n\t\t\tvector<string> ans;\n\t\t\tfor(auto it : freq){\n\t\t\t\tif(it.second >= 2) ans.push_back(it.first);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n};"
    },
    {
        "title": "Minimum Number of Frogs Croaking",
        "algo_input": "You are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed.\n\nReturn the minimum number of different frogs to finish all the croaks in the given string.\n\nA valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1.\n\n&nbsp;\nExample 1:\n\nInput: croakOfFrogs = \"croakcroak\"\nOutput: 1 \nExplanation: One frog yelling \"croak\" twice.\n\n\nExample 2:\n\nInput: croakOfFrogs = \"crcoakroak\"\nOutput: 2 \nExplanation: The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".\n\n\nExample 3:\n\nInput: croakOfFrogs = \"croakcrook\"\nOutput: -1\nExplanation: The given string is an invalid combination of \"croak\" from different frogs.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= croakOfFrogs.length &lt;= 105\n\tcroakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.\n\n",
        "solution_py": "class Solution:\n    def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n        c = r = o = a = k = max_frog_croak = present_frog_croak = 0\n        # need to know, at particular point,\n        # what are the max frog are croaking,\n\n        for i, v in enumerate(croakOfFrogs):\n            if v == 'c':\n                c += 1\n\t\t\t\t# c gives a signal for a frog\n                present_frog_croak += 1\n            elif v == 'r':\n                r += 1\n            elif v == 'o':\n                o += 1\n            elif v == 'a':\n                a += 1\n            else:\n                k += 1\n\t\t\t\t# frog stop croaking\n                present_frog_croak -= 1\n\n            max_frog_croak = max(max_frog_croak, present_frog_croak)\n            # if any inoder occurs;\n            if c < r or r < o or o < a or a < k:\n                return -1\n\n        # if all good, else -1\n        if present_frog_croak == 0 and c == r and r == o and o == a and a == k:\n            return max_frog_croak\n        return -1",
        "solution_js": "var minNumberOfFrogs = function(croakOfFrogs) {\n    const croakArr = new Array(5).fill(0); //Array to store occurence of each char\n    let overlap = 0;  //Store the number of overlaps\n    for(let i = 0; i < croakOfFrogs.length; i++) {\n        switch(croakOfFrogs[i]) {\n            case 'c':\n                croakArr[0] += 1;\n                //Check if new start, is overlapping with others\n                if((croakArr[0] - croakArr[4] - overlap) > 1) {\n                    ++overlap;\n                }\n                break;\n            case 'r':\n                //Condition to check if r comes before c\n                if(croakArr[0] <= croakArr[1]) return -1;\n                croakArr[1] += 1;\n                break;\n            case 'o':\n                //Condition to check if o comes before r\n                if(croakArr[1] <= croakArr[2]) return -1;\n                croakArr[2] += 1;\n                break;\n            case 'a':\n                //Condition to check if a comes before o\n                if(croakArr[2] <= croakArr[3]) return -1;\n                croakArr[3] += 1;\n                break;\n            case 'k':\n                //Condition to check if k comes before a\n                if(croakArr[3] <= croakArr[4]) return -1;\n                croakArr[4] += 1;\n                break;\n        }\n    }\n    //Check if all items of array have same count else return -1\n    //If all items have same count return overlap + 1\n    return (Math.max(...croakArr) === Math.min(...croakArr)) ? overlap + 1 : -1;\n};",
        "solution_java": "class Solution {\n    public int minNumberOfFrogs(String croakOfFrogs) {\n        int[] index = new int[26];\n        String corak = \"croak\";\n\n        // Giving index to each characters\n        for (int i = 0; i < corak.length(); ++i)\n            index[corak.charAt(i) - 'a'] = i;\n\n        int ans = 0, sum = 0;\n        int[] count = new int[5];\n\n        for (char c : croakOfFrogs.toCharArray()) {\n            int i = index[c - 'a'];\n            // If it is not 'c' it will decrease the sum\n            if (c != 'c') {\n                if (count[i - 1]-- <= 0) return -1;\n                sum--;\n            }\n            // If it is not 'k' it will increase the sum\n            if (c != 'k') {\n                count[i]++;\n                sum++;\n            }\n            ans = Math.max(ans, sum);\n        }\n        return sum == 0 ? ans : -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minNumberOfFrogs(string croakOfFrogs) {\n        unordered_map<char,int> mp;\n        int size=croakOfFrogs.size();\n        \n        for(int i=0;i<size;i++)\n        {\n            mp[croakOfFrogs[i]]++;\n            if(mp['c']<mp['r'] || mp['r']<mp['o'] || mp['o']<mp['a'] || mp['a']<mp['k'])\n                return -1;\n        }\n        \n        int count=mp[croakOfFrogs[0]];\n        for(auto i:croakOfFrogs)\n        {\n            if(count!=mp[i])\n                return -1;\n        }\n        \n        int ans=0;\n        int i=0;\n        int temp=0;\n        \n        for(i=0;i<size;i++)\n        {\n            if(croakOfFrogs[i]=='c')\n            {\n                temp++;\n            }\n            else if(croakOfFrogs[i]=='k')\n            {\n                temp--;\n            }\n            if(temp>ans)\n                ans=temp;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Unique Binary Search Trees",
        "algo_input": "Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.\n\n&nbsp;\nExample 1:\n\nInput: n = 3\nOutput: 5\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 19\n\n",
        "solution_py": "class Solution(object):\n    def numTrees(self, n):\n        if n == 0 or n == 1:\n            return 1\n        # Create 'sol' array of length n+1...\n        sol = [0] * (n+1)\n        # The value of the first index will be 1.\n        sol[0] = 1\n        # Run a loop from 1 to n+1...\n        for i in range(1, n+1):\n            # Within the above loop, run a nested loop from 0 to i...\n            for j in range(i):\n                # Update the i-th position of the array by adding the multiplication of the respective index...\n                sol[i] += sol[j] * sol[i-j-1]\n        # Return the value of the nth index of the array to get the solution...\n        return sol[n]",
        "solution_js": "var numTrees = function(n) {\n    // Create 'sol' array to store the solution...\n    var sol = [1, 1];\n    // Run a loop from 2 to n...\n    for (let i = 2; i <= n; i++) {\n        sol[i] = 0;\n        // Within the above loop, run a nested loop from 1 to i...\n        for (let j = 1; j <= i; j++) {\n            // Update the i-th position of the array by adding the multiplication of the respective index...\n            sol[i] += sol[i - j] * sol[j - 1];\n        }\n    }\n    // Return the value of the nth index of the array to get the solution...\n    return sol[n];\n};",
        "solution_java": "class Solution {\n    public int numTrees(int n) {\n        // Create 'sol' array of length n+1...\n        int[] sol = new int[n+1];\n        // The value of the first index will be 1.\n        sol[0] = 1;\n        // Run a loop from 1 to n+1...\n        for(int i = 1; i <= n; i++) {\n            // Within the above loop, run a nested loop from 0 to i...\n            for(int j = 0; j < i; j++) {\n                // Update the i-th position of the array by adding the multiplication of the respective index...\n                sol[i] += sol[j] * sol[i-j-1];\n            }\n        }\n        // Return the value of the nth index of the array to get the solution...\n        return sol[n];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int catalan (int n,vector<int> &dp)\n    {\n        if(n<=1)\n            return 1;\n        \n        int ans =0;\n        for(int i=0;i<n;i++)\n        {\n            ans+=catalan(i,dp)*catalan(n-1-i,dp);\n        }\n        \n        return ans;\n    }\n    int numTrees(int n) {\n        \n        vector<int> dp(n+1,-1);\n        \n        dp[0] = 1;\n        dp[1] = 1;\n        \n        for(int i=2;i<=n;i++)\n        {\n            int ans = 0;\n            for(int j=0;j<i;j++)\n            {\n                ans += dp[j]*dp[i-1-j];\n            }\n            dp[i] = ans;\n        }\n        \n        return dp[n];\n        \n        // return catalan(n,dp);\n        \n    }\n};"
    },
    {
        "title": "Filter Restaurants by Vegan-Friendly, Price and Distance",
        "algo_input": "Given the array restaurants where &nbsp;restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.\n\nThe veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true)&nbsp;or false&nbsp;(meaning you can include any restaurant). In addition, you have the filters&nbsp;maxPrice and maxDistance&nbsp;which&nbsp;are the maximum value for price and distance of restaurants you should consider respectively.\n\nReturn the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.\n\n&nbsp;\nExample 1:\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput: [3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). \n\n\nExample 2:\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput: [4,3,2,1,5]\nExplanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.\n\n\nExample 3:\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput: [4,5]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;restaurants.length &lt;= 10^4\n\trestaurants[i].length == 5\n\t1 &lt;=&nbsp;idi, ratingi, pricei, distancei &lt;= 10^5\n\t1 &lt;=&nbsp;maxPrice,&nbsp;maxDistance &lt;= 10^5\n\tveganFriendlyi and&nbsp;veganFriendly&nbsp;are&nbsp;0 or 1.\n\tAll idi are distinct.\n\n",
        "solution_py": "class Solution:\ndef f_fcn(self,restaurants, veganFriendly, maxPrice, maxDistance):\n\tf_lst = filter(lambda x: (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or\n\t\t\t\t   (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance), restaurants)\n\treturn f_lst\n\ndef h_fcn(self,lst):\n\treturn([lst[0], lst[1]])\n\ndef filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n\n\tres = map(self.h_fcn, self.f_fcn(restaurants, veganFriendly, maxPrice, maxDistance))\n\n\n\treturn map(lambda x: x[0], sorted(res, key=lambda x: (-x[1], -x[0])))",
        "solution_js": "var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) {\n    let result = []\n    // veganFriendly filter\n    if(veganFriendly === 1){\n       restaurants = restaurants.filter(restaurant=> restaurant[2] === 1) \n    }\n    \n    //max price\n    restaurants = restaurants.filter(restaurant=>restaurant[3]<=maxPrice)\n    \n    // max distance\n    restaurants = restaurants.filter(restaurant=>restaurant[4]<=maxDistance)\n    \n    restaurants.sort((a,b)=>b[1]-a[1])\n    \n    let tempArr = []\n    for(let i=0; i<restaurants.length;i++){\n        if(restaurants[i+1] && restaurants[i][1]===restaurants[i+1][1] ){\n            tempArr.push(restaurants[i][0])\n            tempArr.push(restaurants[i+1][0])\n            i++\n        }\n        else{\n            if(tempArr.length>0){\n                tempArr.sort((a,b)=>b-a)\n                result =[...result,...tempArr]    \n                tempArr=[]\n            }            \n            result.push(restaurants[i][0])\n        }\n            \n    }\n        \n    return result\n};",
        "solution_java": "class Restaurant {\n    int id, rating;\n    Restaurant(int id, int rating) {\n        this.id = id;\n        this.rating = rating;\n    }\n}\n\nclass RestaurantComparator implements Comparator<Restaurant> {\n    @Override\n    public int compare(Restaurant r1, Restaurant r2) {\n        return r1.rating == r2.rating ? r2.id - r1.id : r2.rating - r1.rating;\n    }\n}\n\nclass Solution {\n    public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {\n        PriorityQueue<Restaurant> heap = new PriorityQueue<>(new RestaurantComparator());\n        if(veganFriendly == 1) {\n            for(int[] restaurant: restaurants) {\n                if(restaurant[2] == 1 && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n                    heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n                }\n            }\n        } else {\n            for(int[] restaurant: restaurants) {\n                if(restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n                    heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n                }\n            }\n        }\n        List<Integer> answer = new ArrayList<>();\n        while(!heap.isEmpty()) {\n            answer.add(heap.poll().id);\n        }\n        return answer;\n    }\n}",
        "solution_c": "//comparator class for sorting restaurants by their rating \nclass comp{\n        public:\n        bool operator ()(vector<int>a,vector<int>b){\n\t\t//same rating then sort by ids\n                if(a[1]==b[1]) return a[0]>b[0];\n                return a[1]>b[1];\n        }\n};\nclass Solution {\npublic:\n        vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance)\n\t\t{ //sort restaurants by their rating\n            sort(restaurants.begin(),restaurants.end(),comp());\n            vector<int>ans;\n            for(int i=0;i<restaurants.size();i++){\n\t\t\t//veganfriendly\n                    if(veganFriendly)\n\t\t\t\t\t{\n\t\t\t\t\t// store ids who satisfy the constraints\n                    if(restaurants[i][2]==veganFriendly and restaurants[i][3]<=maxPrice and  restaurants[i][4]<=maxDistance)\n\t\t\t\t\t        {\n                            ans.push_back(restaurants[i][0]);\n                            }\n                    }\n\t\t\t\t\t// non vegan\n                    else{\n\t\t\t\t\t// store ids who satisfy the constraints\n                            if(restaurants[i][3]<=maxPrice and  restaurants[i][4]<=maxDistance)\n\t\t\t\t\t\t\t{\n                            ans.push_back(restaurants[i][0]);\n                            }\n                    }\n            }\n         return ans;\n    }\n};"
    },
    {
        "title": "Minimum Moves to Move a Box to Their Target Location",
        "algo_input": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\n\nThe game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.\n\nYour task is to move the box 'B' to the target position 'T' under the following rules:\n\n\n\tThe character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).\n\tThe character '.' represents the floor which means a free cell to walk.\n\tThe character '#' represents the wall which means an obstacle (impossible to walk there).\n\tThere is only one box 'B' and one target cell 'T' in the grid.\n\tThe box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.\n\tThe player cannot walk through the box.\n\n\nReturn the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n               [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n               [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n               [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n               [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n               [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 3\nExplanation: We return only the number of times the box is pushed.\n\nExample 2:\n\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n               [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n               [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n               [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n               [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n               [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: -1\n\n\nExample 3:\n\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n               [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n               [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n               [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n               [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n               [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 5\nExplanation: push the box down, left, left, up and up.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 20\n\tgrid contains only characters '.', '#', 'S', 'T', or 'B'.\n\tThere is only one character 'S', 'B', and 'T' in the grid.\n\n",
        "solution_py": "class Solution:\n    def minPushBox(self, grid: List[List[str]]) -> int:\n        m,n=len(grid),len(grid[0])\n        q=deque()\n        start,target,box=(0,0),(0,0),(0,0)\n        for i in range(m):\n            for j in range(n):\n                if grid[i][j]==\"B\":\n                    box=(i,j)\n                elif grid[i][j]==\"T\":\n                    target=(i,j)\n                elif grid[i][j]==\"S\":\n                    start=(i,j)\n        q.append((box[0],box[1],0,start[0],start[1]))\n        visited=set()\n        directions=((1,0,-1,0),(0,1,0,-1),(-1,0,1,0),(0,-1,0,1))\n        visited.add(box+box)\n        def solve(i,j,bi,bj):\n            nonlocal seen\n            if (i,j)==(bi,bj):\n                return True\n            ans=False\n            for d in directions:\n                ni,nj=i+d[0],j+d[1]\n                if 0<=ni<m and 0<=nj<n and (ni,nj) not in seen and grid[ni][nj]!=\"#\":\n                    seen.add((ni,nj))\n                    ans=ans or solve(ni,nj,bi,bj)\n                    if ans: return ans\n            return ans\n        while q:\n            i,j,pushes,si,sj=q.popleft()\n            if (i,j)==target:\n                return pushes\n            if pushes>m+n:\n                return -1\n            for d in directions:\n                ni,nj,bi,bj=i+d[0],j+d[1],i+d[2],j+d[3]\n                if 0<=ni<m and 0<=nj<n and (ni,nj,i,j) not in visited and grid[ni][nj]!=\"#\" and 0<=bi<m and 0<=bj<n and grid[bi][bj]!=\"#\":\n                    seen=set()\n                    seen.add((i,j))\n                    grid[i][j]==\"#\"\n                    res=solve(si,sj,bi,bj)\n                    grid[i][j]=\".\"\n                    if not res:\n                        continue\n                    visited.add((ni,nj,i,j))\n                    q.append((ni,nj,pushes+1,i,j))\n        return -1",
        "solution_js": "/**\n * @param {character[][]} grid\n * @return {number}\n */\nvar minPushBox = function(grid) {\n    // common info & utils\n    const m = grid.length\n    const n = grid[0].length\n    const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n    const add = (a, b) => [a[0] + b[0], a[1] + b[1]]\n    const equals = (a, b) => a[0] === b[0] && a[1] === b[1]\n    const validate = ([x, y]) => x >= 0 && y >= 0 && x < m && y < n\n    const getKey = ([x, y]) => x * n + y\n\n    // find all player, ball, target, and free cells\n    const init = () => {\n        let player\n        let ball\n        let target\n        const freeSet = new Set()\n        for (let i = 0; i < m; i++) {\n            for (let j = 0; j < n; j++) {\n                if (grid[i][j] === '.') {\n                    freeSet.add(getKey([i, j]))\n                } else if (grid[i][j] === 'S') {\n                    freeSet.add(getKey([i, j]))\n                    player = [i, j]\n                } else if (grid[i][j] === 'B') {\n                    freeSet.add(getKey([i, j]))\n                    ball = [i, j]\n                } else if (grid[i][j] === 'T') {\n                    freeSet.add(getKey([i, j]))\n                    target = [i, j]\n                }\n            }\n        }\n        return { player, ball, target, freeSet }\n    }\n    const { player, ball, target, freeSet } = init()\n    const targetKey = getKey(target)\n\n    // detect whether two cells are connected\n    const connCache = new Map() // [x,y,x2,y2,x3,y3] => boolean\n    const getConnKey = (a, b, ball) => {\n        if (\n            a[0] > b[0] ||\n            a[0] === b[0] && a[1] > b[1]\n        ) {\n            [a, b] = [b, a]\n        }\n        return [a[0], a[1], b[0], b[1], ball[0], ball[1]].join(',')\n    }\n    const isConnected = (a, b, ball) => {\n        if (a[0] === b[0] && a[1] === b[1]) {\n            return true\n        }\n        const connKey = getConnKey(a, b, ball)\n        if (connCache.has(connKey)) {\n            return connCache.get(connKey)\n        }\n        const bKey = getKey(b)\n        const ballKey = getKey(ball)\n        const visited = new Array(m * n).fill(false)\n        visited[getKey(a)] = true\n        const queue = [a]\n        while (queue.length) {\n            const cell = queue.shift()\n            for (let i = 0; i < dirs.length; i++) {\n                const next = add(cell, dirs[i])\n                if (validate(next)) {\n                    const nextKey = getKey(next)\n                    if (nextKey === bKey) {\n                        connCache.set(connKey, true)\n                        return true\n                    }\n                    if (\n                        freeSet.has(nextKey) &&\n                        nextKey !== ballKey &&\n                        !visited[nextKey]\n                    ) {\n                        visited[nextKey] = true\n                        queue.push(next)\n                    }\n                }\n            }\n        }\n        connCache.set(connKey, false)\n        return false\n    }\n\n    // solve the game\n    const getStateKey = ([x, y], [xx, yy]) => [x, y, xx, yy].join(',') // ball, player\n    const stateCache = new Set() // Set<stateKey>\n    let queue = [[ball, player]]\n    let count = 1\n    while (queue.length) {\n        const nextQueue = []\n        for (let i = 0; i < queue.length; i++) {\n            const [ball, player] = queue[i]\n            for (let j = 0; j < dirs.length; j++) {\n                const dir = dirs[j]\n                const reverseDir = [dir[0] ? -dir[0] : 0, dir[1] ? -dir[1] : 0]\n                const nextBall = add(ball, dir)\n                const nextPlayer = add(ball, reverseDir)\n                const nextBallKey = getKey(nextBall)\n                const nextPlayerKey = getKey(nextPlayer)\n                if (\n                    validate(nextBall) &&\n                    validate(nextPlayer) &&\n                    freeSet.has(nextBallKey) &&\n                    freeSet.has(nextPlayerKey)\n                ) {\n                    const nextStateKey = getStateKey(nextBall, nextPlayer)\n                    if (isConnected(player, nextPlayer, ball)) {\n                        if (!stateCache.has(nextStateKey)) {\n                            stateCache.add(nextStateKey)\n                            if (nextBallKey === targetKey) {\n                                return count\n                            }\n                            nextQueue.push([nextBall, nextPlayer])\n                        }\n                    }\n                }\n            }\n        }\n        queue = nextQueue\n        count++\n    }\n    return -1\n};",
        "solution_java": "/**\n  Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves)\n  Uses BFS/A* Algorithm to visit valid transition states\n  Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations\n*/\nclass Solution {\n    private int targetRow;\n    private int targetCol;\n    private char[][] grid;\n    private static int[][] DIRS = {\n            {1,0}, //Down\n            {-1,0},//Up\n            {0,1}, //Right\n            {0,-1} //Left\n    };\n\n    /**\n      State holds shopkeeper and box location, as well as how many times the box has been pushed\n    */\n    class State implements Comparable<State>{\n        int personRow;\n        int personCol;\n        int boxRow;\n        int boxCol;\n        int boxPushes;\n\n        public State(int personRow, int personCol, int boxRow, int boxCol, int boxPushes){\n            this.personRow = personRow;\n            this.personCol = personCol;\n            this.boxRow = boxRow;\n            this.boxCol = boxCol;\n            this.boxPushes = boxPushes;\n        }\n\n        // Override equals - used along with hashcode when we have visited HashSet\n        public boolean equals(Object o){\n            State other = (State) o;\n            return\n            this.personRow == other.personRow &&\n            this.personCol == other.personCol &&\n            this.boxRow == other.boxRow &&\n            this.boxCol == other.boxCol;\n        }\n\n        // Override the hashCode - Note: it's okay for this to have collisions\n        // But it won't due to the problem constraint that there is a bound on NxM dimensions\n        public int hashCode(){\n            return personRow *10_000 + personCol * 1_000 + boxRow * 100 + boxCol;\n        }\n\n        // Override to string method - helpful in debugging state.\n        public String toString(){\n            return \"ShopKeeper:{row:\"+personRow+\", col:\"+personCol+\"}\" +\n                   \"Box:{row:\"+boxRow+\", col:\"+boxCol+\"}\";\n        }\n\n        // Implement comparable interface such that we return the state that\n        // has the possibility of lowest distance using box push count + Manhattan distance\n        public int compareTo(State other){\n            int minDistanceThis = this.boxPushes + distanceToTarget(this);\n            int minDistanceOther = other.boxPushes + distanceToTarget(other);\n            return Integer.compare(minDistanceThis, minDistanceOther);\n        }\n\n    }\n\n    // Calculates Manhattan distance\n    private int distanceToTarget(State state){\n        int yDiff = Math.abs(state.boxCol - targetCol);\n        int xDiff = Math.abs(state.boxRow - targetRow);\n        return yDiff + xDiff;\n    }\n\n    /**\n       Given a state, compare box location to target location to determine if it is\n       a solution state.\n    */\n    private boolean isSolutionState(State state){\n        return state.boxRow == targetRow && state.boxCol == targetCol;\n    }\n\n    /**\n        Given a state, finds all valid transition states.\n        This is accomplished by moving the ShopKeeper in all 4 directions and validate\n        - Next ShopKeeper location is in bounds and is not a wall\n\n        We have additional logic for when the next shopkeeper location is the box location:\n        - Get next box location, by pushing the same direction, again validate that\n          the next box location is in bounds, and is not a wall.\n\n        If it's a valid transition, create the new state with the new shop keeper location\n        and if the box moved, the new box location (also increment the number of box moves).\n\n    **/\n    private List<State> getNeighbors(State state){\n\n        int personRow = state.personRow;\n        int personCol = state.personCol;\n        int boxRow = state.boxRow;\n        int boxCol = state.boxCol;\n\n        List<State> states = new ArrayList<>();\n        for(int[] dir : DIRS){\n            int rowMove = dir[0];\n            int colMove = dir[1];\n            int personRowNew = personRow + rowMove;\n            int personColNew = personCol + colMove;\n            // Shopkeeper cannot move into wall or go out of bounds skip to next direction\n            if(!inBounds(personRowNew, personColNew) ||\n               isWall(personRowNew, personColNew)){\n                continue;\n            }\n            // Whether or not person will collide with box\n            boolean willPushBox = personRowNew == boxRow && personColNew == boxCol;\n\n            if(willPushBox){\n                int boxRowNew = boxRow + rowMove;\n                int boxColNew = boxCol + colMove;\n                // Validate box can be pushed - if so push box and add to neighbor states\n                if(inBounds(boxRowNew, boxColNew) &&\n                   !isWall(boxRowNew, boxColNew)){\n                   states.add(new State(personRowNew, personColNew, boxRowNew, boxColNew, state.boxPushes + 1));\n                }\n            } else {\n                //Shop keeper moved, but not box\n                states.add(new State(personRowNew, personColNew, boxRow, boxCol, state.boxPushes));\n            }\n        }\n        return states;\n\n    }\n\n    // Given row/col, return whether it is wall\n    private boolean isWall(int row, int col){\n        char cell = grid[row][col];\n        return cell == '#';\n    }\n\n    // Given row/col return whether is inBounds\n    private boolean inBounds(int row, int col){\n        int rows = grid.length;\n        int cols = grid[0].length;\n        if(row < 0 || col < 0 || row > rows-1 || col > cols-1){\n            return false;\n        }\n        return true;\n    }\n\n    /**\n      Returns initial state. Also finds and stores the target location.\n    */\n    private State getInitialState(){\n\n        int shopKeeperRow=0;\n        int shopKeeperCol=0;\n\n        int boxRow = 0;\n        int boxCol = 0;\n\n        for(int r=0; r<grid.length; r++){\n            char[] row = grid[r];\n            for(int c=0; c<row.length; c++){\n                char cell = grid[r][c];\n                if(cell == 'T'){\n                    this.targetRow = r;\n                    this.targetCol = c;\n                }\n                else if(cell == 'B'){\n                    boxRow = r;\n                    boxCol = c;\n                } else if(cell == 'S'){\n                    shopKeeperRow = r;\n                    shopKeeperCol = c;\n                }\n            }\n        }\n\n        return new State(shopKeeperRow, shopKeeperCol, boxRow, boxCol, 0);\n    }\n\n    public int minPushBox(char[][] grid) {\n        this.grid = grid;\n\n        State initialState = getInitialState();\n        Queue<State> queue = new PriorityQueue<>();\n        Set<State> visited = new HashSet<>();\n        queue.offer(initialState);\n\n        // Explore every state using BSF and keep track of the best solution\n        while(!queue.isEmpty()){\n            State state = queue.poll();\n            if(visited.contains(state)){\n                continue;\n            }\n            visited.add(state);\n            /*\n              Note: the reason we can return the first solution state we find, is because we are\n              using priority queue with minDistance heuristic which means the first solution we find\n              is guaranteed to be the optimal solution - (A* Algorithm)\n            */\n            if(isSolutionState(state)){\n                return state.boxPushes;\n            }\n            for(State neighbor : getNeighbors(state)){\n                if(!visited.contains(neighbor)){\n                    queue.offer(neighbor);\n                }\n            };\n        }\n        // No solution - return -1\n        return -1;\n    }\n\n}",
        "solution_c": "class Solution {\npublic:\n    \n    pair<int,int> t; //target\n    pair<int,int> s; //source\n    pair<int,int> b; //box\n    \n    // struct to store each member in priority queue\n    struct node {\n        int heuristic; // to find the dist between target and box\n        int dist; // to keep track of how much the box moved\n        pair<int,int> src; // to store the source\n        pair<int,int> dest; // to store the box location\n    };\n    \n    struct comp {\n        bool operator()(node const& a, node const& b){\n            return a.heuristic + a.dist > b.heuristic + b.dist;\n        }\n    };\n \n    int direction[4][2]= {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};\n    \n    int minPushBox(vector<vector<char>>& grid) {\n        \n        int m=grid.size();\n        int n=grid[0].size();\n        \n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                if(grid[i][j]=='T')\n                    t={i,j};\n                \n                else if(grid[i][j]=='B')\n                    b={i,j};\n                \n                else if(grid[i][j]=='S')\n                    s={i,j};\n            }\n        }\n        \n        priority_queue<node,vector<node>,comp> pq;\n        set<string> visited;\n        \n        node initialState = node{manhattanDist(b.first,b.second),0,s,b};\n        string initialStr = hash(initialState);\n        \n        pq.push(initialState);\n                \n        while(!pq.empty()){\n            auto cur = pq.top();\n            pq.pop();\n            \n            // we have reached the target return\n            if(cur.dest == t) \n                return cur.dist;\n            \n            // hash the cur string and \n            string cur_vis = hash(cur);\n            if(visited.count(cur_vis)) continue;\n            \n            // mark it as visited\n            visited.insert(cur_vis);\n            \n            // in all the four directions\n            for(auto& dir:direction){\n                int sx = cur.src.first + dir[0];\n                int sy = cur.src.second + dir[1];\n                \n                // if the new source is valid index\n                if(valid(sx,sy,grid)){\n                    \n                    //if the source is equal to the where the box is\n                    if(sx == cur.dest.first && sy == cur.dest.second){\n                        int bx=cur.dest.first + dir[0];\n                        int by=cur.dest.second + dir[1];\n                        \n                        // if the box is at right position\n                        if(valid(bx,by,grid)){\n                            \n                            // increment the dist by 1 and update the source and box location\n                            node updated = node{manhattanDist(bx,by),cur.dist+1,{sx,sy},{bx,by}};\n                            pq.push(updated);\n                        }\n                    }else{\n                        // update the new location of source \n                        node updated = node{cur.heuristic,cur.dist,{sx,sy},cur.dest};\n                        pq.push(updated);\n                    }\n                }\n            }\n        }\n        \n        // we cannot perform the operation\n        return -1;\n        \n    }\n    \n    string hash(node t){\n        stringstream ss;\n        ss<<t.src.first<<\" \"<<t.src.second<<\" \"<<t.dest.first<<\" \"<<t.dest.second;\n        return ss.str();\n    }\n    \n    int manhattanDist(int i, int j){\n        return abs(t.first-i) + abs(t.second-j);\n    }\n    \n    bool valid(int i, int j, vector<vector<char>>& g){\n        \n        if(i<0 || j<0 || i>=g.size() || j>=g[0].size() || g[i][j]=='#') return false;\n        \n        return true;\n    }\n};"
    },
    {
        "title": "Encrypt and Decrypt Strings",
        "algo_input": "You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.\n\nA string is encrypted with the following process:\n\n\n\tFor each character c in the string, we find the index i satisfying keys[i] == c in keys.\n\tReplace c with values[i] in the string.\n\n\nNote that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string \"\" is returned.\n\nA string is decrypted with the following process:\n\n\n\tFor each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.\n\tReplace s with keys[i] in the string.\n\n\nImplement the Encrypter class:\n\n\n\tEncrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary.\n\tString encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.\n\tint decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Encrypter\", \"encrypt\", \"decrypt\"]\n[[['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]], [\"abcd\"], [\"eizfeiam\"]]\nOutput\n[null, \"eizfeiam\", 2]\n\nExplanation\nEncrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]);\nencrypter.encrypt(\"abcd\"); // return \"eizfeiam\". \n&nbsp;                          // 'a' maps to \"ei\", 'b' maps to \"zf\", 'c' maps to \"ei\", and 'd' maps to \"am\".\nencrypter.decrypt(\"eizfeiam\"); // return 2. \n                              // \"ei\" can map to 'a' or 'c', \"zf\" maps to 'b', and \"am\" maps to 'd'. \n                              // Thus, the possible strings after decryption are \"abad\", \"cbad\", \"abcd\", and \"cbcd\". \n                              // 2 of those strings, \"abad\" and \"abcd\", appear in dictionary, so the answer is 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= keys.length == values.length &lt;= 26\n\tvalues[i].length == 2\n\t1 &lt;= dictionary.length &lt;= 100\n\t1 &lt;= dictionary[i].length &lt;= 100\n\tAll keys[i] and dictionary[i] are unique.\n\t1 &lt;= word1.length &lt;= 2000\n\t1 &lt;= word2.length &lt;= 200\n\tAll word1[i] appear in keys.\n\tword2.length is even.\n\tkeys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters.\n\tAt most 200 calls will be made to encrypt and decrypt in total.\n\n",
        "solution_py": "class Encrypter:\n\n    def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n        self.hashmap = dict()\n        for i in range(len(keys)):\n            self.hashmap[keys[i]] = values[i]\n        self.dictmap = defaultdict(int)\n        for word in dictionary:\n            self.dictmap[self.encrypt(word)] += 1\n\n    def encrypt(self, word1: str) -> str:\n        output = ''\n        for char in word1:\n            output += self.hashmap[char]\n        return output\n\n    def decrypt(self, word2: str) -> int:\n        return self.dictmap[word2]",
        "solution_js": "var Encrypter = function(keys, values, dictionary) {\n    this.encryptMap = new Map();\n    for (let i = 0; i < keys.length; i++) {\n        this.encryptMap.set(keys[i], values[i]);\n    }\n    this.dict = new Set(dictionary);\n    // Encypt the values in dict for easy comparison later\n    this.encryptedVals = [];\n    for (let word of this.dict) {\n        this.encryptedVals.push(this.encrypt(word));\n    }\n};\nEncrypter.prototype.encrypt = function(word1) {\n    let encrypted = '';\n    for (let char of word1) {\n        encrypted += this.encryptMap.get(char);\n    }\n    return encrypted;\n};\nEncrypter.prototype.decrypt = function(word2) {\n    return this.encryptedVals.filter(x => x === word2).length;\n};",
        "solution_java": "class Encrypter {\n    \n    Map<String, Integer> encryptedDictCount;\n    int[] keys;\n    Set<String> dictionary;\n    String[] val;\n    \n    public Encrypter(char[] keys, String[] values, String[] dictionary) {\n        this.keys = new int[26];\n        encryptedDictCount = new HashMap<>();\n        this.val = values.clone();\n        this.dictionary = new HashSet<>(Arrays.asList(dictionary));\n        \n        for(int i=0; i<keys.length; i++) {\n            this.keys[keys[i] - 'a'] = i;\n        }\n        \n        for(String dict : dictionary) {\n            String encrpted = encrypt(dict);\n            encryptedDictCount.put(encrpted, encryptedDictCount.getOrDefault(encrpted, 0) + 1);\n        }\n    }\n    \n    public String encrypt(String word1) {\n        StringBuilder sb = new StringBuilder();\n        for(int i =0; i < word1.length(); i++) {\n            int c = word1.charAt(i) - 'a';\n            sb.append(val[keys[c]]);\n        }\n        return sb.toString();\n    }\n    \n    public int decrypt(String word2) {\n        return encryptedDictCount.getOrDefault(word2, 0);\n    }\n}",
        "solution_c": "class Encrypter {\npublic:\n    unordered_set<string> dict;\n    unordered_map<char,string> en;\n    unordered_map<string,vector<char>> dy;\n   \n    Encrypter(vector<char>& keys, vector<string>& values, vector<string>& dictionary) {\n        for(auto& t:dictionary)\n         {   dict.insert(t);}\n        for(int i=0;i<keys.size();i++)\n        {\n            char c=keys[i];\n            string s=values[i];\n            en[c]=s;\n            dy[s].push_back(c);\n        }\n        \n    }\n    \n    string encrypt(string word1) {\n        string ans=\"\";\n        for(char c:word1)\n        {\n            ans+=en[c];\n        }\n        return ans;\n    }\n    \n    int decrypt(string word2) {\n        int cnt=0;\n        for(auto t:dict)\n        {\n            string ans=\"\";\n            for(int i=0;i<t.size();i++)\n            {\n                ans+=en[t[i]];\n            }\n            if(ans==word2)\n                cnt++;\n        }\n        return cnt;\n    }\n \n};"
    },
    {
        "title": "Capacity To Ship Packages Within D Days",
        "algo_input": "A conveyor belt has packages that must be shipped from one port to another within days days.\n\nThe ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.\n\nReturn the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.\n\n&nbsp;\nExample 1:\n\nInput: weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput: 15\nExplanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.\n\n\nExample 2:\n\nInput: weights = [3,2,2,4,1,4], days = 3\nOutput: 6\nExplanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4\n\n\nExample 3:\n\nInput: weights = [1,2,3,1,1], days = 4\nOutput: 3\nExplanation:\n1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= days &lt;= weights.length &lt;= 5 * 104\n\t1 &lt;= weights[i] &lt;= 500\n",
        "solution_py": "class Solution:\n    def shipWithinDays(self, weights: List[int], days: int) -> int:\n        def calc(m):#function calculate no of days for given weight\n            c,s=0,0\n            for i in weights:\n                if i+s>m:\n                    c+=1\n                    s=0\n                s+=i\n            if s>0:\n                c+=1\n            return c\n        left,right=max(weights),sum(weights)\n        while left <=right:\n            mid = (left+right)//2\n            if calc(mid) > days:\n                left = mid+1\n            else :\n                right = mid -1\n        return left",
        "solution_js": "/**\n * @param {number[]} weights\n * @param {number} days\n * @return {number}\n */\nvar shipWithinDays = function(weights, days) {\n    // set left as max of weight, set right as sum of weight\n    let left = Math.max(...weights), right = weights.reduce((a, b) => a + b);\n\n    // max weight cannot exceed the capacity of ship\n    while (left < right) {\n        // set middle weight\n        const m = Math.floor((left + right) / 2);\n        // reset weight if can be load\n        can(m) ? (left = m + 1) : (right = m);\n    }\n\n    // result\n    return left;\n\n    // check if load can be\n    function can(v) {\n        let need = 1, current = 0;\n\n        for (let i of weights) {\n            if (current + i > v) {\n                need++;\n                current = i;\n            }\n            else {\n                current += i;\n            }\n        }\n\n        return need > days;\n    }\n};",
        "solution_java": "class Solution {\n    public int shipWithinDays(int[] weights, int days) {\n        int left = 0;\n        int right = 0;\n        //  left is the biggest element in the array. It's set as the lower boundary.\n        //  right is the sum of the array, which is the upper limit. \n        for (int weight : weights) {\n            left = Math.max(weight, left);\n            right += weight;\n        }\n        int res = 0;\n        while (left <= right) {\n            int mid = (left + right) / 2;\n            // make sure mid is a possible value \n            if (isPossible(weights, days, mid)) {\n                res = mid;\n                right = mid - 1;\n            } else {\n                left = mid + 1;\n            }\n        }\n        return res;\n    }\n    \n    public boolean isPossible(int [] weights, int days, int mid) {\n        int totalDays = 1;\n        int totalWeight = 0;\n        for (int i = 0; i < weights.length; i++) {\n            totalWeight += weights[i];\n            // increase totalDays if totalWeight is larger than mid\n            if (totalWeight > mid) {\n                totalDays++;\n                totalWeight = weights[i]; \n            } \n            // the problem states all the packages have to ship within `days` days \n            if (totalDays > days) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n    // function to check if it is possible to ship all the items within the given number of days using a given weight capacity\n    bool isPossible(int cp, vector<int>& weights, int days)\n    {\n        int d = 1;\n        int cw = 0;\n        // iterate through the weights and check if it is possible to ship all the items\n        for (auto x : weights) {\n            if (x + cw <= cp) {\n                // if the current weight can be added to the current capacity, add it\n                cw += x;\n            } else {\n                // if not, increment the number of days required for shipping and start a new shipment\n                d++;\n                cw = x;\n                if (x > cp) {\n                    // if the current weight is greater than the current capacity, it is impossible to ship all the items\n                    return false;\n                }\n            }\n        }\n        // check if it is possible to ship all the items within the given number of days\n        return d <= days;\n    }\n    \n    // function to find the minimum weight capacity required to ship all the items within the given number of days\n    int shipWithinDays(vector<int>& weights, int days)\n    {\n        // initialize the search range for the weight capacity\n        int s = 1;\n        int e = 1E9;\n        int ans = -1;\n        \n        // perform binary search on the weight capacity range\n        while (s <= e) {\n            // set the mid-point of the range as the current weight capacity\n            int mid = (s + e) / 2;\n            \n            // check if it is possible to ship all the items within the given number of days using the current weight capacity\n            bool ok = isPossible(mid, weights, days);\n            \n            // if it is possible to ship all the items within the given number of days using the current weight capacity,\n            // set the current weight capacity as the new answer and reduce the upper bound of the weight capacity range\n            if (ok) {\n                ans = mid;\n                e = mid - 1;\n            } else {\n                // if it is not possible to ship all the items within the given number of days using the current weight capacity,\n                // increase the lower bound of the weight capacity range\n                s = mid + 1;\n            }\n        }\n        \n        // return the minimum weight capacity required to ship all the items within the given number of days\n        return ans;\n    }\n};"
    },
    {
        "title": "Reverse Nodes in k-Group",
        "algo_input": "Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.\n\nk is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.\n\nYou may not alter the values in the list's nodes, only nodes themselves may be changed.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [2,1,4,3,5]\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5], k = 3\nOutput: [3,2,1,4,5]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 &lt;= k &lt;= n &lt;= 5000\n\t0 &lt;= Node.val &lt;= 1000\n\n\n&nbsp;\nFollow-up: Can you solve the problem in O(1) extra memory space?\n",
        "solution_py": "# Definition for singly-linked list.\nclass ListNode:\n    def __init__(self, val=0, next=None):\n        self.val = val\n        self.next = next\n\n\nclass Solution:\n    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n\n        # Intialize the result and the current node to the head\n        res = node = head\n\n        # Initialize the index of the current node to 0\n        i = 0\n\n        # Initialize the head and tail of the reversed nodes group to None\n        reversedHead, reversedTail = None, None\n\n        # Initialize the tail of the previous group to None\n        previousTail = None\n\n        # Iterate through all nodes\n        while node:\n\n            # When we reach the first node in a group\n            if i % k == 0:\n\n                # If there is a previous group, connect its tail to the current node\n                # This is the case when we have less than k nodes left\n                if previousTail:\n                    previousTail.next = node\n\n                # Initialize the head and tail of the reversed nodes group\n                reversedHead = reversedTail = ListNode(node.val)\n\n            # Continue to reverse subsequent nodes\n            else:\n                reversedHead = ListNode(node.val, reversedHead)\n\n            # If we are able to reach the last node in a reversed nodes group\n            if i % k == k - 1:\n\n                # If there is a previous group, connect its tail to the current node\n                # This is the case when we have k nodes and thus, we should reverse this group\n                if previousTail:\n                    previousTail.next = reversedHead\n\n                # Set the tail of the previous group to the tail of the reversed nodes group\n                previousTail = reversedTail\n\n            # Set the head of the first reversed nodes group as the result\n            if i == k - 1:\n                res = reversedHead\n\n            # Continue to the next node\n            i, node = i + 1, node.next\n\n        return res",
        "solution_js": "var reverseKGroup = function(head, k) {\n    const helper = (node) => {\n        let ptr = node;\n        \n        let t = k;\n        let prev = null;\n        \n        while(t && ptr) {\n            prev = ptr;\n            ptr = ptr.next;\n            t -= 1;\n        }\n        \n        if(t > 0) //if k is not zero then do not reverse, simply return;\n            return node;\n        \n        let f = prev.next;\n        prev.next = null;\n        \n        let [rev, end] = reverseList(node);\n        \n        end.next = helper(f);\n        \n        return rev;\n    }\n    \n    return helper(head);\n};\n\nvar reverseList = function(head) {\n        let prev = null;\n        let current = head;\n        let end = head;\n\n        while(current) {\n            let next = current.next;\n            current.next = prev;\n            prev = current;\n            current = next;\n        }\n\n        return [prev, end];\n };",
        "solution_java": "class Solution {\n    public ListNode reverseKGroup(ListNode head, int k) {\n        int numOfNodes = count(head);\n        ListNode ptr = null;\n        List<ListNode> start = new ArrayList<>(), end = new ArrayList<>();\n        ListNode f = null;\n        while (head != null) {\n            if (numOfNodes >= k) {\n                start.add(head);\n                int count = 0;\n                while (count < k) {\n                    ListNode temp = head.next;\n                    head.next = ptr;\n                    ptr = head;\n                    head = temp;\n                    count++;\n                }\n                end.add(ptr);\n                ptr = null;\n                numOfNodes -= count;\n            }\n            else {\n                f = head;\n                break;\n            }\n        }\n        int n = start.size();\n        for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);\n        start.get(n - 1).next = f;\n        return end.get(0);\n    }\n    public int count(ListNode head) {\n        ListNode temp = head;\n        int count = 0;\n        while (temp != null) {\n            count++;\n            temp = temp.next;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\n    pair<ListNode* , ListNode*> get_rev_list(ListNode* root){\n        ListNode *tail = root;\n        ListNode *curr = root , *temp , *prev = NULL;\n        \n        while(curr != NULL){\n            temp = curr -> next;\n            curr -> next = prev;\n            \n            prev = curr;\n            curr = temp;\n        }\n        \n        return make_pair(prev , tail);\n    }\n    \n    public:\n    ListNode* reverseKGroup(ListNode* head, int k) {\n        if(k == 1)\n            return head;\n        \n        vector<pair<ListNode* , ListNode*>> store;\n        \n        ListNode *temp = head , *temp_head = head;\n        int len = 0;\n        \n        while(temp != NULL){\n            len++;\n            \n            if(len == k){\n                ListNode *next_head = temp -> next;\n                temp -> next = NULL;\n                \n                store.push_back(get_rev_list(temp_head));\n                temp = next_head;\n                len = 0;\n                temp_head = next_head;\n            }\n            else\n                temp = temp -> next;\n        }\n        \n        if(len == k)\n        store.push_back(get_rev_list(temp_head));\n        \n        for(int i = 1; i < store.size(); i++)\n            store[i - 1].second -> next = store[i].first;\n        \n        if(len != k)\n            store[store.size() - 1].second -> next = temp_head;\n        \n        return store[0].first;\n    }\n};"
    },
    {
        "title": "Making A Large Island",
        "algo_input": "You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.\n\nReturn the size of the largest island in grid after applying this operation.\n\nAn island is a 4-directionally connected group of 1s.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[1,0],[0,1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n\n\nExample 2:\n\nInput: grid = [[1,1],[1,0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n\nExample 3:\n\nInput: grid = [[1,1],[1,1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 4.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 &lt;= n &lt;= 500\n\tgrid[i][j] is either 0 or 1.\n",
        "solution_py": "class Solution:\n    def largestIsland(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        # parent array to keey track\n        parent = list(range(m*n))\n        # rank array used for union by rank and size calculation\n        rank = [1 for _ in range(m*n)]\n        \n        # standard DSU find function\n        def find(x):\n            while x != parent[x]:\n                parent[x] = parent[parent[x]]\n                x = parent[x]\n            return x\n        \n        # standard DSU union by rank function\n        def union(x,y):\n            parX, parY = find(x), find(y)\n            if parX == parY: return\n            if rank[parX] >= rank[parY]:\n                rank[parX] += rank[parY]\n                parent[parY] = parX\n            else:\n                rank[parY] += rank[parX]\n                parent[parX] = parY\n    \n        # Step 1: join the land\n\n        # for each island we perform union operation\n        for i, row in enumerate(grid):\n            for j, val in enumerate(row):\n                \n                # important condition: if we have a water body, we set its rank to 0 (will be used in the next step)\n                if not val: \n                    rank[i*m+j] = 0\n                    continue\n                \n                # performing union of land bodies\n                for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n                    # outside of grid check\n                    if not (0 <= x < m and 0 <= y < n): continue\n                    \n                    if grid[x][y]: union(i*m+j, x*m+y)\n        \n        # Step 2: convert a water body (if present)\n        \n        # the minimum final ans will always be the size of the largest land present \n        ans = max(rank)\n        for i, row in enumerate(grid):\n            for j, val in enumerate(row):\n                \n                # we dont need to do anything if we encounter a land\n                if val: continue\n                \n                neighbours = set()\n                res = 0\n                \n                # \n                for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n                    # outside of grid check\n                    if not (0 <= x < m and 0 <= y < n): continue\n                        \n                    # checking unique neighbours by adding the parent to the set\n                    # here we dont care if the neighbour is water as its rank is 0 so it contributes nothing\n                    idx = x*m+y\n                    neighbours.add(find(idx))\n                \n                # Once we have all unique neighbours, just add their ranks\n                for idx in neighbours:\n                    res += rank[idx]\n                \n                # res + 1 because we convert the current cell (i,j) to land too\n                ans = max(ans, res+1)\n        \n        return ans",
        "solution_js": "var largestIsland = function(grid) {\n    const n = grid.length\n\t/**\n\t *  Create the merge find (union find) structure --> https://www.youtube.com/watch?v=ibjEGG7ylHk\n\t *  For this case, we will form the sets at once, already assigning the same representative to all members.\n\t *  Thus, we can use this simplistic implementation without path compression and find(i) = mf[i]\n\t */\n    const mf = []\n    for (let i = 0; i < n*n; i++) {\n        mf.push(i)\n    }\n\t// Helper that converts coordinates to array position\n    const toPos = (r, c) => r * n + c\n\t// Recursively set the merge find structure to represent the islands' map\n    const merge = (r, c, repr) => {\n        mf[toPos(r, c)] = repr // Merge coordinate\n\t\t/**\n\t\t *  Visit neighbors. To visit a neighboring coordinate we first check for:\n\t\t *  Boundaries (coordinates stay within matrix limits)\n\t\t *  Neighbor is land (contains a 1)\n\t\t *  We didn't visit it already (has different representative)\n\t\t */\n        if (r > 0 && grid[r-1][c] === 1 && mf[toPos(r-1, c)] !== repr) { // Top\n            merge(r-1, c, repr)\n        }\n        if (c < n-1 && grid[r][c+1] === 1 && mf[toPos(r, c+1)] !== repr) { // Right\n            merge(r, c+1, repr)\n        }\n        if (r < n-1 && grid[r+1][c] === 1 && mf[toPos(r+1, c)] !== repr) { // Bottom\n            merge(r+1, c, repr)\n        }\n        if (c > 0 && grid[r][c-1] === 1 && mf[toPos(r, c-1)] !== repr) { // Left\n            merge(r, c-1, repr)\n        }\n    }\n\t/**\n\t *  For each land (1) position that wasn't already merged into a set,\n\t *  we define a new set with its neighbors.\n\t */\n    for (let i = 0; i < n; i++) {\n        for (let j = 0; j < n; j++) {\n            const pos = toPos(i, j)\n            if (grid[i][j] === 1 && mf[pos] === pos) {\n                merge(i, j, pos)\n            } \n        }\n    }\n\t/**\n\t *  We can now calculate the surface of every island by counting the number of cells\n\t *  with the same representative.\n\t */\n    const count = Array(n*n).fill(0)\n    mf.forEach(el => count[el]++)\n    /**\n\t *  Now we have to decide on which sea (0) should be toggled into land (1).\n\t *  For this we save, for each zero, which sets it is contact with. Once this is done,\n\t *  we can calculate the entire surface by suming 1 + the surface of all touching sets.\n\t *  Again, to add the neighbor set to the store, we need to check that it is a one, that we\n\t *  are within the boundaries, and that it was not already marked as neighbor.\n\t *  We store the maximum surface found, which is the final solution.\n\t */\n    let maxSurface = 0\n    for (let r = 0; r < n; r++) {\n        for (let c = 0; c < n; c++) {\n            if (grid[r][c] === 0) {\n                const touching = []\n                let currentSurface = 1\n                if (r > 0 && grid[r-1][c] === 1 && !touching.includes(mf[toPos(r-1, c)])) { // Top\n                    touching.push(mf[toPos(r-1,c)])\n                }\n                if (c < n-1 && grid[r][c+1] === 1 && !touching.includes(mf[toPos(r, c+1)])) { // Right\n                    touching.push(mf[toPos(r,c+1)])\n                }\n                if (r < n-1 && grid[r+1][c] === 1 && !touching.includes(mf[toPos(r+1, c)])) { // Bottom\n                    touching.push(mf[toPos(r+1, c)])\n                }\n                if (c > 0 && grid[r][c-1] === 1 && !touching.includes(mf[toPos(r, c-1)])) { // Left\n                    touching.push(mf[toPos(r, c-1)])\n                }\n                touching.forEach(set => currentSurface += count[set])\n                if (currentSurface > maxSurface) {\n                    maxSurface = currentSurface\n                }\n            } \n        }\n    }\n    /**\n\t * If maxSurface remained at zero, it means the input is a matrix of ones.\n\t */\n    if (maxSurface > 0) { return maxSurface }\n    return n*n\n}",
        "solution_java": "class Solution {\n    int dir[][] = new int[][]{\n        {1, 0},\n        {-1,0},\n        {0,1},\n        {0,-1}\n    };\n    private int countArea(int grid[][], int i, int j, int num){\n        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)\n            return 0;\n        \n        if(grid[i][j] != 1) return 0;\n        \n        grid[i][j] = num;\n        int count = 0;\n        for(int d[] : dir){\n            count += countArea(grid, i + d[0], j + d[1], num);\n        }\n        \n        return 1 + count;\n    }\n    \n    private void fillDP(int grid[][], int dp[][], int i, int j, int count, int num){\n        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return ;\n        \n        if(grid[i][j] != num) return;\n        \n        if(dp[i][j] != 0) return ;\n        dp[i][j] = count;\n        for(int d[] : dir){\n            fillDP(grid, dp, i + d[0], j + d[1], count, num);\n        }\n        \n    }\n    \n    \n    public int largestIsland(int[][] grid) {\n        int n = grid.length, m = grid[0].length;\n        int dp[][] = new int[n][m];\n        \n        int num = 1;\n        for(int i = 0; i < n; ++i){\n            for(int j = 0; j < m; ++j){\n                if(grid[i][j] == 1){\n                    ++num;\n                    int count1 = countArea(grid, i, j, num);\n                    fillDP(grid, dp, i, j, count1, num);\n                }\n            }\n        }\n        \n        int max = 0;\n        for(int i = 0; i < n; ++i){\n            for(int j = 0; j < m; ++j){\n                if(grid[i][j] != 0) continue;\n                int val = 1;\n                Set<Integer> set = new HashSet<>();\n                for(int d[] : dir){\n                    int newRow = i + d[0];\n                    int newCol = j + d[1];\n                    \n                    if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= m) continue;\n                    if(set.contains(grid[newRow][newCol])) continue;\n                    \n                    val += dp[newRow][newCol];\n                    set.add(grid[newRow][newCol]);\n                }\n                max = Math.max(max, val);\n            }\n        }\n        \n        if(max == 0) return n * m;\n        return max;\n        \n    }\n}",
        "solution_c": "class Solution {\n    int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};\n    \n    bool isValid(vector<vector<int>>const &grid,vector<vector<int>> &visited, int row, int col){\n        int n=grid.size();\n        \n        if(row<0 || row>=n || col<0 || col>=n || grid[row][col]!=1 || visited[row][col]!=0){\n            return false;\n        }\n        return true;\n    }\n    \n    int helper(vector<vector<int>>const &grid,vector<vector<int>> &visited, int row, int col){\n        \n        if(!isValid(grid,visited,row,col)) return 0;\n        \n        visited[row][col]=1;\n            \n       \n           \n       return 1+helper(grid,visited, row+dir[0][0], col+dir[0][1])+\n                helper(grid,visited, row+dir[1][0], col+dir[1][1])+\n                helper(grid,visited, row+dir[2][0], col+dir[2][1])+\n                helper(grid,visited, row+dir[3][0], col+dir[3][1]);\n        \n        return 0;\n    }\npublic:\n    int largestIsland(vector<vector<int>>& grid) {\n        int ans=0;\n        int n=grid.size();\n        for(int i=0;i<n;i++){\n            for(int j=0;j<grid.size();j++){\n                \n                if(grid[i][j]==0){\n                    grid[i][j]=1;\n                    vector<vector<int>> visited(n,vector<int>(n,0));\n                    ans=max(ans,helper(grid,visited, i,j));\n                    grid[i][j]=0;\n                }\n                \n            }\n        }\n        return ans==0?n*n:ans;\n    }\n};"
    },
    {
        "title": "Verbal Arithmetic Puzzle",
        "algo_input": "Given an equation, represented by words on the left side and the result on the right side.\n\nYou need to check if the equation is solvable under the following rules:\n\n\n\tEach character is decoded as one digit (0 - 9).\n\tNo two characters can map to the same digit.\n\tEach words[i] and result are decoded as one number without leading zeros.\n\tSum of numbers on the left side (words) will equal to the number on the right side (result).\n\n\nReturn true if the equation is solvable, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput: true\nExplanation: Map 'S'-&gt; 9, 'E'-&gt;5, 'N'-&gt;6, 'D'-&gt;7, 'M'-&gt;1, 'O'-&gt;0, 'R'-&gt;8, 'Y'-&gt;'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" ,  9567 + 1085 = 10652\n\nExample 2:\n\nInput: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput: true\nExplanation: Map 'S'-&gt; 6, 'I'-&gt;5, 'X'-&gt;0, 'E'-&gt;8, 'V'-&gt;7, 'N'-&gt;2, 'T'-&gt;1, 'W'-&gt;'3', 'Y'-&gt;4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" ,  650 + 68782 + 68782 = 138214\n\nExample 3:\n\nInput: words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput: false\nExplanation: There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= words.length &lt;= 5\n\t1 &lt;= words[i].length, result.length &lt;= 7\n\twords[i], result contain only uppercase English letters.\n\tThe number of different characters used in the expression is at most 10.\n\n",
        "solution_py": "class Solution:\n    def isSolvable(self, words: List[str], result: str) -> bool:\n        \n        # reverse words\n        words = [i[::-1] for i in words]\n        result = result[::-1]\n        allWords = words + [result]\n        \n        # chars that can not be 0\n        nonZero = set()\n        for word in allWords:\n            if len(word) > 1:\n                nonZero.add(word[-1])\n        \n        # numbers selected in backtracking\n        selected = set()\n        # char to Int map\n        charToInt = dict()\n        mxLen = max([len(i) for i in allWords])\n        \n        def res(i = 0, c = 0, sm = 0):\n            if c == mxLen:\n                return 1 if sm == 0 else 0\n            elif i == len(words):\n                num = sm % 10\n                carry = sm // 10\n                if c >= len(result):\n                    if num == 0:\n                        return res(0, c+1, carry)\n                    else:\n                        return 0\n                # result[c] should be mapped to num if a mapping exists\n                if result[c] in charToInt:\n                    if charToInt[result[c]] != num:\n                        return 0\n                    else:\n                        return res(0, c+1, carry)\n                elif num in selected:\n                    return 0\n                # if mapping does not exist, create a mapping\n                elif (num == 0 and result[c] not in nonZero) or num > 0:\n                    selected.add(num)\n                    charToInt[result[c]] = num\n                    ret = res(0, c + 1, carry)\n                    del charToInt[result[c]]\n                    selected.remove(num)\n                    return ret\n                else:\n                    return 0\n            else:\n                word = words[i]\n                if c >= len(word):\n                    return res(i+1, c, sm)\n                elif word[c] in charToInt:\n                    return res(i+1, c, sm + charToInt[word[c]])\n                else:\n                    ret = 0\n                    # possibilities for word[c]\n                    for j in range(10):\n                        if (j == 0 and word[c] not in nonZero) or j > 0:\n                            if j not in selected:\n                                selected.add(j)\n                                charToInt[word[c]] = j\n                                ret += res(i + 1, c, sm + j)\n                                del charToInt[word[c]]\n                                selected.remove(j)\n                    return ret\n        \n        return res() > 0",
        "solution_js": "/**\n * @param {string[]} words\n * @param {string} result\n * @return {boolean}\n */\nvar isSolvable = function(words, result) {\n  // set to hold all the first characters\n  const firstChars = new Set();\n  \n  // map for steps 1 & 2\n  // this will hold the key as the character and multiple as the value\n  let map = {};\n  for (let i = 0; i < result.length; i++) {\n      const char = result[i];\n      if (!i) firstChars.add(char);\n      if (!map.hasOwnProperty(char)) map[char] = 0;\n      map[char] -= 10 ** (result.length - i - 1);\n    }\n    for (let j = 0; j < words.length; j++) {\n      const word = words[j];\n      for (let i = 0; i < word.length; i++) {\n        const char = word[i];\n        if (!i) firstChars.add(char);\n        if (!map.hasOwnProperty(char)) map[char] = 0;\n        map[char] += 10 ** (word.length - i - 1);\n      }\n  }\n  \n  // Step 3: we group the positive and negative values\n  const positives = [];\n  const negatives = [];\n  Object.entries(map).forEach((entry) => {\n    if (entry[1] < 0) negatives.push(entry);\n    else positives.push(entry);\n  })\n\n  // Step 4: backtrack\n  const numsUsed = new Set();\n  const backtrack = (val = 0) => {\n    // if we have used all the characters and the value is 0 the input is solvable\n    if (!positives.length && !negatives.length) return val === 0;\n\t\n\t// get the store that we are going to examine depending on the value\n    let store = val > 0 || (val === 0 && negatives.length) ? negatives : positives;\n    if (store.length === 0) return false;\n    const entry = store.pop();\n    const [char, multiple] = entry;\n\t\n\t// try every possible value watching out for the edge case that it was a first character\n    for (let i = firstChars.has(char) ? 1 : 0; i < 10; i++) {\n      if (numsUsed.has(i)) continue;\n      numsUsed.add(i);\n      if (backtrack(i * multiple + val)) return true;\n      numsUsed.delete(i);\n    }\n    store.push(entry);\n    return false;\n  }\n  return backtrack();\n};",
        "solution_java": "class Solution {\n     public static boolean isSolvable(String[] words, String result) {\n\t    // reverse all strings to facilitate add calculation.\n        for (int i = 0; i < words.length; i++) {\n            words[i] = new StringBuilder(words[i]).reverse().toString();\n        }\n        result = new StringBuilder(result).reverse().toString();\n        if (!checkLength(words, result)) {\n            return false;\n        }\n        boolean[] visited = new boolean[10];    // digit 0, 1, ..., 9\n        int[] chToDigit = new int[26];\n        Arrays.fill(chToDigit, -1);\n        return dfs(0, 0, 0, visited, chToDigit, words, result);\n    }\n\n    /**\n     * Elminate the case where result is too long\n     * word1:  AAA\n     * word2:  BBB\n     * result: XXXXXXXXX\n     */\n    private static boolean checkLength(String[] words, String result) {\n        int maxLen = 0;\n        for (String word : words) {\n            maxLen = Math.max(maxLen, word.length());\n        }\n        return result.length() == maxLen || result.length() == maxLen + 1;\n    }\n\n    /*\n    Put all words like this:\n    w1:     ABC\n    w2:     EF\n    w3:     GHIJ\n    result: KLMNO\n    i, is the row\n    j,  is the column\n    carrier, the one contributed from previous calculation\n    chToDigit, 26 int array, which records choosen digit for 'A', 'B', 'C', ... If not choosen any, default is -1 \n     */\n    private static boolean dfs(int i, int j, int carrier, boolean[] visited, int[] chToDigit, String[] words, String result) {\n        if (i == words.length) {\n            char ch = result.charAt(j);\n            // (i, i) at bottom right corner. final check\n            if (j == result.length() - 1) {\n                // 1. check if carrier is equal or greater than 10. If so, false.\n                if (carrier >= 10) {\n                    return false;\n                }\n                // 2. check if result.length() > 1 && result.lastCh is zero. If so the false.\n                if (j > 0 && j == result.length() - 1 && chToDigit[ch - 'A'] == 0) {\n                    return false;\n                }\n                // not selected, can select any. True.\n                if (chToDigit[ch - 'A'] == -1) {\n                    System.out.println(Arrays.toString(chToDigit));\n                    return true;\n                } else {    // if selected, check if it matches with carrier. Also, carrier can't be 0. result = '00' is invalid\n                    return chToDigit[ch - 'A'] == carrier;\n                }\n            } else {    // reached normal result line.\n                // 1. if not selected. Use current carrier's unit digit\n                if (chToDigit[ch - 'A'] == -1) {\n                    int selectedDigit = carrier % 10;\n                    // For example carrier = 13. selectedDigit = 3. ch = 'H'. Should set 3 to 'H'.\n                    // But 3 is already taken by 'B' previously. So wrong.\n                    if (visited[selectedDigit]) {\n                        return false;\n                    }\n                    visited[selectedDigit] = true;\n                    chToDigit[ch - 'A'] = selectedDigit;\n                    if (dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result)) {\n                        return true;\n                    }\n                    chToDigit[ch - 'A'] = -1;\n                    visited[selectedDigit] = false;\n                } else { // 2. selected\n                    // just need to check if ch.digit equals to unit digit.\n                    if (chToDigit[ch - 'A'] != carrier % 10) {\n                        return false;\n                    }\n                    boolean ans = dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result);\n                    return ans;\n                }\n            } //\n        } else { // normal word\n            String word = words[i];\n            // 1. check if j is equal or greater than word.len. If so pass to next word.\n            if (j >= word.length()) {\n                boolean ans = dfs(i + 1, j, carrier, visited, chToDigit, words, result);\n                return ans;\n            }\n            // 2. check if it's last ch, word.len is greater than 1, and is '0'. If so false;\n            if (j == word.length() - 1 && word.length() > 1 && chToDigit[word.charAt(j) - 'A'] == 0) {\n                return false;\n            }\n            char ch = word.charAt(j);\n            // 3. check if word.ch is selected. Just add current digit and move to next word.\n            if (chToDigit[ch - 'A'] != -1) {\n                int newSum = carrier + chToDigit[ch - 'A'];\n                boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n                return ans;\n            } else {\n                for (int k = 0; k < visited.length; k++) {\n                    if (visited[k]) {\n                        continue;\n                    }\n                    visited[k] = true;\n                    chToDigit[ch - 'A'] = k;\n                    int newSum = k + carrier;\n                    boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n                    if (ans) {\n                        return true;\n                    }\n                    visited[k] = false;\n                    chToDigit[ch - 'A'] = -1;\n                }\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\n    int limit = 0;\n    unordered_map<char, int> c2i;\n    unordered_map<int, char> i2c;\n    bool helper(vector<string> &words, string &result, int digit, int wid, int sum)\n    {\n        if(digit==limit)\n            return sum == 0;\n        if(wid==words.size())\n        {\n            if(c2i.count(result[digit])==0 && i2c.count(sum%10)==0)\n            {\n                if(sum%10==0 && digit+1 == limit)\n                    return false; //Means leading zeros\n                c2i[result[digit]] = sum%10;\n                i2c[sum%10] = result[digit];\n                bool tmp = helper(words, result, digit+1, 0, sum/10); //0 because it will\n                //go one digit at a time until all digits in words are finished\n                c2i.erase(result[digit]);\n                i2c.erase(sum%10);\n                return tmp;\n            }\n            else if(c2i.count(result[digit]) && c2i[result[digit]] == sum%10) //c2i for that exits and is equal to sum%10, remember default will be 0 and sum%10 can also be 0\n            {\n                if(digit+1 == limit && c2i[result[digit]]==0)\n                    return false; //again same condition of leading zeros\n                return helper(words, result, digit+1, 0, sum/10);\n            }\n            else //if result[digit] exists in c2i but is not equal to sum%10\n                return false;\n        }\n        if(digit>=words[wid].length()) //digit>current words length\n            return helper(words, result, digit, wid+1, sum); //go to next word at same position\n        //(digit) and sum, also going wid + 1 that is why checking wid limit in last condition already\n        if(c2i.count(words[wid][digit]))\n        {\n            if(digit+1 == words[wid].length() && words[wid].length() > 1 && c2i[words[wid][digit]]==0)\n                return false; //here we checking if there is no leading 0 in the word itself\n            return helper(words, result, digit, wid+1, sum+c2i[words[wid][digit]]);\n        }\n        for(int i=0; i<10; i++)\n        {\n            if(digit+1==words[wid].length() && i==0 && words[wid].length()>1)\n                continue;\n            if (i2c.count(i))\n                continue;\n            c2i[words[wid][digit]] = i;\n            i2c[i] = words[wid][digit];\n            bool tmp = helper(words, result, digit, wid+1, sum+i);\n            c2i.erase(words[wid][digit]);\n            i2c.erase(i);\n            if(tmp)\n                return true;\n        }\n        return false;\n    }\n    \npublic:\n    bool isSolvable(vector<string>& words, string result) {\n        limit = result.length();\n        for(auto s:words)\n        {\n            if(s.length()>limit)\n                return false;\n        }\n        for(auto &s:words)\n        {\n            reverse(s.begin(), s.end());\n        }\n        reverse(result.begin(), result.end());\n        return helper(words, result, 0, 0, 0);\n    }\n};"
    },
    {
        "title": "Maximum Depth of Binary Tree",
        "algo_input": "Given the root of a binary tree, return its maximum depth.\n\nA binary tree's maximum depth&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 3\n\n\nExample 2:\n\nInput: root = [1,null,2]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-100 &lt;= Node.val &lt;= 100\n\n",
        "solution_py": "class Solution(object):\n    def maxDepth(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: int\n        \"\"\"\n        result = 0\n        depths = []\n        self.handler(root, result, depths)\n        return max(depths)\n\n    def handler(self, root, result, depths):\n        if root:\n            result += 1\n            self.handler(root.left, result, depths)\n            self.handler(root.right, result, depths)\n        else:\n            depths.append(result)",
        "solution_js": "var maxDepth = function(root) {\n    if(root == null) return 0\n    \n    let leftDepth = maxDepth(root.left)\n    let rightDepth = maxDepth(root.right)\n    \n    let ans = Math.max(leftDepth,rightDepth) + 1\n    \n    return ans\n};",
        "solution_java": "class Solution {\n    public int maxDepth(TreeNode root) {\n        // Base Condition\n        if(root == null) return 0;\n        // Hypothesis\n        int left = maxDepth(root.left);\n        int right = maxDepth(root.right);\n        // Induction\n        return Math.max(left, right) + 1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDepth(TreeNode* root) {\n        if(root == NULL) return 0;\n        int left = maxDepth(root->left);\n        int right = maxDepth(root->right);\n        return max(left, right) + 1;\n    }\n};"
    },
    {
        "title": "Tuple with Same Product",
        "algo_input": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,4,6]\nOutput: 8\nExplanation: There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n\n\nExample 2:\n\nInput: nums = [1,2,4,5,10]\nOutput: 16\nExplanation: There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 104\n\tAll elements in nums are distinct.\n\n",
        "solution_py": "class Solution:\n    def tupleSameProduct(self, nums: List[int]) -> int:\n\n        from itertools import combinations\n        mydict=defaultdict(int)\n        ans=0\n\n        for a,b in combinations(nums,2):\n            mydict[a*b]+=1\n\n        for i,j in mydict.items():\n            if j>1:\n                ans+=(j*(j-1)//2)*8\n\n        return ans",
        "solution_js": "var tupleSameProduct = function(nums) {\n    let tupleCount = 0;\n    let products = {}; // we'll keep track of how many times we've seen a given product before\n    for (let a = 0; a < nums.length; a++) {\n        for (let b = a + 1; b < nums.length; b++) {\n            let product = nums[a] * nums[b];\n            if (products[product]) { // we've seen at least one other pair of numbers with the same product already\n                tupleCount += 8 * products[product]; // multiply by 8 because for any 4 numbers there are 8 permutations\n                products[product] += 1; // increment the count, if we see this product again there are even more possible tuple combinations\n            } else {\n                products[product] = 1; // mark as seen once\n            }\n        }\n    }\n    return tupleCount;\n};",
        "solution_java": "class Solution {\n    public int tupleSameProduct(int[] nums) {\n        \n        if(nums.length < 4){\n            return 0;\n        }\n        \n        int res = 0;\n        \n        HashMap<Integer, Integer> map = new HashMap<>();\n        \n        for(int i = 0; i < nums.length - 1; i++){\n            \n            for(int j = i + 1; j < nums.length; j++){\n                \n                int val = nums[i] * nums[j];\n                map.put(val, map.getOrDefault(val, 0) + 1);\n            }\n        }\n        \n        for(int key : map.keySet()){\n            \n            int val = map.get(key);\n            \n            if(val > 1){\n                res += val * (val - 1) * 4;    // (val * (val - 1) / 2) * 8\n            }\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int tupleSameProduct(vector<int>& nums) {\n        int n = nums.size();\n        unordered_map<int,int> map;\n        int res = 0;\n        for(int i = 0 ; i < n ; i++){\n            for(int j = i+1 ; j < n ; j++){\n                int prod = nums[i] * nums[j];\n                map[prod]++;//store product of each possible pair\n            }\n        }\n        for(pair<int,int> m:map){\n            int n=m.second;\n            res += (n*(n-1))/2; //no. of tuple\n        }\n        return res*8; //Every tuple has 8 permutations\n    }\n};"
    },
    {
        "title": "Maximum Number of Eaten Apples",
        "algo_input": "There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.\n\nYou decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.\n\nGiven two integer arrays days and apples of length n, return the maximum number of apples you can eat.\n\n&nbsp;\nExample 1:\n\nInput: apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput: 7\nExplanation: You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.\n\n\nExample 2:\n\nInput: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput: 5\nExplanation: You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == apples.length == days.length\n\t1 &lt;= n &lt;= 2 * 104\n\t0 &lt;= apples[i], days[i] &lt;= 2 * 104\n\tdays[i] = 0 if and only if apples[i] = 0.\n\n",
        "solution_py": "import heapq\nclass Solution(object):\n    def eatenApples(self, apples, days):\n        \"\"\"\n        :type apples: List[int]\n        :type days: List[int]\n        :rtype: int\n        \"\"\"\n        heap = [(days[0], apples[0])]\n        heapq.heapify(heap)\n        day = 0\n        rtn = 0\n        while heap or day < len(days):\n            # print(heap, day)\n            apple = 0\n            if heap :\n                cnt, apple = heapq.heappop(heap)\n                while heap and cnt <= day and apple > 0:\n                    cnt, apple = heapq.heappop(heap)\n            if apple > 0 and cnt > day  :\n                rtn +=1\n            day +=1\n            if apple >  1 and cnt > day:\n                heapq.heappush(heap, (cnt, apple-1))\n            if day < len(days) and apples[day] > 0 :\n                heapq.heappush(heap, (day +days[day], apples[day]))\n        return rtn ",
        "solution_js": "var eatenApples = function(apples, days) {\n    const heap = new MinPriorityQueue({priority: x => x[0]});\n    let totalApple = 0;\n    \n    for(let i = 0; i < apples.length; i++) {\n        heap.enqueue([i + days[i], apples[i]]);\n        \n        while(!heap.isEmpty()) {\n            const [expire, count] = heap.front().element;\n            if(!count || expire <= i) heap.dequeue();\n            else break;\n        }\n        \n        if(heap.isEmpty()) continue;\n        totalApple++;\n        heap.front().element[1]--;\n    }\n    \n    let i = apples.length;\n    \n    while(!heap.isEmpty()) {\n        const [expire, count] = heap.dequeue().element;\n        if(!count || expire <= i) continue;\n        totalApple += Math.min(count, expire - i);\n        i = Math.min(expire, i + count);\n    }\n    return totalApple;\n};",
        "solution_java": "class Solution {\n    public int eatenApples(int[] apples, int[] days) {\n        PriorityQueue<Apple> minHeap = new PriorityQueue<Apple>((a, b) -> (a.validDay - b.validDay));\n        \n        //start from day 1\n        int currentDay = 1;\n        int eatenAppleCount = 0;\n        \n        for(int i = 0; i < apples.length; i++){\n            \n            //add apple count and their valid day\n            if(apples[i] > 0 && days[i] > 0) {\n                \n                //current day is included\n                int validDay = currentDay + days[i] - 1;\n                \n                minHeap.add(new Apple(apples[i], validDay));\n            }\n\n            \n            //check for eatable apple\n            while(!minHeap.isEmpty()){\n                //get that applen, with minimum valid date (going to expiry soon)\n                Apple apple = minHeap.remove();\n                \n                if(apple.validDay >= currentDay){\n                    //eat 1 apple\n                    apple.count--;\n                    \n                    //increment count\n                    eatenAppleCount++;\n\n                    //add remaiing apple, if not gonna expiry current day\n                    if(apple.count > 0 && apple.validDay > currentDay){\n                        minHeap.add(apple);\n                    }\n                    \n                    break;\n                }\n            }\n           \n            //move to the next day\n            currentDay++;\n        }\n        \n        \n        //eat stored apple\n        while(!minHeap.isEmpty()){\n            Apple apple = minHeap.remove();\n\n            if(apple.validDay >= currentDay){\n                //eat 1 apple\n                apple.count--;\n                \n                //increment count\n                eatenAppleCount++;\n                \n                //add remaiing apple, if not gonna expiry current day\n                if(apple.count > 0 && apple.validDay > currentDay){\n                    minHeap.add(apple);\n                }\n                \n                //apple is eaten in current day, now move to next day\n                currentDay++;\n            }\n        }\n        \n        \n        return eatenAppleCount;\n    }\n}\n\n\nclass Apple {\n    int count;\n    int validDay;\n    \n    public Apple(int count, int validDay){\n        this.count = count;\n        this.validDay = validDay;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int eatenApples(vector<int>& apples, vector<int>& days) {\n        ios_base::sync_with_stdio(0);cin.tie(0);\n        priority_queue<int,vector<int>,greater<int>>p;\n        unordered_map<int,int>m;\n        int ans=0;\n        int i=0;\n        while(p.size() || i<days.size()){\n            if(i<days.size() && apples[i]!=0 && days[i]!=0){\n                m[days[i]+i]=apples[i];\n                p.push(days[i]+i);\n            }\n            while(p.size()){\n                if(m[p.top()]!=0 && p.top()>i)\n                    break;\n                p.pop();\n            }\n            if(p.size()){\n                ans++;\n                m[p.top()]--;\n            }\n            ++i;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Consecutive Cards to Pick Up",
        "algo_input": "You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.\n\nReturn the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.\n\n&nbsp;\nExample 1:\n\nInput: cards = [3,4,2,3,4,7]\nOutput: 4\nExplanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.\n\n\nExample 2:\n\nInput: cards = [1,0,5,3]\nOutput: -1\nExplanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= cards.length &lt;= 105\n\t0 &lt;= cards[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def minimumCardPickup(self, cards: List[int]) -> int:\n        d={}\n        x=[]\n        for i in range(len(cards)):\n            if cards[i] not in d:\n                d[cards[i]]=i\n            else:\n                x.append(i-d[cards[i]])\n                d[cards[i]]=i\n        if len(x)<=0:\n            return -1\n        return min(x)+1",
        "solution_js": "var minimumCardPickup = function(cards) {\n    let cardsSeen = {};\n    let minPicks = Infinity;\n    for (let i = 0; i < cards.length; i++) {\n        if (!(cards[i] in cardsSeen)) {\n            cardsSeen[cards[i]] = i;\n        } else {\n            const temp = i - cardsSeen[cards[i]] + 1;\n            minPicks = Math.min(minPicks, temp);\n            cardsSeen[cards[i]] = i;\n        }\n    }\n    return minPicks === Infinity ? -1 : minPicks;\n};",
        "solution_java": "class Solution\n{\n    public int minimumCardPickup(int[] cards)\n    {\n        Map<Integer,Integer> map = new HashMap<>();\n        int min = Integer.MAX_VALUE;\n        for(int i = 0; i < cards.length; i++)\n        {\n            if(map.containsKey(cards[i]))\n                min = Math.min(i-map.get(cards[i])+1,min); // Check if the difference in indices is smaller than minimum\n            map.put(cards[i],i); // Update the last found index of the card\n        }\n        return min == Integer.MAX_VALUE?-1:min; // Repetition found or not\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minimumCardPickup(vector<int>& cards) {\n\n        int res (INT_MAX), n(size(cards));\n        unordered_map<int, int> m;\n        for (auto i=0; i<n; i++) {\n            // number of consecutive cards you have to pick up to have a pair of matching cards == (Diference between 2 indexes of same card) + 1\n            if (m.count(cards[i])) res = min(res, i-m[cards[i]]+1);\n            m[cards[i]] = i;\n        }\n        return (res == INT_MAX) ? -1 : res;\n    }\n};"
    },
    {
        "title": "Find Triangular Sum of an Array",
        "algo_input": "You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).\n\nThe triangular sum of nums is the value of the only element present in nums after the following process terminates:\n\n\n\tLet nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.\n\tFor each index i, where 0 &lt;= i &lt;&nbsp;n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.\n\tReplace the array nums with newNums.\n\tRepeat the entire process starting from step 1.\n\n\nReturn the triangular sum of nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4,5]\nOutput: 8\nExplanation:\nThe above diagram depicts the process from which we obtain the triangular sum of the array.\n\nExample 2:\n\nInput: nums = [5]\nOutput: 5\nExplanation:\nSince there is only one element in nums, the triangular sum is the value of that element itself.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 9\n\n",
        "solution_py": "class Solution(object):\n    def triangularSum(self, nums):\n        while len(nums) > 1:\n            arr = []\n            for i in range(len(nums)-1):\n                arr.append((nums[i] + nums[i+1]) % 10)\n            nums = arr\n        return nums[0]",
        "solution_js": "var triangularSum = function(nums) {\n    while(nums.length > 1){\n        let arr = []\n        for(let i=0; i<nums.length-1; i++){\n            arr.push((nums[i] + nums[i+1]) % 10)\n        }\n        nums = arr\n    }\n    return nums[0]\n};",
        "solution_java": "class Solution {\n    public int triangularSum(int[] nums) {\n        return find(nums,nums.length);\n    }\n    \n    public int find(int[] a, int n){\n        if(n == 1)\n            return a[0];\n            \n        for(int i=0;i<n-1;i++){\n            a[i] = (a[i] + a[i+1])%10; \n        }\n        return find(a,n-1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int triangularSum(vector<int>& nums) {\n        int n=nums.size();\n        for(int i=n-1;i>=1;i--){\n            for(int j=0;j<i;j++){\n                nums[j]=(nums[j]+nums[j+1])%10;\n            }\n        }\n        return nums[0];\n    }\n};"
    },
    {
        "title": "Pseudo-Palindromic Paths in a Binary Tree",
        "algo_input": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.\n\nReturn the number of pseudo-palindromic paths going from the root node to leaf nodes.\n\n&nbsp;\nExample 1:\n\n\n\nInput: root = [2,3,1,3,1,null,1]\nOutput: 2 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\n\nExample 2:\n\n\n\nInput: root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput: 1 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\n\nExample 3:\n\nInput: root = [9]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 105].\n\t1 &lt;= Node.val &lt;= 9\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def dfs(self, node, path):\n        if not node:\n            return\n        \n        if not node.left and not node.right:\n            path += [node.val]\n            d = {}\n            for i in path.copy():\n                if i in d:\n                    del d[i]\n                else:\n                    d[i] = 1\n            #print(d.items())\n            self.ans += 1 if len(d) <= 1 else 0\n            return\n                \n        self.dfs(node.left, path+[node.val])\n        self.dfs(node.right, path+[node.val])\n    \n    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:\n        self.ans = 0\n        self.dfs(root, [])\n        return self.ans",
        "solution_js": "var pseudoPalindromicPaths  = function(root) {\n    if(!root) return 0;\n    // if even it's zero or it's power of two when odd\n    const ways = (r = root, d = 0) => {\n        if(!r) return 0;\n        d = d ^ (1 << r.val);\n        // leaf\n        if(r.left == r.right && r.left == null) {\n            const hasAllEven = d == 0;\n            const hasOneOdd = (d ^ (d & -d)) == 0;\n            return Number(hasEven || hasOneOdd);\n        }\n        return ways(r.left, d) + ways(r.right, d);\n    }\n    return ways();\n};",
        "solution_java": "class Solution {\n    public int pseudoPalindromicPaths (TreeNode root) {\n        return helper(root, 0);\n    }\n    \n    public int helper(TreeNode node, int freq) {\n        if (node == null) return 0;\n        \n        freq = freq ^ (1 << node.val);\n        if (node.left == null && node.right == null) {\n            return (freq & (freq - 1)) == 0 ? 1 : 0;\n            // return Integer.bitCount(freq) <= 1 ? 1 : 0;\n        }\n        return helper(node.left, freq) + helper(node.right, freq);\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n\tvoid dfs(TreeNode* root,int &ans,unordered_map<int,int> &m){\n\n\t\tif(!root) return;\n\t\tm[root -> val]++;\n\n\t\tif(!root -> left and !root -> right){\n\t\t\tint oddCnt = 0;\n\t\t\tfor(auto it : m){\n\t\t\t\tif(it.second % 2 != 0) oddCnt++;\n\t\t\t}\n\t\t\tif(oddCnt <= 1) ans++;\n\t\t}\n\n\n\t\tdfs(root -> left,ans,m);\n\t\tdfs(root -> right,ans,m);\n\n\t\tm[root -> val]--;\n\n\t}\npublic:\n\tint pseudoPalindromicPaths (TreeNode* root) {\n\n\t\tif(root == NULL) return 0;\n\n\t\tint ans = 0;\n\n\t\tunordered_map<int,int> m;\n\n\t\tdfs(root,ans,m);\n\n\t\treturn ans;\n\n\t}\n};"
    },
    {
        "title": "Maximal Square",
        "algo_input": "Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput: 4\n\n\nExample 2:\n\nInput: matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput: 1\n\n\nExample 3:\n\nInput: matrix = [[\"0\"]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 300\n\tmatrix[i][j] is '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def maximalSquare(self, matrix: List[List[str]]) -> int:\n        m, n = len(matrix), len(matrix[-1])   \n        dp = [[0] * n for _ in range(m)]     \n        max_area = 0\n        for i in range(m):\n            for j in range(n): \n                if i - 1 < 0 or j - 1 < 0:\n                    if matrix[i][j] == '1': dp[i][j] = 1\n                else:\n                    if matrix[i][j] == '1':\n                        dp[i][j] = 1 + min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j])\n                max_area = max(max_area, dp[i][j] ** 2)\n        return max_area",
        "solution_js": "var maximalSquare = function(matrix) {\n    let max = 0;\n    const height = matrix.length-1;\n    const width = matrix[0].length-1;\n    for (let i=height; i>=0; i--) {\n        for (let j=width; j>=0; j--) {\n            const right = j < width ? Number(matrix[i][j+1]) : 0;\n            const diag = i < height && j < width ? Number(matrix[i+1][j+1]) : 0\n            const bottom = i < height ? Number(matrix[i+1][j]) : 0;\n            matrix[i][j] = matrix[i][j] === '0' ? 0 : \n                Math.min(right, diag, bottom) + 1;\n            max = Math.max(max, matrix[i][j] * matrix[i][j]);\n        }  \n    }\n    return max;\n};",
        "solution_java": "class Solution {\n    public int maximalSquare(char[][] matrix) {\n        int m = matrix.length;\n        int n = matrix[0].length;\n        int[][] dp = new int[m][n];\n\n        int max = 0;\n\n        for (int i = 0; i < m; i++) {\n            dp[i][0] = matrix[i][0] - 48;\n            if (matrix[i][0] == '1') max = 1;\n        }\n        for (int i = 0; i < n; i++) {\n            dp[0][i] = matrix[0][i] - 48;\n            if (matrix[0][i] == '1') max = 1;\n        }\n\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                if (matrix[i][j] == '1') {\n                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;\n                    if (dp[i][j] > max) {\n                        max = dp[i][j];\n                    }\n                }\n            }\n        }\n\n        return max * max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int dp[305][305];\n    int ans;\n    \n    int getMax(vector<vector<char>>& mat, int i, int j){\n        int n=mat.size(), m=mat[0].size();\n        if(i>=n || j>=m) return 0;\n        if(dp[i][j] != -1) return dp[i][j];\n        \n\t\t// getting min of the perfect squares formed by left adjacent, right adjacent, cross adjacent \n\t\t// +1 for including current\n        dp[i][j] = min({getMax(mat, i, j+1), getMax(mat, i+1, j), getMax(mat, i+1, j+1)}) + 1;\n\t\t// There are no perfect squares if mat[i][j] is zero\n        if(mat[i][j] == '0') dp[i][j] = 0;\n\t\t\n\t\t// final ans = max(ans, current_max);\n        ans = max(ans, dp[i][j]);\n\t\t\n        return dp[i][j];\n    }\n    \n    int maximalSquare(vector<vector<char>>& matrix) {\n        memset(dp, -1, sizeof(dp));\n        ans = 0;\n        getMax(matrix, 0, 0);\n        return ans*ans;\n    }\n};"
    },
    {
        "title": "Number of Valid Words in a Sentence",
        "algo_input": "A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.\n\nA token is a valid word if all three of the following are true:\n\n\n\tIt only contains lowercase letters, hyphens, and/or punctuation (no digits).\n\tThere is at most one hyphen '-'. If present, it must be surrounded by lowercase characters (\"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).\n\tThere is at most one punctuation mark. If present, it must be at the end of the token (\"ab,\", \"cd!\", and \".\" are valid, but \"a!b\" and \"c.,\" are not valid).\n\n\nExamples of valid words include \"a-b.\", \"afad\", \"ba-c\", \"a!\", and \"!\".\n\nGiven a string sentence, return the number of valid words in sentence.\n\n&nbsp;\nExample 1:\n\nInput: sentence = \"cat and  dog\"\nOutput: 3\nExplanation: The valid words in the sentence are \"cat\", \"and\", and \"dog\".\n\n\nExample 2:\n\nInput: sentence = \"!this  1-s b8d!\"\nOutput: 0\nExplanation: There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.\n\n\nExample 3:\n\nInput: sentence = \"alice and  bob are playing stone-game10\"\nOutput: 5\nExplanation: The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentence.length &lt;= 1000\n\tsentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.\n\tThere will be at least&nbsp;1 token.\n\n",
        "solution_py": "import re\nclass Solution:\n    def countValidWords(self, sentence: str) -> int:\n        \n        # parse and get each word from sentence\n        words = sentence.split()\n        \n        # regular expression pattern for valid words\n        pattern = re.compile( r'^([a-z]+\\-?[a-z]+[!\\.,]?)$|^([a-z]*[!\\.,]?)$' )\n        \n        # valid word count\n        count = 0\n        \n        # scan each word from word pool\n        for word in words:\n            \n            # judge whether current word is valid or not\n            match = re.match(pattern, word)\n            \n            if match:\n                count+=1\n                \n        return count",
        "solution_js": "/**\n * @param {string} sentence\n * @return {number}\n */\nvar countValidWords = function(sentence) {\n    let list = sentence.split(' ')\n    let filtered = list.filter(s => {\n        if (/\\d/.test(s) || s === '') return false   //removes anything with numbers or is blank\n        if (/^[!,.]$/.test(s)) return true          //punctuation only\n        if (/^\\w+[!,.]?$/.test(s)) return true      //word + optional punctuation\n        if (/^\\w+[-]?\\w+[!,.]?$/.test(s)) return true //word + optional hypen + word + optional punctuation\n        return false\n    })\n    \n    return filtered.length\n};",
        "solution_java": "class Solution {\n    public int countValidWords(String sentence) {\n        String regex = \"^([a-z]+(-?[a-z]+)?)?(!|\\\\.|,)?$\";\n        String r2 = \"[^0-9]+\";\n        String[] arr = sentence.split(\"\\\\s+\");\n        int ans = 0;\n        for(String s: arr)\n        {\n            if(s.matches(regex) && s.matches(r2))\n            {\n                ans++;\n                //System.out.println(s);\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "#include <regex>\n\nclass Solution {\npublic:\n    int countValidWords(string sentence) {\n\n        int count = 0;\n\n        // Defining the regex pattern\n        regex valid_word(\"[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?\");\n\n        // splitting the sentence to words\n        stringstream s(sentence);\n        string word;\n        while(getline(s, word, ' ')) {\n\n            // Checking if the word matches the regex pattern\n            if(word != \"\" && regex_match(word, valid_word)){\n                ++count;\n            }\n        }\n\n        return count;\n    }\n};"
    },
    {
        "title": "Contains Duplicate II",
        "algo_input": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) &lt;= k.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,1], k = 3\nOutput: true\n\n\nExample 2:\n\nInput: nums = [1,0,1,1], k = 1\nOutput: true\n\n\nExample 3:\n\nInput: nums = [1,2,3,1,2,3], k = 2\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\t0 &lt;= k &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n        seen = {}\n        for i, n in enumerate(nums):\n            if n in seen and i - seen[n] <= k:\n                    return True\n            seen[n] = i\n        return False",
        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nvar containsNearbyDuplicate = function(nums, k) {\n    const duplicateCheck = {};\n    let isValid = false;\n    for(var indexI=0; indexI<nums.length;indexI++){\n         if(duplicateCheck[nums[indexI]] > -1) {\n            if(Math.abs(duplicateCheck[nums[indexI]] - indexI) <= k) {\n              isValid = true;\n              break;\n            }\n\n        }\n        duplicateCheck[nums[indexI]] = indexI;\n    }\n    return isValid;\n};",
        "solution_java": "class Solution {\n    public boolean containsNearbyDuplicate(int[] nums, int k) {\n        HashMap<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < nums.length; i++) {\n            if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) {\n                return true;\n            }\n            map.put(nums[i], i);\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool containsNearbyDuplicate(vector<int>& nums, int k) {\n        unordered_map<int,int> m;\n        for(int i=0;i<nums.size();i++){\n            if(m.count(nums[i]) && i-m[nums[i]]<=k) return true;\n            m[nums[i]]=i;\n        }\n        return false;\n    }   \n};"
    },
    {
        "title": "Minimum Moves to Equal Array Elements",
        "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 n - 1 elements of the array by 1.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 3\nExplanation: Only three moves are needed (remember each move increments two elements):\n[1,2,3]  =&gt;  [2,3,3]  =&gt;  [3,4,3]  =&gt;  [4,4,4]\n\n\nExample 2:\n\nInput: nums = [1,1,1]\nOutput: 0\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\tThe answer is guaranteed to fit in a 32-bit integer.\n\n",
        "solution_py": "class Solution:\n    def minMoves(self, nums: List[int]) -> int:\n        return sum(nums)-min(nums)*len(nums)",
        "solution_js": "var minMoves = function(nums) {\n    let minElm = Math.min(...nums);\n    let ans = 0;\n    for(let i=0; i<nums.length; i++){\n        ans += (nums[i]-minElm)\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public int minMoves(int[] nums) {\n        int min=Integer.MAX_VALUE;\n        int count=0;\n        for(int i:nums)\n            min=Math.min(i,min);\n        \n        for(int i=0;i<nums.length;i++)\n        {\n            count+=nums[i]-min;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minMoves(vector<int>& nums) {\n\n        // sorting the array to get min at the first\n        sort(nums.begin(), nums.end());\n        int cnt = 0, n = nums.size();\n\n        // Now we have to make min equal to every number and keep adding the count\n        for(int i = 1; i < n; i++)\n            cnt += nums[i] - nums[0];\n\n        return cnt;\n    }\n};"
    },
    {
        "title": "Strong Password Checker II",
        "algo_input": "A password is said to be strong if it satisfies all the following criteria:\n\n\n\tIt has at least 8 characters.\n\tIt contains at least one lowercase letter.\n\tIt contains at least one uppercase letter.\n\tIt contains at least one digit.\n\tIt contains at least one special character. The special characters are the characters in the following string: \"!@#$%^&amp;*()-+\".\n\tIt does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not).\n\n\nGiven a string password, return true if it is a strong password. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: password = \"IloveLe3tcode!\"\nOutput: true\nExplanation: The password meets all the requirements. Therefore, we return true.\n\n\nExample 2:\n\nInput: password = \"Me+You--IsMyDream\"\nOutput: false\nExplanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.\n\n\nExample 3:\n\nInput: password = \"1aB!\"\nOutput: false\nExplanation: The password does not meet the length requirement. Therefore, we return false.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= password.length &lt;= 100\n\tpassword consists of letters, digits, and special characters: \"!@#$%^&amp;*()-+\".\n\n",
        "solution_py": "class Solution:\n    def strongPasswordCheckerII(self, pwd: str) -> bool:\n        return (\n            len(pwd) > 7\n            and max(len(list(p[1])) for p in groupby(pwd)) == 1\n            and reduce(\n                lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0\n            ) == 15\n        )",
        "solution_js": "const checkLen = (password) => password.length >= 8;\n\nconst checkSmallLetter = (password) => {\n    for(let i=0;i<password.length;i++){\n        const ind = password.charCodeAt(i);\n        if(ind > 96 && ind < 123){\n            return true;\n        }\n    }\n    return false;\n}\n\nconst checkCapitalLetter = (password) => {\n    for(let i=0;i<password.length;i++){\n        const ind = password.charCodeAt(i);\n        if(ind > 64 && ind < 91){\n            return true;\n        }\n    }\n    return false;\n}\n\nconst checkDigit = (password) => {\n    for(let i=0;i<password.length;i++){\n        const ind = password.charCodeAt(i);\n        if(ind > 47 && ind < 58){\n            return true;\n        }\n    }\n    return false;\n}\n\nconst checkSpecialChar = (password) => {\n    const str = \"!@#$%^&*()-+\";\n     for(let i=0;i<str.length;i++){\n       if(password.includes(str[i])) return true;\n    }\n    return false;\n}\n\nconst checkAdjacentMatches = (password) => {\n    for(let i=1;i<password.length;i++){\n        if(password[i] === password[i-1]) return false;\n    }\n    return true;\n}\n\n\nvar strongPasswordCheckerII = function(password) {\n    const lenValidity = checkLen(password);\n    const smallLetterValidity = checkSmallLetter(password);    \n    const capitalLetterValidity = checkCapitalLetter(password);\n    const digitValidity = checkDigit(password);\n    const specialCharValidity = checkSpecialChar(password);\n    const adjacentMatchesValidity = checkAdjacentMatches(password);\n        \n    const passwordIsStrong = lenValidity && smallLetterValidity && capitalLetterValidity && digitValidity && specialCharValidity && adjacentMatchesValidity;\n  \n    return passwordIsStrong;\n};",
        "solution_java": "class Solution {\n    public boolean strongPasswordCheckerII(String password) {\n           HashSet<Integer> intAscii = new HashSet<>();\n        String specialCharacters = \"!@#$%^&*()-+\";\n        for (int i = 0; i < specialCharacters.length(); i++) {\n            int ascii = specialCharacters.charAt(i);\n            intAscii.add(ascii);\n        }\n        \n        if(password.length() < 8){\n            return false;\n        }\n        boolean small = false;\n        boolean large = false;\n        boolean numbers = false;\n        boolean specialChars = false;\n        for(int i = 0 ; i < password.length() ; i++){\n            int ascii = (int)(password.charAt(i));\n            if(ascii <= 90 && ascii>=65){\n                large = true;\n            }\n                if(ascii <= 122 && ascii>=97){\n                small = true;\n            }\n            if(ascii <=57 && ascii >=48){\n                numbers = true;\n            }\n            if(intAscii.contains(ascii)){\n                specialChars = true;\n            }\n            if(i> 0 && password.charAt(i)== password.charAt(i-1)){\n                return false;\n            }\n        }\n        if(large == false || small == false || numbers == false || specialChars ==false){\n            return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool strongPasswordCheckerII(string password) {\n\t\tif(password.size() < 8) //8 char length\n            return false;\n\t\t\t\n        bool lower = 0, upper = 0;\n        bool digit = 0, special = 0;\n\t\t\n        for(int i=0; i<password.size(); i++){ //check rest conditions\n            if(i>0 && password[i] == password[i-1])   //check duplicate\n\t\t\t\treturn false; \n             \n\t\t\tif(password[i] >=65 && password[i] <=90)  upper = 1;  //uppercase\n\t\t\telse if(password[i] >=97 && password[i] <=122)   lower = 1;   //lowercase\n\t\t\telse if(password[i] >=48 && password[i] <=57)       digit = 1;   //digit\n\t\t\telse     //special char\n                special = 1;\n        }\n        \n        if(upper && lower && digit && special)\n            return true;\n        return false;\n    }\n};"
    },
    {
        "title": "Largest Component Size by Common Factor",
        "algo_input": "You are given an integer array of unique positive integers nums. Consider the following graph:\n\n\n\tThere are nums.length nodes, labeled nums[0] to nums[nums.length - 1],\n\tThere is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\n\nReturn the size of the largest connected component in the graph.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,6,15,35]\nOutput: 4\n\n\nExample 2:\n\nInput: nums = [20,50,9,63]\nOutput: 2\n\n\nExample 3:\n\nInput: nums = [2,3,6,7,4,12,21,39]\nOutput: 8\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t1 &lt;= nums[i] &lt;= 105\n\tAll the values of nums are unique.\n\n",
        "solution_py": "class Solution:\n    def largestComponentSize(self, nums: List[int]) -> int:\n        \n        def find(node):\n            if parent[node] == -1: return node\n            else:\n                parent[node] = find(parent[node])\n                return parent[node]\n        \n        def union(idx1,idx2):\n            par1,par2 = find(idx1),find(idx2)\n            if par1!=par2:\n                if rank[par1] > rank[par2]:\n                    parent[par2] = par1\n                elif rank[par2] > rank[par1]:\n                    parent[par1] = par2\n                else:\n                    parent[par2] = par1\n                    rank[par1] += 1\n        \n        n = len(nums)\n        parent = defaultdict(lambda:-1)\n        rank = defaultdict(lambda:0)\n        for i in range(n):\n            limit = int(nums[i]**0.5)\n            for j in range(2,limit+1):\n                if nums[i] % j == 0:\n                    union(nums[i],j)\n                    union(nums[i],nums[i]//j)\n        count = defaultdict(lambda:0)\n        best = -1\n        for num in nums:\n            par = find(num)\n            tmp = count[par] + 1\n            if tmp > best: best = tmp\n            count[par] = tmp\n        return best",
        "solution_js": "var largestComponentSize = function(nums) {\n  const rootByFactor = new Map();\n  const parents = new Array(nums.length);\n\n  function addFactor(i, factor) {\n    if (rootByFactor.has(factor)) {\n      let r = rootByFactor.get(factor);\n      while (parents[i] != i) i = parents[i];\n      while (parents[r] != r) r = parents[r];\n      parents[i] = r;\n    }\n    rootByFactor.set(factor, parents[i]);\n  }\n\n  for (const [i, num] of nums.entries()) {\n    parents[i] = i;\n    addFactor(i, num);\n    for (let factor = 2; factor * factor <= num; ++factor) {\n      if (num % factor == 0) {\n        addFactor(i, factor);\n        addFactor(i, num / factor);\n      }\n    }\n  }\n\n  let largest = 0;\n  const sums = new Array(nums.length).fill(0);\n  for (let r of parents) {\n    while (parents[r] != r) r = parents[r];\n    largest = Math.max(largest, ++sums[r]);\n  }\n  return largest;\n};",
        "solution_java": "class Solution {\n    public int largestComponentSize(int[] nums) {\n        int maxNum = getMaxNum(nums);\n        Map<Integer, Integer> numToFirstPrimeFactor = new HashMap<>();\n        DisjointSet ds = new DisjointSet(maxNum + 1);\n        for (int num : nums) {\n            if (num == 1) {\n                continue;\n            }\n\n            List<Integer> primeFactors = getPrimeFactors(num);\n            int firstPrimeFactor = primeFactors.get(0);\n            numToFirstPrimeFactor.put(num, firstPrimeFactor);\n\n            for (int i = 1; i < primeFactors.size(); i++) {\n                ds.union(primeFactors.get(i-1), primeFactors.get(i));\n            }\n        }\n\n        Map<Integer, Integer> componentToSize = new HashMap<>();\n        int maxSize = 0;\n        for (int num : nums) {\n            if (num == 1) {\n                continue;\n            }\n\n            int firstPrimeFactor = numToFirstPrimeFactor.get(num);\n            int component = ds.find(firstPrimeFactor);\n            int size = componentToSize.getOrDefault(component, 0);\n            componentToSize.put(component, ++size);\n            maxSize = Math.max(maxSize, size);\n        }\n        return maxSize;\n    }\n\n    public int getMaxNum(int[] nums) {\n        int maxNum = 0;\n        for (int num : nums) {\n            maxNum = Math.max(maxNum, num);\n        }\n        return maxNum;\n    }\n\n    public List<Integer> getPrimeFactors(int num) {\n        List<Integer> primeFactors = new ArrayList<>();\n\n        // even prime factor i.e. 2\n        if((num & 1) == 0){\n            primeFactors.add(2);\n\n            do{\n                num >>= 1;\n            }while((num & 1) == 0);\n        }\n\n        // odd prime factors\n        int primeFactor = 3;\n        while(num != 1 && primeFactor*primeFactor <= num){\n            if(num % primeFactor == 0){\n                primeFactors.add(primeFactor);\n\n                do{\n                    num /= primeFactor;\n                }while(num % primeFactor == 0);\n            }\n            primeFactor += 2;\n        }\n\n        // num is prime\n        if(num != 1){\n            primeFactors.add(num);\n        }\n        return primeFactors;\n    }\n}\n\nclass DisjointSet {\n    int[] root;\n    int[] rank;\n\n    public DisjointSet(int size) {\n        root = new int[size];\n        rank = new int[size];\n        for (int i = 0; i < size; i++) {\n            root[i] = i;\n            rank[i] = 1;\n        }\n    }\n\n    public int find(int x) {\n        while (x != root[x]) {\n            root[x] = root[root[x]];\n            x = root[x];\n        }\n        return x;\n    }\n\n    public void union(int x, int y) {\n        int rootX = find(x);\n        int rootY = find(y);\n\n        if (rootX == rootY) {\n            return;\n        }\n\n        if (rank[rootX] > rank[rootY]) {\n            root[rootY] = rootX;\n        } else if (rank[rootX] < rank[rootY]) {\n            root[rootX] = rootY;\n        } else {\n            root[rootY] = rootX;\n            rank[rootX]++;\n        }\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    vector<bool> sieve(int n) {\n        vector<bool> prime(n + 1);\n        for (int i = 0; i <= n; i++)\n            prime[i] = 1;\n        for (int p = 2; p * p <= n; p++) {\n            if (prime[p] == 1) {\n                for (int i = p * p; i <= n; i += p)\n                    prime[i] = 0;\n            }\n        }\n        prime[1] = prime[0] = 0;\n        return prime;\n    }\n    vector<int> factors(int n, vector<int> &primelist) {\n        vector<int> facs;\n        for (int i = 0; primelist[i] * primelist[i] <= n && i < primelist.size(); i++) {\n            if (n % primelist[i] == 0) {\n                facs.push_back(primelist[i]);\n                while (n % primelist[i] == 0) {\n                    n /= primelist[i];\n                }\n            }\n        }\n        if (n > 1) facs.push_back(n);\n        return facs;\n    }\n    void dfs(vector<vector<int>> &gr, int node, vector<int> &vis, int &compSize) {\n        if(vis[node]) return;\n        vis[node] = 1;\n        compSize++;\n        for(auto x : gr[node]) {\n            dfs(gr, x, vis, compSize);\n        }\n    }\npublic:\n    int largestComponentSize(vector<int>& nums) {\n        int n = nums.size();\n        vector<vector<int>> gr(n);\n        vector<bool> prime = sieve(1e5 + 6);\n        vector<int> primelist;\n\t\t// Getting all the primes till 10^5 as maximum value of nums[i] is 10^5\n        for (int i = 2; i <= 1e5 + 5; i++) if (prime[i]) primelist.push_back(i);\n        unordered_map<int, int> m; // to store the index of the node with prime factor x\n        for(int i = 0; i < n; i++) {\n            vector<int> facs = factors(nums[i], primelist);\n            for(auto j : facs) {\n                if(m.find(j) == m.end()) { // prime factor had not occured before\n                    m[j] = i; // j is the prime factor and its index is i\n                } else {\n\t\t\t\t    // prime factor has already been seen before in a previous number and nums[i] is connected to that number\n                    gr[i].push_back(m[j]);\n                    gr[m[j]].push_back(i);\n                }\n            }\n        }\n        int ans = 0;\n        vector<int> vis(n);\n        for(int i = 0; i < n; i++) { // running a simple dfs to calculate the maximum component size\n            if(!vis[i]) {\n                int compSize = 0;\n                dfs(gr, i, vis, compSize);\n                ans = max(ans, compSize);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Kth Distinct String in an Array",
        "algo_input": "A distinct string is a string that is present only once in an array.\n\nGiven an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string \"\".\n\nNote that the strings are considered in the order in which they appear in the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\nOutput: \"a\"\nExplanation:\nThe only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1st distinct string.\n\"a\" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, \"a\" is returned. \n\n\nExample 2:\n\nInput: arr = [\"aaa\",\"aa\",\"a\"], k = 1\nOutput: \"aaa\"\nExplanation:\nAll strings in arr are distinct, so the 1st string \"aaa\" is returned.\n\n\nExample 3:\n\nInput: arr = [\"a\",\"b\",\"a\"], k = 3\nOutput: \"\"\nExplanation:\nThe only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= arr.length &lt;= 1000\n\t1 &lt;= arr[i].length &lt;= 5\n\tarr[i] consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def kthDistinct(self, arr: List[str], k: int) -> str:\n        hash_map = {}\n        for string in arr:\n            hash_map[string] = hash_map.get(string, 0) + 1\n        for string in arr:\n            if hash_map[string] == 1:\n                k -= 1\n                if k == 0:\n                    return string\n        return \"\"",
        "solution_js": "var kthDistinct = function(arr, k) {\n    const map = {} // used for arr occurences\n    const distinctArr = [] // store the distinct values (only appearing once)\n    \n\t// increment the occurence to the map\n    arr.forEach(letter => map[letter] = map[letter] + 1 || 1)\n    \n\t// store all the distinct values in order\n    for (let [key, val] of Object.entries(map)) \n        if (val == 1) distinctArr.push(key)\n    \n\t// return the key or empty string\n    return distinctArr[k-1] || \"\"\n};\n~``",
        "solution_java": "class Solution {\n    public String kthDistinct(String[] arr, int k) {\n        Map<String,Integer> map=new HashMap<>();\n        \n        for(String s:arr){\n            \n            if(map.containsKey(s)) map.put(s,map.get(s)+1);\n             else map.put(s,1);\n        }\n\t\tint i=0;\n        for(String s:arr){\n            if(map.get(s)==1 && ++i==k){\n                \n                    return s;\n                } \n                 \n        }\n        return \"\";\n        \n    }\n}",
        "solution_c": "class Solution \n{\npublic:\n    string kthDistinct(vector<string>& arr, int k) \n    {\n        unordered_map<string,int>m;\n        for(int i=0;i<arr.size();i++)\n        {\n            m[arr[i]]++;\n        }\n        for(int i=0;i<arr.size();i++)\n        {\n            if(m[arr[i]]==1)\n            {\n                k--;\n            }\n            if(k==0 && m[arr[i]]==1)\n            {\n                return arr[i];\n            }\n        }\n        return \"\";\n    }\n};"
    },
    {
        "title": "Count Square Submatrices with All Ones",
        "algo_input": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.\n\n&nbsp;\nExample 1:\n\nInput: matrix =\n[\n&nbsp; [0,1,1,1],\n&nbsp; [1,1,1,1],\n&nbsp; [0,1,1,1]\n]\nOutput: 15\nExplanation: \nThere are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is  1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15.\n\n\nExample 2:\n\nInput: matrix = \n[\n  [1,0,1],\n  [1,1,0],\n  [1,1,0]\n]\nOutput: 7\nExplanation: \nThere are 6 squares of side 1.  \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length&nbsp;&lt;= 300\n\t1 &lt;= arr[0].length&nbsp;&lt;= 300\n\t0 &lt;= arr[i][j] &lt;= 1\n\n",
        "solution_py": "class Solution:\n    def countSquares(self, matrix: List[List[int]]) -> int:\n\n        m = len(matrix)\n        n = len(matrix[0])\n\n        dp = [[0 for _ in range(n)] for _ in range(m)]\n        total = 0\n\n        for i in range(m):\n            for j in range(n):\n\n                if i == 0:\n                    dp[i][j] = matrix[0][j]\n\n                elif j == 0:\n                    dp[i][j] = matrix[i][0]\n\n                else:\n                    if matrix[i][j] == 1:\n                        dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j])\n\n                total += dp[i][j]\n\n        return total",
        "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number}\n */\nvar countSquares = function(matrix) {\n  let count = 0;\n  for (let i = 0; i < matrix.length; ++i) {\n    for (let j = 0; j < matrix[0].length; ++j) {\n      if (matrix[i][j] === 0) continue;\n      if (i > 0 && j > 0) {\n        matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]);\n      }\n      count += matrix[i][j];\n    }\n  }\n  return count; \n};",
        "solution_java": "class Solution {\n    public int countSquares(int[][] matrix) {\n        int m = matrix.length;\n        int n = matrix[0].length;\n        int[][] res = new int[m][n];\n        \n        for(int j=0; j<n; j++)\n            res[0][j] = matrix[0][j];\n        \n        for(int i=0; i<m; i++)\n            res[i][0] = matrix[i][0];\n        \n        for(int i=1; i<m; i++){\n            for(int j=1; j<n; j++){\n                if(matrix[i][j] == 1){\n                    res[i][j] = Math.min(res[i-1][j], Math.min(res[i][j-1], res[i-1][j-1])) + 1;\n                }\n                else\n                    res[i][j] = 0;\n            }\n        }\n        \n        int sum = 0;\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                sum += res[i][j];\n            }\n        }\n        \n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    int solve( vector<vector<int>>&mat , int n , int m , vector<vector<int>>&dp){\n\n        if(n<0 or m<0 or mat[n][m] == 0 )\n            return 0;\n\n        if(dp[n][m] != -1 )\n            return dp[n][m];\n\n        return dp[n][m] = ( 1 + min({\n            solve( mat , n-1 , m , dp ),\n            solve(mat , n-1 , m-1 , dp ),\n            solve(mat , n , m-1 , dp )\n        }));\n\n    }\n\n    int countSquares(vector<vector<int>>& matrix) {\n        int n = matrix.size();\n        int m = matrix[0].size();\n        int ans = 0 ;\n\n        // vector<vector<int>>dp(n , vector<int>(m,-1));\n        // for(int i = 0 ; i<n ; ++i ){\n        // for(int j= 0 ; j<m ; ++j ){\n        // ans += solve( matrix,i , j , dp );\n        // }\n        // }\n\n        vector<vector<int>>dp(n , vector<int>(m, 0));\n\n        for(int i = 0 ; i<n ; ++i ){\n            for(int j = 0 ; j<m ; ++j ){\n                if(i==0 || j ==0 ){\n                    dp[i][j] = matrix[i][j];\n                }\n                else{\n                    if(matrix[i][j])\n                        dp[i][j] = 1 + min({dp[i-1][j] , dp[i-1][j-1] , dp[i][j-1]});\n                }\n            }\n        }\n\n        for(auto x : dp ){\n            for(auto y : x )\n                ans += y;\n        }\n\n        return ans ;\n    }\n};"
    },
    {
        "title": "Unique Length-3 Palindromic Subsequences",
        "algo_input": "Given a string s, return the number of unique palindromes of length three that are a subsequence of s.\n\nNote that even if there are multiple ways to obtain the same subsequence, it is still only counted once.\n\nA palindrome is a string that reads the same forwards and backwards.\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\n&nbsp;\nExample 1:\n\nInput: s = \"aabca\"\nOutput: 3\nExplanation: The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")\n\n\nExample 2:\n\nInput: s = \"adc\"\nOutput: 0\nExplanation: There are no palindromic subsequences of length 3 in \"adc\".\n\n\nExample 3:\n\nInput: s = \"bbcbaba\"\nOutput: 4\nExplanation: The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 105\n\ts consists of only lowercase English letters.\n\n",
        "solution_py": "class Solution(object):\n    def countPalindromicSubsequence(self, s):\n        d=defaultdict(list)\n        for i,c in enumerate(s):\n            d[c].append(i)\n        ans=0\n        for el in d:\n            if len(d[el])<2:\n                continue\n            a=d[el][0]\n            b=d[el][-1]\n            ans+=len(set(s[a+1:b]))\n        return(ans)",
        "solution_js": "var countPalindromicSubsequence = function(s) {\n    const charToIndices = {};\n    for (let i = 0; i < s.length; i++) {\n        const char = s[i];\n        if (charToIndices[char]) {\n            charToIndices[char].push(i);\n        } else {\n            charToIndices[char] = [i];\n        }\n    }\n\n    let count = 0;\n    for (const currChar in charToIndices) {\n        if (charToIndices[currChar].length < 2) continue;\n        const currCharIndices = charToIndices[currChar];\n        const firstIndex = currCharIndices[0];\n        const lastIndex = currCharIndices[currCharIndices.length - 1];\n\n        for (const char in charToIndices) {\n            const indices = charToIndices[char];\n            let lo = 0;\n            let hi = indices.length;\n            while (lo < hi) {\n                const mid = (lo + hi) >> 1;\n                if (indices[mid] <= firstIndex) {\n                    lo = mid + 1;\n                } else {\n                    hi = mid;\n                }\n            }\n            if (indices[lo] && indices[lo] < lastIndex) {\n                count++;\n            }\n        }\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int countPalindromicSubsequence(String s) {\n        \n        int n = s.length();\n        \n        char[] chArr = s.toCharArray();\n        \n        int[] firstOcc = new int[26];\n        int[] lastOcc = new int[26];\n        \n        Arrays.fill(firstOcc, -1);\n        Arrays.fill(lastOcc, -1);\n        \n        for(int i = 0; i < n; i++){\n            \n            char ch = chArr[i];\n            \n            if(firstOcc[ch - 'a'] == -1){\n                firstOcc[ch - 'a'] = i;\n            }\n            \n            lastOcc[ch - 'a'] = i;\n        }\n        \n        int ans = 0, count = 0;\n        \n        boolean[] visited;\n        \n\t\t// check for each character ( start or end of palindrome )\n        for(int i = 0; i < 26; i++){\n            \n            int si = firstOcc[i]; // si - starting index\n            int ei = lastOcc[i]; // ei - ending index\n            \n            visited = new boolean[26];\n            \n            count = 0;\n            \n\t\t\t// check for unique charcters ( middle of palindrome )\n            for(int j = si + 1; j < ei; j++){\n                \n                if(!visited[chArr[j] - 'a']){\n                    visited[chArr[j] - 'a'] = true;\n                    count++;\n                }\n            }\n            \n            ans += count;\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countPalindromicSubsequence(string s) {\n        \n        vector<pair<int, int> > v(26, {-1, -1} ); //to store first occurance  and last occurance of every alphabet.\n        \n        int n = s.length(); //size of the string\n        \n        for (int i = 0 ; i< n ;i++ ){\n            if (v[s[i] - 'a'].first == -1 ) v[s[i] - 'a'].first = i; // storing when alphabet appered first time.\n            else v[s[i] - 'a'].second = i; // else whenever it appears again. So that the last occurrence will be stored at last.\n        }\n        \n        int ans = 0 ;\n        for (int i = 0 ; i <26 ;i++ ){ //traversing over all alphabets.\n\n            if (v[i].second != -1 ){ //only if alphabet occured second time.\n                \n                unordered_set<char> st; //using set to keep only unique elements between the range.\n                \n                for (int x = v[i].first + 1 ; x < v[i].second ; x++ ) st.insert(s[x]); // set keeps only unique elemets.\n                    \n                ans += ((int)st.size()); // adding number of unique elements to the answer.\n            }\n        }\n        return ans;\n        \n    }\n};"
    },
    {
        "title": "Divide a String Into Groups of Size k",
        "algo_input": "A string s can be partitioned into groups of size k using the following procedure:\n\n\n\tThe first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.\n\tFor the last group, if the string does not have k characters remaining, a character fill is used to complete the group.\n\n\nNote that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.\n\nGiven the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcdefghi\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\"]\nExplanation:\nThe first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".\n\n\nExample 2:\n\nInput: s = \"abcdefghij\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\",\"jxx\"]\nExplanation:\nSimilar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of lowercase English letters only.\n\t1 &lt;= k &lt;= 100\n\tfill is a lowercase English letter.\n\n",
        "solution_py": "class Solution:\n    def divideString(self, s: str, k: int, fill: str) -> List[str]:\n        l, i, N = [], 0, len(s)\n        while i<N:\n            l.append(s[i:i+k])\n            i += k\n        last = l[-1]\n        if(len(last)<k):\n            l[-1] += fill*(k-len(last))\n        return l",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @param {character} fill\n * @return {string[]}\n */\nvar divideString = function(s, k, fill) \n{\n  var ans=[];\n  for(let i=0;i<s.length;i+=k)\n    {\n      ans.push(s.substring(i,i+k));\n    }\n  let str=ans[ans.length-1];\n  if(str.length==k)\n    {\n      return ans;\n    }\n  for(let i=str.length;i<k;i++)\n    {\n      ans[ans.length-1]+=fill;\n    }\n  return ans;\n};",
        "solution_java": "class Solution {\n    public String[] divideString(String s, int k, char fill) {\n        int rem = 0;\n        if( s.length() % k != 0){\n             rem = k - s.length() % k; //counting the total positions where we have to fill the char \"fill\".\n        }\n        for(int i = 0; i < rem; i++){\n            s = s+fill; //appending the char to the String\n        }\n        \n        String[] strs = new String[s.length()/k];  //the length will be String length / K because we are making pair of k length Strings.\n        int index = 0;  //index for array.\n        for(int i = 0; i < s.length(); i+=k){\n            strs[index] = s.substring(i, i+k); //substing of  current element to Kth element. \n            index++;\n        }\n        return strs;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> divideString(string s, int k, char fill) {\n        vector<string> v;\n        for(int i=0;i<s.size();i=i+k)\n        {\n            string t=s.substr(i,k); // make substring of size atmost k\n\n            if(t.size()==k) // if size if k then push\n            {\n                v.push_back(t);\n                continue;\n            }\n\n            int l=t.size(); // if it is the last group and size if less than k\n            for(int j=0;j<(k-l);j++) // add fill char to t to make size k\n                t+=fill;\n\n            v.push_back(t);\n        }\n        return v;\n    }\n};"
    },
    {
        "title": "Task Scheduler II",
        "algo_input": "You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task.\n\nYou are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.\n\nEach day, until all tasks have been completed, you must either:\n\n\n\tComplete the next task from tasks, or\n\tTake a break.\n\n\nReturn the minimum number of days needed to complete all tasks.\n\n&nbsp;\nExample 1:\n\nInput: tasks = [1,2,1,2,3,1], space = 3\nOutput: 9\nExplanation:\nOne way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.\n\n\nExample 2:\n\nInput: tasks = [5,8,8,5], space = 2\nOutput: 6\nExplanation:\nOne way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tasks.length &lt;= 105\n\t1 &lt;= tasks[i] &lt;= 109\n\t1 &lt;= space &lt;= tasks.length\n\n",
        "solution_py": "import math\nclass Solution:\n    def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n        count_dict = {}\n        total_days = 0\n        for task in tasks:\n            if task not in count_dict:\n                count_dict[task] = -math.inf\n            total_days = max(total_days + 1, count_dict[task] + space + 1)\n            count_dict[task] = total_days\n        return total_days",
        "solution_js": "var taskSchedulerII = function(tasks, n) {\n\tconst config = {};\n\tlet totalIteration = 0;\n\tlet currentTime = 0;\n\tfor (const iterator of tasks) {\n\t\tcurrentTime++;\n\t\tif (!config[iterator]) {\n\t\t\tconfig[iterator] = 0;\n\t\t} else {\n\t\t\tif (config[iterator] > currentTime) {\n\t\t\t\tlet difference = config[iterator] - currentTime;\n\t\t\t\ttotalIteration += difference;\n\t\t\t\tcurrentTime += difference;\n\t\t\t}\n\t\t}\n\t\tconfig[iterator] = currentTime + n + 1;\n\t\ttotalIteration++;\n\t}\n\n\treturn totalIteration;\n};",
        "solution_java": "class Solution {\n    public long taskSchedulerII(int[] tasks, int space) {\n        HashMap<Integer, Long> map = new HashMap<>();\n        long day = 0;\n\n        for (int item : tasks) {\n            if (map.containsKey(item) && map.get(item) > day)\n                day = map.get(item);\n\n            day++;\n            map.put(item, day + space);\n        }\n\n        return day;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long taskSchedulerII(vector<int>& tasks, int space) {\n        unordered_map<int,long long int> hash; long long int curday=0;\n        for(int i=0;i<tasks.size();i++){\n            if(hash.count(tasks[i])) curday=max(curday,hash[tasks[i]]);\n            hash[tasks[i]]=curday+space+1;\n            curday+=1;\n        }\n        return curday;\n    }\n};"
    },
    {
        "title": "Maximum Number of Words You Can Type",
        "algo_input": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.\n\nGiven a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.\n\n&nbsp;\nExample 1:\n\nInput: text = \"hello world\", brokenLetters = \"ad\"\nOutput: 1\nExplanation: We cannot type \"world\" because the 'd' key is broken.\n\n\nExample 2:\n\nInput: text = \"leet code\", brokenLetters = \"lt\"\nOutput: 1\nExplanation: We cannot type \"leet\" because the 'l' and 't' keys are broken.\n\n\nExample 3:\n\nInput: text = \"leet code\", brokenLetters = \"e\"\nOutput: 0\nExplanation: We cannot type either word because the 'e' key is broken.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 104\n\t0 &lt;= brokenLetters.length &lt;= 26\n\ttext consists of words separated by a single space without any leading or trailing spaces.\n\tEach word only consists of lowercase English letters.\n\tbrokenLetters consists of distinct lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n        text = text.split()\n        length = len(text)\n        brokenLetters = set(brokenLetters)\n\n        for word in text:\n            for char in word:\n                if char in brokenLetters:\n                    length -= 1\n                    break\n\t\t\t\t\t\n        return length",
        "solution_js": "var canBeTypedWords = function(text, brokenLetters) {\n    let regexp=\"[\"+brokenLetters+\"]\\+\"\n    let word=text.split(\" \"), count=0;\n    for(let i=0; i<word.length; i++){\n        let work=true;\n        // if matches, means word[i] contains malfunction letters.\n        if(word[i].match(regexp)){work=false};\n        if(work){count++};\n    }\n    return count;\n};",
        "solution_java": "class Solution {\n    public int canBeTypedWords(String text, String brokenLetters) {\n        int count = 1;\n        boolean isBad = false;\n        for (char c : text.toCharArray()) {\n            if (c == ' ') {\n                isBad = false;\n                count++;\n            } else {\n                if (!isBad && brokenLetters.indexOf(c) != -1) {\n                    isBad = true;\n                    count--;\n                }\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int canBeTypedWords(string text, string brokenLetters) {\n        vector<int> ch(26,0);\n\t\t// store the broken letters in ch vector\n        for(char c: brokenLetters){\n            ch[c-'a']=1;\n        }\n        int cnt=0,ans=0;\n\t\t//traversing the text string\n        for(int i=0;i<text.length();i++){\n\t\t    //if char is ' ' means that we got a new word\n            if(text[i]==' '){\n\t\t\t    // cnt remain 0 means that there is no broken letter in this word\n                if(cnt==0) ans++;\n                cnt=0; //reinitialize cnt to 0 as new word start from here\n            }else if(ch[text[i]-'a']==1){ //if char is present in ch then just increment the cnt\n                    cnt++;\n            }\n        }\n\t\t//for last word in string\n        if(cnt==0) ans++;\n        return ans;\n    }\n};"
    },
    {
        "title": "Sudoku Solver",
        "algo_input": "Write a program to solve a Sudoku puzzle by filling the empty cells.\n\nA sudoku solution must satisfy all of the following rules:\n\n\n\tEach of the digits 1-9 must occur exactly once in each row.\n\tEach of the digits 1-9 must occur exactly once in each column.\n\tEach of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.\n\n\nThe '.' character indicates empty cells.\n\n&nbsp;\nExample 1:\n\nInput: board = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput: [[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]\nExplanation:&nbsp;The input board is shown above and the only valid solution is shown below:\n\n\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == 9\n\tboard[i].length == 9\n\tboard[i][j] is a digit or '.'.\n\tIt is guaranteed that the input board has only one solution.\n\n",
        "solution_py": "class Solution:\n    def solveSudoku(self, board: List[List[str]]) -> None:\n        \"\"\"\n        Do not return anything, modify board in-place instead.\n        \"\"\"\n        full = set('123456789')\n\t\t# lets keep rows, columns and boxes sets in hashmaps\n        rows = [set() for _ in range(9)]\n        cols = [set() for _ in range(9)]\n        boxes = [[set() for _ in range(3)] for _ in range(3)]\n\t\t# and remember empty cell to fill them in\n        empty = set()\n\n        for i in range(9):\n            for j in range(9):\n                if board[i][j] == '.':\n                    empty.add((i,j))\n                    continue\n                rows[i].add(board[i][j])\n                cols[j].add(board[i][j])\n                boxes[i//3][j//3].add(board[i][j])\n                \n        def options(i, j):\n\t\t\t\"\"\"returns possible options for i,j intersecting options from row, col and box\"\"\"\n            return (\n                (full - rows[i]) &\n                (full - cols[j]) &\n                (full - boxes[i//3][j//3])\n            )\n\n        psingle = True # did we have single option decisions in previos traverse\n        while empty:\n            single = False # for single option decisions in this traverse\n            \n            for i, j in deepcopy(empty):\n                opts = options(i, j)\n                if len(opts) == 0:\n\t\t\t\t\t# we've made a wrong assumption - sudoku is unsolvable\n                    return None, None\n                elif len(opts) == 2 and not psingle: # we have no single-option decisions so have to take an assumption\n                    board1 = deepcopy(board)\n                    board1[i][j] = opts.pop()\n                    board1, empty1 = self.solveSudoku(board1)\n                    if board1 != None: # if solved - we're done\n                        empty = empty1\n                        for i, b1 in enumerate(board1):\n                            board[i] = b1 # have to modify initial list, not just replace the reference\n                        return board, empty\n                if len(opts) == 1: # hey, we have a predetermined choice. nice\n                    single = True\n                    board[i][j] = opts.pop()\n                    empty.remove((i, j))\n                    rows[i].add(board[i][j])\n                    cols[j].add(board[i][j])\n                    boxes[i//3][j//3].add(board[i][j])\n                    \n            psingle = single\n\n        return board, empty\n        ```",
        "solution_js": "var solveSudoku = function(board) {\n    let intBoard = convertBoardToInteger(board);\n\n    let y = 0, x = 0;\n\n    while (y <= 8){\n        x = 0;\n        while (x <= 8){\n            if (isFreeIndex(board, x, y)){\n                intBoard[y][x]++;\n                while (!isPossibleValue(intBoard, x, y) && intBoard[y][x] < 10){\n                    intBoard[y][x]++;\n                };\n\n                if (intBoard[y][x] > 9){\n                    intBoard[y][x] = 0;\n                    let a = retraceBoard(board, x, y);\n                    x = a[0], y = a[1];\n                    x--;\n                }\n            }\n            x++;\n        }\n        y++;\n    }\n    \n    convertIntBoardToString(intBoard, board);\n}\n\nvar isFreeIndex = function(board, x, y){\n    return (board[y][x] == '.');\n}\n\nvar isPossibleValue = function(intBoard, x, y){\n    return (isUniqueInColumn(intBoard, x, y) && isUniqueOnRow(intBoard, x, y) && isUniqueInBox(intBoard, x, y))\n}\nvar isUniqueOnRow = function(intBoard, x, y){\n    for (let i = 0;i<9;i++){\n        if (intBoard[i][x] == intBoard[y][x] && i != y){\n            return false;\n        }\n    }\n    return true;\n}\nvar isUniqueInColumn = function(intBoard, x, y){\n    for (let i = 0;i<9;i++){\n        if (intBoard[y][i] == intBoard[y][x] && i != x){\n            return false;\n        }\n    }\n    return true;\n}\nvar isUniqueInBox = function(intBoard, x, y){\n    let startX = x - (x % 3);\n    let startY = y - (y % 3);\n\n    for (let i = startX; i < startX+3; i++){\n        for (let j = startY; j < startY+3; j++){\n            if (intBoard[j][i] == intBoard[y][x] && (i != x || j != y)){\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvar retraceBoard = function(board, x, y){\n    do {\n        if (x > 0){\n            x--;\n        } else {\n            x = 8;\n            y--;\n        }\n    } while (board[y][x] != '.');\n    return [x,y]; \n}\n\nvar convertBoardToInteger = function(board){\n\n    let intBoard = new Array(8);\n    for (let y = 0;y<9;y++){\n        intBoard[y] = new Array(8);\n        for (let x =  0;x < 9;x++){\n                intBoard[y][x] = parseInt(board[y][x]);\n                if (!intBoard[y][x]) intBoard[y][x] = 0;\n        }\n    }\n    return intBoard;\n}\nvar convertIntBoardToString = function(intBoard, board){\n    for (let y = 0;y<9;y++){\n        for (let x =  0;x < 9;x++){\n                board[y][x] = intBoard[y][x].toString();\n        }\n    }\n    \n    return board;\n}",
        "solution_java": "class Solution {\n    public void solveSudoku(char[][] board) {\n       solve(board);\n    }\n    boolean solve(char board[][]){\n        for(int i = 0; i<board.length; i++){\n            for(int j = 0; j<board[0].length; j++){\n                if(board[i][j] == '.') {\n                    for(char c = '1'; c<='9'; c++){\n                        if(isValid(board, c, i, j) == true){\n                            board[i][j] = c;\n\n                            if(solve(board) == true) return true;\n                            else board[i][j] = '.';\n                        }\n                    }\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n\n    boolean isValid(char board[][], char c, int row, int col){\n        for(int i = 0; i<9; i++){\n            if(board[row][i] == c) return false;\n            if(board[i][col] == c) return false;\n            if(board[3 * (row/3) + (i/3)][3 * (col/3) + (i % 3)] == c) return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    bool issafe(vector<vector<char>> &board,int row,int col,char c)\n    {\n        for(int i=0;i<9;i++)\n        {\n            if(board[row][i]==c)\n                return 0;\n            if(board[i][col]==c)\n                return 0;\n            if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c)\n                return 0;\n        }\n        return 1;\n    }\n    \n    bool solve(vector<vector<char>> & board)\n    {\n        for(int i=0;i<9;i++)\n        {\n            for(int j=0;j<9;j++)\n            {\n                if(board[i][j]=='.')\n                {\n                    for(char c='1';c<='9';c++)\n                    {\n                        if(issafe(board,i,j,c))\n                        {\n                            board[i][j]=c;\n                            if(solve(board)==1)\n                                return 1;\n                            else\n                                board[i][j]='.';\n                        }\n                    }\n                    return 0;   \n                }\n            }\n        }\n        return 1;\n    }\n    \n    void solveSudoku(vector<vector<char>>& board) {\n        solve(board);\n    }\n};"
    },
    {
        "title": "Maximize the Confusion of an Exam",
        "algo_input": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).\n\nYou are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:\n\n\n\tChange the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').\n\n\nReturn the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.\n\n&nbsp;\nExample 1:\n\nInput: answerKey = \"TTFF\", k = 2\nOutput: 4\nExplanation: We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.\n\n\nExample 2:\n\nInput: answerKey = \"TFFT\", k = 1\nOutput: 3\nExplanation: We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.\n\n\nExample 3:\n\nInput: answerKey = \"TTFTTFTT\", k = 1\nOutput: 5\nExplanation: We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == answerKey.length\n\t1 &lt;= n &lt;= 5 * 104\n\tanswerKey[i] is either 'T' or 'F'\n\t1 &lt;= k &lt;= n\n\n",
        "solution_py": "class Solution:\n    def maxConsecutiveAnswers(self, string: str, k: int) -> int:\n        result = 0\n        j = 0\n        count1 = k\n        for i in range(len(string)):\n            if count1 == 0 and string[i] == \"F\":\n                while string[j] != \"F\":\n                    j+=1\n                count1+=1\n                j+=1\n\n            if string[i] == \"F\":\n                if count1 > 0:\n                    count1-=1\n\n            if i - j + 1 > result:\n                result = i - j + 1\n\n        j = 0\n        count2 = k\n        for i in range(len(string)):\n            if count2 == 0 and string[i] == \"T\":\n                while string[j] != \"T\":\n                    j+=1\n                count2+=1\n                j+=1\n\n            if string[i] == \"T\":\n                if count2 > 0:\n                    count2-=1\n\n            if i - j + 1 > result:\n                result = i - j + 1\n\n        return result",
        "solution_js": "var maxConsecutiveAnswers = function(answerKey, k) {\n    let [left, right, numOfTrue, numOfFalse, max] = new Array(5).fill(0);\n    const moreChanges = () => numOfTrue > k && numOfFalse > k;\n    while (right < answerKey.length) {\n        if(answerKey[right] === 'T') numOfTrue++;\n        if(answerKey[right] === 'F') numOfFalse++;\n        while(moreChanges()) {\n            if(answerKey[left] === 'T') numOfTrue--;\n            if(answerKey[left] === 'F') numOfFalse--;    \n            left++;    \n        }\n        max = Math.max(max, right - left + 1);\n        right++;\n    }\n    return max;\n};",
        "solution_java": "class Solution {\n\n    // Binary Search + Sliding Window fixed\n\n    public int maxConsecutiveAnswers(String answerKey, int k) {\n\n        int start = 1 ;\n        int end = answerKey.length();\n        int max_length = 0 ;\n\n        while(start <= end) {\n            int mid = start+(end-start)/2 ;\n            if(isMax(answerKey , k , mid)) {\n                max_length = mid ;\n                start = mid+1 ;\n            }else {\n                end = mid-1 ;\n            }\n        }\n\n        return max_length ;\n    }\n\n    public boolean isMax(String answerKey , int k , int max_val) {\n\n        int T_count = 0 ;\n        int F_count = 0 ;\n\n        int i = 0 ;\n        int j = 0 ;\n\n        while(j < answerKey.length()) {\n\n            if(answerKey.charAt(j) == 'T') {\n                T_count++ ;\n            }else {\n                F_count++ ;\n            }\n\n            if(j-i+1 == max_val) {\n\n                if(Math.max(T_count, F_count)+k >= max_val) {\n                    return true ;\n                }\n\n                if(answerKey.charAt(i) == 'T') {\n                    T_count-- ;\n                }else {\n                    F_count-- ;\n                }\n\n                i++ ;\n            }\n\n            j++ ;\n        }\n\n        return false ;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxConsecutiveAnswers(string answerKey, int k) {\n        return max(helper(answerKey,k,'T'),helper(answerKey,k,'F'));\n    }\n\n    int helper(string answerKey, int k,char c){\n        int start = 0;\n        int end = 0;\n        int count = 0;\n        int ans = 0;\n        while(end<answerKey.length()){\n            if(answerKey[end]==c)count++;\n            while(count>k){\n                if(answerKey[start]==c)count--;\n                start++;\n            }\n            ans = max(ans,end-start+1);\n            end++;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Difference Between Increasing Elements",
        "algo_input": "Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 &lt;= i &lt; j &lt; n and nums[i] &lt; nums[j].\n\nReturn the maximum difference. If no such i and j exists, return -1.\n\n&nbsp;\nExample 1:\n\nInput: nums = [7,1,5,4]\nOutput: 4\nExplanation:\nThe maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i &gt; j, so it is not valid.\n\n\nExample 2:\n\nInput: nums = [9,4,3,2]\nOutput: -1\nExplanation:\nThere is no i and j such that i &lt; j and nums[i] &lt; nums[j].\n\n\nExample 3:\n\nInput: nums = [1,5,2,10]\nOutput: 9\nExplanation:\nThe maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t2 &lt;= n &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maximumDifference(self, nums: List[int]) -> int:\n        curmin = nums[0]\n        diff = 0\n        for num in nums:\n            diff = max(diff, num - curmin)\n            curmin = min(curmin, num)\n        return diff or -1",
        "solution_js": "var maximumDifference = function(nums) {\n    var diff=-1\n    for(let i=0;i<nums.length;i++){\n        for(let j=i+1;j<nums.length;j++){\n            if (nums[j]> nums[i]) diff=Math.max(nums[j]-nums[i],diff)\n        }\n    }\n    return diff\n};",
        "solution_java": "class Solution {\n    public int maximumDifference(int[] nums) {\n        if(nums.length < 2)\n            return -1;\n        int result = Integer.MIN_VALUE;\n        int minValue = nums[0];\n        for(int i = 1; i < nums.length; i++) {\n            if(nums[i] > minValue)\n                result = Math.max(result, nums[i] - minValue);\n            minValue = Math.min(minValue, nums[i]);\n        }\n        return result == Integer.MIN_VALUE ? -1 : result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumDifference(vector<int>& nums) {\n        int mn = nums[0], res = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            res = max(res, nums[i] - mn);\n            mn = min(mn, nums[i]);\n        }\n        return res == 0 ? -1 : res;\n    }\n};"
    },
    {
        "title": "Sort the Matrix Diagonally",
        "algo_input": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].\n\nGiven an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n\n\nExample 2:\n\nInput: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 100\n\t1 &lt;= mat[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def diagonalSort(self, A: List[List[int]]) -> List[List[int]]:\n        n, m, d = len(A), len(A[0]), defaultdict(list)\n        any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m))\n        any(d[sum_].sort(reverse=1) for sum_ in d)\n        return [[d[i-j].pop() for j in range(m)] for i in range(n)]",
        "solution_js": "/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nvar diagonalSort = function(mat) {\nconst res=new Array(mat.length);\n    \nfor(let i=0;i<mat.length;i++)\n    res[i]=new Array(mat[i].length);\n\n    \nfor(let i=0;i<mat.length;i++){\n    for(let j=0;j<mat[i].length;j++){\n        if(i===0 || j===0){\n            const scale= i-j;\n            let val=[],index=[];\n            \n            for(let i=0;i<mat.length;i++){\n                for(let j=0;j<mat[i].length;j++){\n                    if(scale===i-j){\n                        val.push(mat[i][j]);    \n                        index.push([i,j]);            \n                    }\n                }\n            }\n            val=val.sort((a,b)=>a-b);\n            index.forEach(([x,y],id)=>res[x][y]=val[id]);\n        }\n    }\n}\n    return res;\n\n};",
        "solution_java": "class Solution {\n    public int[][] diagonalSort(int[][] mat) {\n        int n = mat.length; \n        int m = mat[0].length;\n        for(int i=0;i<m;i++){\n            give(0,i,mat,n,m);\n        }\n        for(int i=1;i<n;i++){\n            give(i,0,mat,n,m);\n        }\n        return mat;\n    }\n    public void give(int i,int j,int[][] mat,int n,int m){\n        int[] dig = new int[Math.min(m-j,n-i)];\n        int r = i;\n        int c = j;\n        int k = 0;\n        while(r<n && c<m){\n            dig[k] = mat[r][c];\n            r++;\n            c++;\n            k++;\n        }\n        Arrays.sort(dig);\n        k = 0;\n        while(i<n && j<m){\n            mat[i][j] = dig[k];\n            i++;\n            j++;\n            k++;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tvoid sortmat(int i,int j,vector<vector<int>>& mat,int m,int n,vector<int>& temp){\n\t\tif(i>=m || j>=n){\n\t\t\tsort(temp.begin(),temp.end());\n\t\t\treturn ;\n\t\t}\n\t\ttemp.push_back(mat[i][j]);\n\t\tsortmat(i+1,j+1,mat,m,n,temp);\n\t\tmat[i][j]=temp.back();\n\t\ttemp.pop_back();\n\t}\n\n\tvector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\n\t\tint m=mat.size();\n\t\tint n=mat[0].size();\n\t\tvector<int>temp;\n//      For column\n\t\tfor(int j=0;j<n;j++) sortmat(0,j,mat,m,n,temp);\n//      For Row\n\t\tfor(int i=1;i<m;i++) sortmat(i,0,mat,m,n,temp);\n\t\treturn mat;\n\t}\n};"
    },
    {
        "title": "Cells in a Range on an Excel Sheet",
        "algo_input": "A cell (r, c) of an excel sheet is represented as a string \"&lt;col&gt;&lt;row&gt;\" where:\n\n\n\t&lt;col&gt; denotes the column number c of the cell. It is represented by alphabetical letters.\n\n\t\n\t\tFor example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.\n\t\n\t\n\t&lt;row&gt; is the row number r of the cell. The rth row is represented by the integer r.\n\n\nYou are given a string s&nbsp;in&nbsp;the format \"&lt;col1&gt;&lt;row1&gt;:&lt;col2&gt;&lt;row2&gt;\", where &lt;col1&gt; represents the column c1, &lt;row1&gt; represents the row r1, &lt;col2&gt; represents the column c2, and &lt;row2&gt; represents the row r2, such that r1 &lt;= r2 and c1 &lt;= c2.\n\nReturn the list of cells (x, y) such that r1 &lt;= x &lt;= r2 and c1 &lt;= y &lt;= c2. The cells should be represented as&nbsp;strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.\n\n&nbsp;\nExample 1:\n\nInput: s = \"K1:L2\"\nOutput: [\"K1\",\"K2\",\"L1\",\"L2\"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.\n\n\nExample 2:\n\nInput: s = \"A1:F1\"\nOutput: [\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.\n\n\n&nbsp;\nConstraints:\n\n\n\ts.length == 5\n\t'A' &lt;= s[0] &lt;= s[3] &lt;= 'Z'\n\t'1' &lt;= s[1] &lt;= s[4] &lt;= '9'\n\ts consists of uppercase English letters, digits and ':'.\n\n",
        "solution_py": "class Solution:\n    def cellsInRange(self, s: str) -> List[str]:\n        start, end = s.split(':')\n        start_letter, start_num = start[0], int(start[-1])\n        end_letter, end_num = end[0], int(end[1])\n        alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n        alphabet_slice = \\\n            alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1]\n        res = list()\n        for el in alphabet_slice:\n            res += [el + str(num) for num in range(start_num, end_num + 1)]\n        return res",
        "solution_js": "const toCharCode = (char) => char.charCodeAt()\n\nvar cellsInRange = function(s) {\n    const result = []\n    for(let i = toCharCode(s[0]) ; i <= toCharCode(s[3]) ; i++){\n        for(let j = s[1] ; j <= s[4] ; j++){\n            result.push(String.fromCharCode(i) +j)\n        }\n    }\n    return result\n};",
        "solution_java": "class Solution {\n    public List<String> cellsInRange(String s) {\n        char sc = s.charAt(0), ec = s.charAt(3);\n        char sr = s.charAt(1), er = s.charAt(4);\n        List<String> res = new ArrayList<>();\n        \n        for (char i = sc; i <= ec; ++i){\n            for (char j = sr; j <= er; ++j){\n                res.add(new String(new char[]{i, j}));\n            }\n        }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> cellsInRange(string s) {\n\n        vector<string>ans;\n\n        for(char ch=s[0];ch<=s[3];ch++)\n        {\n            for(int i=s[1]-'0';i<=s[4]-'0';i++)\n            {\n                string res=\"\";\n                res+=ch;\n                res+=to_string(i);\n                ans.push_back(res);\n\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Candy",
        "algo_input": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.\n\nYou are giving candies to these children subjected to the following requirements:\n\n\n\tEach child must have at least one candy.\n\tChildren with a higher rating get more candies than their neighbors.\n\n\nReturn the minimum number of candies you need to have to distribute the candies to the children.\n\n&nbsp;\nExample 1:\n\nInput: ratings = [1,0,2]\nOutput: 5\nExplanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n\n\nExample 2:\n\nInput: ratings = [1,2,2]\nOutput: 4\nExplanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == ratings.length\n\t1 &lt;= n &lt;= 2 * 104\n\t0 &lt;= ratings[i] &lt;= 2 * 104\n\n",
        "solution_py": "class Solution:\n    def candy(self, ratings: List[int]) -> int:\n        n=len(ratings)\n        temp = [1]*n\n\n        for i in range(1,n):\n            if(ratings[i]>ratings[i-1]):\n                temp[i]=temp[i-1]+1\n        if(n>1):\n            if(ratings[0]>ratings[1]):\n                temp[0]=2\n\n        for i in range(n-2,-1,-1):\n            if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):\n                temp[i]=temp[i+1]+1\n\n        return sum(temp)",
        "solution_js": "/**\n * @param {number[]} ratings\n * @return {number}\n */\nvar candy = function(ratings) {\n    const n = ratings.length;    \n    \n    let candies = [...Array(n)].fill(1);\n \n    let index = 0;\n    let copy = [ratings[0]];\n    \n    let isDecreasing = true;\n    for(let i = 1; i < n; i++) {\n        if (ratings[i] > ratings[i - 1]) {\n            isDecreasing = false;\n            break;\n        }\n        /* In case of decreasing sequence, make a copy of the current rating, but in inverted format */\n        copy.unshift(ratings[i]);\n    }\n    \n    if (isDecreasing) {\n        ratings = copy;\n    } else {\n        copy = [];\n    }\n    \n    while(index >= 0) {\n        \n        if (index >= n) {\n            break;\n        }\n\n        if (ratings[index] > ratings[index + 1] && candies[index + 1] >= candies[index]) {            \n            candies[index] = candies[index] + 1;            \n            index = Math.max(-1, index - 2);\n        }\n        else if (ratings[index] > ratings[index - 1] && candies[index - 1] >= candies[index]) {            \n            candies[index] = candies[index - 1] + 1;\n        }\n\n        index++;\n     }\n\n    \n    return candies.reduce((sum, candy) => sum + candy, 0);\n}",
        "solution_java": "class Solution {\n    public int candy(int[] ratings) {\n\n        int[] left = new int[ratings.length];\n        Arrays.fill(left, 1);\n\n        // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy\n        for(int i = 0; i<ratings.length-1; i++){\n            if(ratings[i] < ratings[i+1])\n                left[i+1] = left[i]+1;\n        }\n\n        int[] right = new int[ratings.length];\n        Arrays.fill(right, 1);\n\n        //we are checking from right to left if the element after than our current element is greater or not , if yes then we are also checking their candies if greater rating has less number of candies then increasing their candy\n        for(int i = ratings.length -2; i>=0; i--){\n            if(ratings[i+1] < ratings[i] && right[i] <= right[i+1])\n                right[i] = right[i+1]+1;\n        }\n        int sum = 0;\n        for(int i = 0; i<right.length; i++){\n            sum += Math.max(right[i], left[i]);\n        }\n\n    return sum;}\n}",
        "solution_c": "class Solution {\npublic:\n    int candy(vector<int>& ratings) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        int ans = 0, i;\n        vector<int> store(ratings.size(), 1);\n        for (i = 0; i < ratings.size()-1; i++) if(ratings[i+1] > ratings[i]) store[i+1] = store[i]+1;\n        for (i = ratings.size()-1; i > 0; i--) if(ratings[i-1] > ratings[i]) store[i-1] = max(store[i-1], store[i]+1);\n        for (auto i:store) ans += i;\n        return ans;\n    }\n};"
    },
    {
        "title": "Last Stone Weight",
        "algo_input": "You are given an array of integers stones where stones[i] is the weight of the ith stone.\n\nWe are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x &lt;= y. The result of this smash is:\n\n\n\tIf x == y, both stones are destroyed, and\n\tIf x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\n\n\nAt the end of the game, there is at most one stone left.\n\nReturn the weight of the last remaining stone. If there are no stones left, return 0.\n\n&nbsp;\nExample 1:\n\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\n\n\nExample 2:\n\nInput: stones = [1]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= stones.length &lt;= 30\n\t1 &lt;= stones[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def lastStoneWeight(self, stones: List[int]) -> int:\n        stones = [-x for x in stones]\n        heapq.heapify(stones)\n\n        while len(stones) > 1:\n            mx1 = -heapq.heappop(stones)\n            mx2 = -heapq.heappop(stones)\n            if mx1 - mx2:\n                heapq.heappush(stones, -(mx1 - mx2))\n\n        if len(stones):\n            return -heapq.heappop(stones)\n        return 0",
        "solution_js": "var lastStoneWeight = function(stones) {\n    let first = 0, second = 0;\n    stones.sort((a,b) => a - b);\n    while(stones.length > 1) {\n        first = stones.pop();\n        second = stones.pop();\n        stones.push(first - second);\n        stones.sort((a,b) => a - b);\n    }\n    return stones[0];\n};",
        "solution_java": "class Solution {\n    public int lastStoneWeight(int[] stones) {\n        PriorityQueue<Integer> pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x));\n        for (int i = 0; i < stones.length; i++) {\n            pq.add(stones[i]);\n        }\n        while (pq.size() > 1) {\n            int r1 = pq.poll();\n            int r2 = pq.poll();\n            if (r1 != r2) pq.add(r1 - r2);\n        }\n        return (pq.isEmpty()) ? 0 : pq.poll();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int lastStoneWeight(vector<int>& stones) {\n        while(stones.size()>1){\n            sort(stones.begin(), stones.end(), greater<int>());\n            stones[1] = (stones[0]-stones[1]);\n            stones.erase(stones.begin());\n        }\n        return stones[0];\n    }\n};"
    },
    {
        "title": "Widest Vertical Area Between Two Points Containing No Points",
        "algo_input": "Given n points on a 2D plane where points[i] = [xi, yi], Return&nbsp;the widest vertical area between two points such that no points are inside the area.\n\nA vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.\n\nNote that points on the edge of a vertical area are not considered included in the area.\n\n&nbsp;\nExample 1:\n​\nInput: points = [[8,7],[9,9],[7,4],[9,7]]\nOutput: 1\nExplanation: Both the red and the blue area are optimal.\n\n\nExample 2:\n\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tn == points.length\n\t2 &lt;= n &lt;= 105\n\tpoints[i].length == 2\n\t0 &lt;= xi, yi&nbsp;&lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n        # only taking x-axis point as it's relevant\n        arr = [i[0] for i in points]\n        \n        arr.sort()\n        \n        diff = -1\n        for i in range(1, len(arr)):\n            diff = max(diff, arr[i] - arr[i - 1])\n        \n        return diff",
        "solution_js": "var maxWidthOfVerticalArea = function(points) {\n    let ans = 0;\n    points = points.map(item => item[0]).sort((a, b) => a - b);\n    \n    for(let i = 1; i < points.length; i++){\n        \n        ans = Math.max(ans, points[i] - points[i-1]);\n    }\n        \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxWidthOfVerticalArea(int[][] points) {\n        int L = points.length;\n        // y-coordinate of a point does not matter in width\n        int arr[] = new int[L];\n        for(int i=0;i<L;i++){\n            arr[i]=points[i][0];\n        }\n        Arrays.sort(arr);\n\n        int diff = Integer.MIN_VALUE;\n\n        for(int i=1;i<L;i++){\n            if((arr[i]-arr[i-1])>diff){\n                diff=arr[i]-arr[i-1];\n            }\n        }\n        return diff;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n        sort(begin(points),end(points));\n        int n=points.size();\n        int m=0;\n        for(int i=0;i<n-1;i++)\n            m=max(points[i+1][0]-points[i][0],m);\n        return m;\n    }\n};"
    },
    {
        "title": "Replace Elements with Greatest Element on Right Side",
        "algo_input": "Given an array arr,&nbsp;replace every element in that array with the greatest element among the elements to its&nbsp;right, and replace the last element with -1.\n\nAfter doing so, return the array.\n\n&nbsp;\nExample 1:\n\nInput: arr = [17,18,5,4,6,1]\nOutput: [18,6,6,6,1,-1]\nExplanation: \n- index 0 --&gt; the greatest element to the right of index 0 is index 1 (18).\n- index 1 --&gt; the greatest element to the right of index 1 is index 4 (6).\n- index 2 --&gt; the greatest element to the right of index 2 is index 4 (6).\n- index 3 --&gt; the greatest element to the right of index 3 is index 4 (6).\n- index 4 --&gt; the greatest element to the right of index 4 is index 5 (1).\n- index 5 --&gt; there are no elements to the right of index 5, so we put -1.\n\n\nExample 2:\n\nInput: arr = [400]\nOutput: [-1]\nExplanation: There are no elements to the right of index 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t1 &lt;= arr[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def replaceElements(self, arr: List[int]) -> List[int]:\n        maxright = arr[-1]\n        for i in range(len(arr) -1,-1,-1):\n            temp = arr[i]\n            arr[i] = maxright\n            if temp > maxright:\n                maxright = temp\n        arr[-1] = -1\n        \n        return arr",
        "solution_js": " * @param {number[]} arr\n * @return {number[]}\n */\nvar replaceElements = function(arr) {\n    let max = arr[arr.length -1]\n    \n     for(let j=arr.length - 2; j>=0; --j){\n         let curr = arr[j];\n         arr[j] = max\n         max = Math.max(max,curr)\n     }\n    \n    arr[arr.length -1] = -1;\n    return arr;\n};",
        "solution_java": "class Solution {\n    public int[] replaceElements(int[] arr) {\n      int greatElement = -1;\n        for(int i = arr.length-1; i >= 0; i--) {\n            int temp = arr[i];\n            arr[i] = greatElement;\n            greatElement = Math.max(temp, greatElement);\n        }\n        return arr;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> replaceElements(vector<int>& arr) {\n        int n=arr.size();\n\n        //taking last index as greatest for now\n        int g=arr[n-1];\n        //setting last index as -1\n        arr[n-1]=-1;\n        for(int i=n-2;i>=0;i--)\n        {\n        //storing last index value to be changed to comapare with the greatest value till now\n            int h=arr[i];\n            //assigning greatest till now from right\n            arr[i]=g;\n            //checking if current is greater than the previous indices\n            if(h>g)\n            {\n                g=h;\n            }\n        }\n                     //returning the value\n     return arr;\n    }\n};"
    },
    {
        "title": "Best Poker Hand",
        "algo_input": "You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].\n\nThe following are the types of poker hands you can make from best to worst:\n\n\n\t\"Flush\": Five cards of the same suit.\n\t\"Three of a Kind\": Three cards of the same rank.\n\t\"Pair\": Two cards of the same rank.\n\t\"High Card\": Any single card.\n\n\nReturn a string representing the best type of poker hand you can make with the given cards.\n\nNote that the return values are case-sensitive.\n\n&nbsp;\nExample 1:\n\nInput: ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\nOutput: \"Flush\"\nExplanation: The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".\n\n\nExample 2:\n\nInput: ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\nOutput: \"Three of a Kind\"\nExplanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.\n\nExample 3:\n\nInput: ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\nOutput: \"Pair\"\nExplanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".\n\n\n&nbsp;\nConstraints:\n\n\n\tranks.length == suits.length == 5\n\t1 &lt;= ranks[i] &lt;= 13\n\t'a' &lt;= suits[i] &lt;= 'd'\n\tNo two cards have the same rank and suit.\n\n",
        "solution_py": "class Solution:\n    def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n        s={}\n        for i in suits:\n            if i in s:\n                s[i]+=1\n                if s[i]==5:\n                    return 'Flush'\n            else:\n                s[i]=1\n        r={}\n        max_ = 0\n        for i in ranks:\n            if i in r:\n                r[i]+=1\n                max_=max(max_,r[i])\n            else:\n                r[i]=1\n        if max_>=3:\n            return \"Three of a Kind\"\n        elif max_==2:\n            return \"Pair\"\n        else:\n            return \"High Card\"",
        "solution_js": "var bestHand = function(ranks, suits) {\n    let suitsMap = {}\n    for (let i=0; i<suits.length; i++) {\n        if (suitsMap[suits[i]]) {\n            suitsMap[suits[i]]++;\n        } else {\n            suitsMap[suits[i]] = 1;\n        }\n    }\n    if (Object.keys(suitsMap).length === 1) return \"Flush\";\n    let pair = false;\n    let ranksMap = {};\n    for (let i=0; i<ranks.length; i++) {\n        if (ranksMap[ranks[i]]) {\n            ranksMap[ranks[i]]++;\n            if (ranksMap[ranks[i]] >= 3) return \"Three of a Kind\";\n        } else {\n            ranksMap[ranks[i]] = 1;\n        }\n    }\n    if (Object.keys(ranksMap).length === 5) return \"High Card\";\n    return \"Pair\";\n};",
        "solution_java": "class Solution {\n    public String bestHand(int[] ranks, char[] suits) {\n    int max = 0;\n    int card = 0;\n    char ch = suits[0];\n    int[] arr = new int[14];\n    for(int i = 0; i < 5; i++){\n        arr[ranks[i]]++;\n        max = Math.max(max,arr[ranks[i]]);\n        if(suits[i] == ch) card++;\n    }\n        if(card == 5) return \"Flush\";\n     return max >= 3 ? \"Three of a Kind\":(max == 2 ? \"Pair\" : \"High Card\");\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string bestHand(vector<int>& ranks, vector<char>& suits) {\n        map<int, int> m1;\n        int mn = INT_MIN;\n        int all_same = count(begin(suits), end(suits), suits[0]);\n        int n = ranks.size();\n        for (int i = 0; i < n; i++) {\n            m1[ranks[i]]++;\n            mn = max(mn, m1[ranks[i]]);\n        }\n        if (all_same == n)     return \"Flush\";\n        if (mn >= 3)      return \"Three of a Kind\";\n        if (mn == 2)      return \"Pair\";\n        return \"High Card\";\n    }\n};"
    },
    {
        "title": "Populating Next Right Pointers in Each Node II",
        "algo_input": "Given a binary tree\n\nstruct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n\n\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\n\nInitially, all next pointers are set to NULL.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: [1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 6000].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow-up:\n\n\n\tYou may only use constant extra space.\n\tThe recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.\n\n",
        "solution_py": "\"\"\"\n# Definition for a Node.\nclass Node(object):\n    def __init__(self, val=0, left=None, right=None, next=None):\n        self.val = val\n        self.left = left\n        self.right = right\n        self.next = next\n\"\"\"\n\nclass Solution(object):\n    def findRightMost(self, root, level, requiredLevel):\n        if not root:\n            return root\n        if level == requiredLevel:\n            return root\n        right = self.findRightMost(root.right, level + 1, requiredLevel)\n        if right:\n            return right\n        return self.findRightMost(root.left, level + 1, requiredLevel)\n    def findLeftMost(self, root, level, requiredLevel):\n        if not root:\n            return root\n        if level == requiredLevel:\n            return root\n        left = self.findLeftMost(root.left, level + 1, requiredLevel)\n        if left:\n            return left\n        return self.findLeftMost(root.right, level + 1, requiredLevel)\n    def findRightMostFromRoot(self, rootLevelInfo, requiredLevel, currentRight):\n        if currentRight:\n            if currentRight.right:\n                return currentRight.right\n            if currentRight.left:\n                return currentRight.left\n        root, rootlevel = rootLevelInfo\n        rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n        while not rightMost and root:\n            root = root.right if root.right else root.left\n            rootlevel += 1\n            rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n            if rightMost:\n                rootLevelInfo[-1] = rootlevel\n                rootLevelInfo[0] = root\n        return rightMost\n    def findLeftMostFromRoot(self, rootLevelInfo, requiredLevel, currentLeft):\n        if currentLeft:\n            if currentLeft.left:\n                return currentLeft.left\n            if currentLeft.right:\n                return currentLeft.right\n        root, rootlevel = rootLevelInfo\n        leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n        while not leftMost and root:\n            root = root.left if root.left else root.right\n            rootlevel += 1\n            leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n            if leftMost:\n                rootLevelInfo[-1] = rootlevel\n                rootLevelInfo[0] = root\n\n        return leftMost\n    def stitch(self, root):\n        if not root:\n            return\n        leftRootStart = [root.left, 1]\n        rightRootStart = [root.right, 1]\n        connectLevel = 1\n        currentLeft = self.findLeftMostFromRoot(rightRootStart, 1, None)\n        currentRight = self.findRightMostFromRoot(leftRootStart, 1, None)\n        while currentLeft and currentRight:\n            currentRight.next = currentLeft\n            connectLevel += 1\n            currentLeft = self.findLeftMostFromRoot(rightRootStart, connectLevel, currentLeft)\n            currentRight = self.findRightMostFromRoot(leftRootStart, connectLevel, currentRight)\n\n        self.stitch(root.left)\n        self.stitch(root.right)\n    def connect(self, root):\n        \"\"\"\n        :type root: Node\n        :rtype: Node\n        \"\"\"\n        if not root:\n            return root\n        self.stitch(root)\n        return root",
        "solution_js": "var connect = function(root) {\n    let curr = root;\n    \n    while (curr != null) {\n        let start = null; // (1)\n        let prev = null;\n    \n        while (curr != null) { // (2)\n            if (start == null) { // (3)\n                if (curr.left) start = curr.left;\n                else if (curr.right) start = curr.right;\n                \n                prev = start; // (4)\n            }\n            \n            if (prev != null) {\n                if (curr.left && prev != curr.left) {\n                    prev = prev.next = curr.left; // (5)\n                }\n                if (curr.right && prev != curr.right) {\n                    prev = prev.next = curr.right;\n                }\n            }\n\n            curr = curr.next; // (6)\n        }\n\t\t\n        curr = start; // (7)\n    }\n    \n    return root;\n};",
        "solution_java": "class Solution {\n    public Node connect(Node root) {\n        if (root == null) {\n            return root;\n        }\n        Node head = null; //the start node of next level, the first left of next level\n        Node prev = null; //the next pointer\n        Node curr = root;\n\n        while (curr != null) {\n            //traverse the whole current level, left -> right, until we meet a null pointer\n            while (curr != null) {\n                if (curr.left != null) {\n                    if (head == null) {\n                        head = curr.left;\n                        prev = curr.left;\n                    } else {\n                        prev.next = curr.left;\n                        prev = prev.next;\n                    }\n                }\n\n                if (curr.right != null) {\n                    if (head == null) {\n                        head = curr.right;\n                        prev = curr.right;\n                    } else {\n                        prev.next = curr.right;\n                        prev = prev.next;\n                    }\n                }\n                curr = curr.next;\n            }\n\n            curr = head;\n            prev = null;\n            head = null;\n        }\n        return root;\n    }\n}",
        "solution_c": "// method-1\nclass Solution {\npublic:\n    Node* connect(Node* root) {\n        if(!root)\n            return NULL;\n        queue<Node*> q;\n        q.push(root);\n        root->next=NULL;\n\n        while(!q.empty()){\n\n            int size=q.size();\n            Node* prev=NULL;\n\n            for(int i=0;i<size;i++){\n                Node* temp=q.front();\n                q.pop();\n\n                if(prev)\n                    prev->next=temp;\n\n                if(i==size-1){\n                    temp->next=NULL;\n                }\n\n                if(temp->left)\n                    q.push(temp->left);\n\n                if(temp->right)\n                    q.push(temp->right);\n\n                prev=temp;\n\n            }\n        }\n\n        return root;\n    }\n};"
    },
    {
        "title": "Number of Laser Beams in a Bank",
        "algo_input": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.\n\nThere is one laser beam between any two security devices if both conditions are met:\n\n\n\tThe two devices are located on two different rows: r1 and r2, where r1 &lt; r2.\n\tFor each row i where r1 &lt; i &lt; r2, there are no security devices in the ith row.\n\n\nLaser beams are independent, i.e., one beam does not interfere nor join with another.\n\nReturn the total number of laser beams in the bank.\n\n&nbsp;\nExample 1:\n\nInput: bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\nOutput: 8\nExplanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0th row with any on the 3rd row.\nThis is because the 2nd row contains security devices, which breaks the second condition.\n\n\nExample 2:\n\nInput: bank = [\"000\",\"111\",\"000\"]\nOutput: 0\nExplanation: There does not exist two devices located on two different rows.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == bank.length\n\tn == bank[i].length\n\t1 &lt;= m, n &lt;= 500\n\tbank[i][j] is either '0' or '1'.\n\n",
        "solution_py": "class Solution(object):\n    def numberOfBeams(self, bank):\n        ans, pre = 0, 0\n        for s in bank:\n            n = s.count('1')\n            if n == 0: continue\n            ans += pre * n\n            pre = n\n        return ans",
        "solution_js": "var numberOfBeams = function(bank) {\n    let totalBeams = 0;\n    const maximumSecurityDevicePerRow = bank.map(row => (row.match(/1/g) || []).length).filter(Boolean)\n    for (let index = 0; index < maximumSecurityDevicePerRow.length - 1; index++) \n        totalBeams+= maximumSecurityDevicePerRow[index] * maximumSecurityDevicePerRow[index + 1];\n    return totalBeams;\n};",
        "solution_java": "class Solution {\n    public int numberOfBeams(String[] bank) {\n        int ans = 0, pre = 0;\n        for (int i = 0;i < bank.length; i ++) {\n            int n = 0;\n            for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++;\n            if (n == 0) continue;\n            ans += pre * n;;\n            pre = n;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfBeams(vector<string>& bank) \n    {\n        int rowLaserCount=0,totalLaserCount=0,prevCount=0;\n        for(int i=0;i<bank.size();i++)\n        {\n            rowLaserCount=0;\n            for(char j:bank[i])\n            {\n              if(j=='1')  rowLaserCount++;\n            }totalLaserCount+=(prevCount*rowLaserCount);\n            if(rowLaserCount)prevCount=rowLaserCount;\n        }\n        return totalLaserCount;\n        \n    }\n};"
    },
    {
        "title": "Three Equal Parts",
        "algo_input": "You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.\n\nIf it is possible, return any [i, j] with i + 1 &lt; j, such that:\n\n\n\tarr[0], arr[1], ..., arr[i] is the first part,\n\tarr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and\n\tarr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.\n\tAll three parts have equal binary values.\n\n\nIf it is not possible, return [-1, -1].\n\nNote that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.\n\n&nbsp;\nExample 1:\nInput: arr = [1,0,1,0,1]\nOutput: [0,3]\nExample 2:\nInput: arr = [1,1,0,1,1]\nOutput: [-1,-1]\nExample 3:\nInput: arr = [1,1,0,0,1]\nOutput: [0,2]\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= arr.length &lt;= 3 * 104\n\tarr[i] is 0 or 1\n\n",
        "solution_py": "class Solution:\n    def threeEqualParts(self, arr: List[int]) -> List[int]:\n        n = len(arr)\n        count_one = arr.count(1)\n        if count_one == 0: return [0,n-1]\n        if count_one % 3!= 0: return [-1,-1]\n        target_ones = count_one // 3\n        breaks = []\n        one_count = 0\n        for i , bit in enumerate(arr):\n            if bit ==1 :\n                one_count +=1\n                if one_count in [1,target_ones+1,2*target_ones+1]:breaks.append(i)   \n                if one_count in [target_ones,2*target_ones,3*target_ones]:breaks.append(i)\n        i1,j1,i2,j2,i3,j3 = breaks\n        \n        if not arr[i1:j1+1] == arr[i2:j2+1] == arr[i3:j3+1]:return [-1,-1]\n        \n        trailing_zeroes_left  = i2 - j1 - 1\n        trailing_zeroes_mid   = i3 - j2 - 1\n        trailing_zeroes_right = n -  j3 - 1\n        if trailing_zeroes_right > min(trailing_zeroes_left,trailing_zeroes_mid):return [-1,-1]\n        j1 += trailing_zeroes_right\n        j2 += trailing_zeroes_right\n        return [j1,j2+1]\n    ",
        "solution_js": "/**\n * @param {number[]} arr\n * @return {number[]}\n */\nvar threeEqualParts = function(arr) {\n  const ones = arr.reduce((s, n) => s + n, 0);\n  if (ones === 0) return [0, 2];\n  if (ones % 3 !== 0) return [-1, -1];\n  let onesToFind = ones / 3;\n  let k = arr.length;\n  while (onesToFind > 0) if (arr[--k] === 1) --onesToFind;\n  const iter = arr.length - k;\n  const firstOne = arr.indexOf(1);\n  const secondOne = arr.indexOf(1, firstOne + iter);\n  for (let i = 0; i < iter; i++)\n    if (arr[i + firstOne] !== arr[k + i] || arr[i + secondOne] !== arr[k + i]) return [-1, -1];\n  return [firstOne + iter - 1, secondOne + iter];\n};",
        "solution_java": "class Solution {\n    public int[] threeEqualParts(int[] arr) {\n        List<Integer> ones = new ArrayList<>();\n        for (int i = 0; i < arr.length; i++){\n            if (arr[i]==1){\n                ones.add(i);\n            }\n        }\n        if (ones.size()==0){ // edge case\n            return new int[]{0,2};\n        }\n        int[] ans = new int[2];\n        int each = ones.size()/3;\n        for (int i = 0; i < 2 && ones.size()%3==0; i++){ // for the first 2 partitions\n            for (int j = 0; j < each-1; j++){ // compare gaps\n                if (ones.get(j+1+i*each)-ones.get(j+i*each)!=ones.get(j+2*each+1)-ones.get(j+2*each))\n                    return new int[]{-1, -1};\n            }\n            ans[i]=ones.get((i+1)*each-1)+i+(arr.length - 1 - ones.get(ones.size()-1)); // cut point\n        }\n        return ones.size()%3>0||ans[0]>=ones.get(each)||ans[1]>ones.get(2*each)?\n            new int[]{-1, -1} : ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> threeEqualParts(vector<int>& v) {\n        vector<int> one;\n        int n=v.size();\n        for(int i=0;i<n;i++){\n            if(v[i]==1) one.push_back(i+1);\n        }\n        if(one.size()==0){\n            return {0,2};\n        }\n        if(one.size()%3)    return {-1,-1};\n\n        int ext=n-one.back(),sz=one.size();\n        int gap1=one[sz/3]-one[sz/3-1]-1,gap2=one[2*sz/3]-one[2*sz/3-1]-1;\n        // cout<<gap1<<\" \"<<gap2<<endl;\n        if(gap1<ext || gap2<ext)    return {-1,-1};\n\n        string s1,s2,s3;\n        for(int i=0;i<=one[sz/3-1]+ext-1;i++){\n            if(s1.length()>0 || v[i])   s1+=to_string(v[i]);\n        }\n\n        for(int i=one[sz/3-1]+ext;i<=one[2*sz/3-1]+ext-1;i++){\n            if(s2.length()>0 || v[i])   s2+=to_string(v[i]);\n        }\n\n        for(int i=one[2*sz/3-1]+ext;i<=n-1;i++){\n            if(s3.length()>0 || v[i])   s3+=to_string(v[i]);\n        }\n        //All 3 Numbers in vector v :-\n        // num1={0,one[sz/3-1]+ext-1};\n        // num2={one[sz/3-1]+ext,one[2*sz/3-1]+ext-1}\n        // num3={one[2*sz/3-1]+ext,n-1};\n        if(s1==s2 && s2==s3)    return {one[sz/3-1]+ext-1,one[2*sz/3-1]+ext};\n        return {-1,-1};\n    }\n};"
    },
    {
        "title": "Shortest Path with Alternating Colors",
        "algo_input": "You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.\n\nYou are given two arrays redEdges and blueEdges where:\n\n\n\tredEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and\n\tblueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.\n\n\nReturn an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []\nOutput: [0,1,-1]\n\n\nExample 2:\n\nInput: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]\nOutput: [0,1,-1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\t0 &lt;= redEdges.length,&nbsp;blueEdges.length &lt;= 400\n\tredEdges[i].length == blueEdges[j].length == 2\n\t0 &lt;= ai, bi, uj, vj &lt; n\n\n",
        "solution_py": "class Solution:\n    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n        g = [[[] for _ in range(2)] for _ in range(n)]\n        \n        for i,j in redEdges:\n            g[i][0] += [j]\n        for i,j in blueEdges:\n            g[i][1] += [j]\n        distance = [float(\"inf\") for _ in range(n)]\n        distance[0] = 0\n        q = queue.Queue()\n        q.put((0,0,False))\n        q.put((0,0,True))\n        \n        redS = set([0])\n        blueS = set([0])\n        while not q.empty():\n            node,dist,red = q.get()\n            if red:\n                neighbours = g[node][0]\n                redS.add(node)\n                curr = blueS\n            else:\n                neighbours = g[node][1]\n                blueS.add(node)\n                curr = redS\n            for neighbour in neighbours:\n                if dist + 1 < distance[neighbour]:\n                    distance[neighbour] = dist + 1\n                    q.put((neighbour,dist + 1,not red))\n                if not (neighbour in curr):\n                    q.put((neighbour,dist + 1,not red))\n        for i in range(n):\n            if distance[i] == float(\"inf\"):\n                distance[i] = -1\n        return distance\n            ",
        "solution_js": "const RED = \"red\";\nconst BLUE = \"blue\";\n\nfunction mapAllEdges(edges) {\n    const map = new Map();\n    for(let edge of edges) {\n        if(!map.has(edge[0])) {\n            map.set(edge[0], []);\n        }\n        map.get(edge[0]).push(edge[1])\n    }\n    return map;\n}\n\nfunction bfs(color, redNodeMap, blueNodeMap, result) {\n    const queue = [0];\n    let length = 0;\n    let currentColor = color;\n    while(queue.length > 0) {\n        const size = queue.length;\n        for(let i = 0; i < size; i++) {\n            const node = queue.shift();\n            if(result[node] === -1 || length < result[node] ) {\n                result[node] = length;\n            }\n            const map = RED === currentColor ? redNodeMap : blueNodeMap;\n            if(map.has(node)) {\n                const edges = map.get(node);\n                map.delete(node);\n                queue.push(...edges)\n            }\n        }\n        length++;\n        currentColor = RED === currentColor ? BLUE : RED;\n    }\n    return result;\n}\n\nfunction shortestPath(redEdges, blueEdges, color, result) {\n    const redNodeMap = mapAllEdges(redEdges);\n    const blueNodeMap = mapAllEdges(blueEdges);\n    bfs(color, redNodeMap, blueNodeMap, result);\n}\n\n/**\n * @param {number} n\n * @param {number[][]} redEdges\n * @param {number[][]} blueEdges\n * @return {number[]}\n */\nvar shortestAlternatingPaths = function(n, redEdges, blueEdges) {\n    const result = new Array(n).fill(-1);\n    shortestPath(redEdges, blueEdges, RED, result);\n    shortestPath(redEdges, blueEdges, BLUE, result);\n    return result\n};",
        "solution_java": "class Solution {\n    // g1-> graph with red edges\n    // g2-> graph with blue edges\n    List<Integer> g1[], g2[];\n    int[] dist1, dist2, ans;\n    int MX = (int) 2e9;\n\n    public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {\n        dist1 = new int[n];\n        dist2 = new int[n];\n        g1=new ArrayList[n];\n        g2=new ArrayList[n];\n        ans=new int[n];\n        for (int i=0;i<n;i++){\n            g1[i]=new ArrayList<>();\n            g2[i]=new ArrayList<>();\n            dist1[i]=MX;\n            dist2[i]=MX;\n            ans[i]=MX;\n        }\n        for (int i=0;i<redEdges.length;i++){\n            int u=redEdges[i][0];\n            int v=redEdges[i][1];\n            g1[u].add(v);\n        }\n        for (int i=0;i<blueEdges.length;i++){\n            int u=blueEdges[i][0];\n            int v=blueEdges[i][1];\n            g2[u].add(v);\n        }\n        dist1[0]=0;\n        dist2[0]=0;\n        dfs(0,true);\n        dfs(0,false);\n        for (int i=0;i<n;i++){\n            ans[i]=Math.min(dist1[i], dist2[i]);\n            if (ans[i]==MX) ans[i]=-1;\n        }\n        return ans;\n    }\n    public void dfs(int u, boolean flag) {\n        if (flag) {\n            for (int v: g1[u]) {\n                if (dist1[v]>dist2[u]+1){\n                    dist1[v]=dist2[u]+1;\n                    dfs(v,!flag);\n                }\n            }\n        } else {\n            for (int v: g2[u]) {\n                if (dist2[v]>dist1[u]+1){\n                    dist2[v]=dist1[u]+1;\n                    dfs(v,!flag);\n                }\n            }\n        }\n    }\n}",
        "solution_c": "#define red 1\n#define blue 2\nclass Solution {\npublic:\n    vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) {\n        vector<vector<pair<int,int>>> graph(n);\n        vector<vector<int>> visited(n, vector<int>(3, false));\n        for(int i = 0;i<redEdges.size();i++)\n        {\n            graph[redEdges[i][0]].push_back({redEdges[i][1], red});\n        }\n              \n        for(int i = 0;i<blueEdges.size();i++)\n        {\n            graph[blueEdges[i][0]].push_back({blueEdges[i][1], blue});\n        }\n        \n        queue<tuple<int, int,int>> q;\n        q.push({0, 0, 0});\n        \n        vector<int> res(n, INT_MAX);\n        \n        while(!q.empty())\n        {\n            auto top = q.front();\n            q.pop();\n            int parent = get<0>(top);\n            int step = get<1>(top);\n            int color = get<2> (top);\n            res[parent] = min(res[parent], step);\n            if(visited[parent][color]) continue;\n            visited[parent][color] = true;\n            for(auto child:graph[parent])\n            {\n                if(color == child.second) continue;\n                q.push(make_tuple(child.first, step+1, child.second));\n            }\n        }\n        for(int i = 0;i<res.size();i++)\n        {\n            if(res[i]==INT_MAX) res[i] = -1;\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Count of Matches in Tournament",
        "algo_input": "You are given an integer n, the number of teams in a tournament that has strange rules:\n\n\n\tIf the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.\n\tIf the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.\n\n\nReturn the number of matches played in the tournament until a winner is decided.\n\n&nbsp;\nExample 1:\n\nInput: n = 7\nOutput: 6\nExplanation: Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.\n\n\nExample 2:\n\nInput: n = 14\nOutput: 13\nExplanation: Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 200\n\n",
        "solution_py": "class Solution:\n\tdef numberOfMatches(self, n: int) -> int:\n\t\treturn n - 1",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar numberOfMatches = function(n) {\n    let matches = 0,current = n;\n    while(current > 1){\n        if(current % 2 === 0){\n            matches += current/2;\n            current = current/2\n        }else{\n            matches += (current-1)/2;\n            current = (current-1)/2 + 1 ;\n        }\n    }\n    return matches;\n};",
        "solution_java": "class Solution {\n    public int numberOfMatches(int n) {\n\t\t// This is the problem's base case; we know that if n == 1,\n\t\t// the number of matches played must be 0, since the last team left\n\t\t// can't play a match against themselves.\n        if (n == 1) return 0;\n        \n\t\t// We declare an int to hold our recursive solution.\n        int res;\n\t\t\n\t\t// We initialize res using a recursive call, reducing n \n\t\t// as described in the problem.\n        if (n % 2 == 0) {\n            res = numberOfMatches(n / 2);\n\t\t\t// After the recursive call is executed, we add the appropriate value to \n\t\t\t// our solution variable.\n            res += n / 2;\n        }\n        else {\n            res = numberOfMatches((n - 1) / 2 + 1);\n            res += (n - 1) / 2;\n        }\n        \n\t\t// Our initial call to numberOfMatches()\n\t\t// will return the total number of matches \n\t\t// added to res in each recursive call.\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numberOfMatches(int n) {\n        int count=0;\n        while(n>1)\n        { \n            if(n%2==0)\n            {\n           int a=n/2;\n           n=n/2;\n           count=count+a;}\n           else\n           {\n               int a=(n-1)/2;\n               n=a+1;\n               count=count+a;\n           }            \n        }\n        return count;\n    }\n};"
    },
    {
        "title": "Remove Duplicates from Sorted Array II",
        "algo_input": "Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.\n\nSince it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums&nbsp;should hold the final result. It does not matter what you leave beyond the first&nbsp;k&nbsp;elements.\n\nReturn k after placing the final result in the first k slots of nums.\n\nDo not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n\nCustom Judge:\n\nThe judge will test your solution with the following code:\n\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n\n\nIf all assertions pass, then your solution will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,1,2,2,3]\nOutput: 5, nums = [1,1,2,2,3,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\nExample 2:\n\nInput: nums = [0,0,1,1,1,1,2,3,3]\nOutput: 7, nums = [0,0,1,1,2,3,3,_,_]\nExplanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-104 &lt;= nums[i] &lt;= 104\n\tnums is sorted in non-decreasing order.\n\n",
        "solution_py": "class Solution(object):\n    def removeDuplicates(self, nums):\n        n=len(nums)\n        if n==2:\n            return 2\n        if n==0:\n            return 0\n        if n==1:\n            return 1\n        same=0\n        start=-1\n        end=-1\n        i=0\n        while i<n-1:\n            if nums[i]==nums[i+1] and same==0:\n                same=1\n                start=i+2\n                i+=1\n                continue\n            while i<n-1 and nums[i]==nums[i+1] and same==1:\n                end=i+1\n                i+=1\n            i+=1\n            if start!=-1 and end!=-1:\n                no_of_shifts=end-start+1\n                while i<n:\n                    nums[i-no_of_shifts]=nums[i]\n                    i+=1\n                n=n-no_of_shifts\n                i=start\n            start=-1\n            end=-1\n            same=0\n            \n        return n\n\t\t```",
        "solution_js": "var removeDuplicates = function(nums) {\n    let i = 0;\n    let count = 0;\n    for(let num of nums) {\n        (num == nums[i - 1]) ? count++ : count = 1;\n        if(i == 0 || (num >= nums[i - 1] && count <= 2)) nums[i++] = num;\n    }\n    return i;\n};",
        "solution_java": "class Solution {\n    public int removeDuplicates(int[] nums) {\n     int   index = 1;\n      int  count = 0;\n        for(int i = 1;i<nums.length;i++){\n            if(nums[i] == nums[i-1]){\n                count++;\n            }\n            else{\n                count = 0;\n            }\n\n            if(count <= 1){\n                nums[index] = nums[i];\n                index++;\n            }\n        }\n        return index;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n       int l = 1;\n        int last_selected = nums[0];\n        int count = 1;\n        int n = nums.size();\n        for(int i = 1;i<n;i++)\n        {\n            if(nums[i]!=last_selected){\n                count = 1;\n                last_selected = nums[i];\n                nums[l] = nums[i];\n                l++;\n            }\n            else if(count == 2){\n                continue;\n            }\n            else{\n                nums[l] = nums[i];\n                l++;\n                count++;\n            }\n        }\n        return (l);\n    }\n};"
    },
    {
        "title": "Find All Groups of Farmland",
        "algo_input": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.\n\nTo keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.\n\nland can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].\n\nReturn a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput: [[0,0,0,0],[1,1,2,2]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].\n\n\nExample 2:\n\nInput: land = [[1,1],[1,1]]\nOutput: [[0,0,1,1]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].\n\n\nExample 3:\n\nInput: land = [[0]]\nOutput: []\nExplanation:\nThere are no groups of farmland.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == land.length\n\tn == land[i].length\n\t1 &lt;= m, n &lt;= 300\n\tland consists of only 0's and 1's.\n\tGroups of farmland are rectangular in shape.\n\n",
        "solution_py": "class Solution:\n\n    def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n        n = len(land)\n        m = len(land[0])\n\n        groups = []\n        visited = set()\n\n        for y in range(n):\n            for x in range(m):\n                if land[y][x] == 0:\n                    continue\n\n                if (y, x) in visited:\n                    continue\n\n                q = collections.deque()\n                q.append((y, x))\n                visited.add((y, x))\n\n                while q:\n                    cy, cx = q.popleft()\n\n                    for dy, dx in ((0, 1), (1, 0)):\n                        if (cy + dy, cx + dx) in visited:\n                            continue\n\n                        if 0 <= cy + dy < n and 0 <= cx + dx < m:\n                            if land[cy + dy][cx + dx] == 1:\n                                q.append((cy + dy, cx + dx))\n                                visited.add((cy + dy, cx + dx))\n\n                groups.append([y, x, cy, cx])\n\n        return groups",
        "solution_js": "var findFarmland = function(land) {\n    let height = land.length;\n    let width = land[0].length;\n    let results = [];\n    let endRow = 0;\n    let endCol = 0;\n\n    let go = (i, j) => {\n        if (i < 0 || j < 0 || i >= height || j >= width || land[i][j] === 0) {\n            return;\n        }\n\n        endRow = Math.max(endRow, i);\n        endCol = Math.max(endCol, j);\n        land[i][j] = 0; // reset everything to 0\n\n        go(i + 1, j);\n        go(i - 1, j);\n        go(i, j + 1);\n        go(i, j - 1);\n    }\n\n    for (let i = 0; i < height; i++) {\n        for (let j = 0; j < width; j++) {\n            if (land[i][j] === 1) {\n                endRow = 0;\n                endCol = 0;\n                go(i, j);\n                results.push([i, j, endRow, endCol]);\n            }\n        }\n    }\n\n    return results;\n};",
        "solution_java": "class Solution {\n    int[] arr;\n    public int[][] findFarmland(int[][] land) {\n        List<int[]> res = new ArrayList<>();\n        for(int i=0;i<land.length;i++)\n            for(int j=0;j<land[0].length;j++){\n                if(land[i][j] == 1){\n                    arr = new int[]{i,j,0,0};\n                    dfs(land,i,j);\n                    res.add(arr);\n                }\n            }\n        return res.stream().map(i->i).toArray(int[][] :: new);\n    }\n    public void dfs(int[][] land, int i,int j){\n        if(i<0 || j<0 || i>=land.length || j>= land[0].length || land[i][j] == 0) return;\n        arr[2] = Math.max(i,arr[2]);\n        arr[3] = Math.max(j,arr[3]);\n        land[i][j] = 0;\n        dfs(land,i-1,j);\n        dfs(land,i,j+1);\n        dfs(land,i+1,j);\n        dfs(land,i,j-1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> nbrs = {{0,1},{1,0},{-1,0},{0,-1}};\n    pair<int, int> dfs(vector<vector<int>> &land, int i, int j, vector<vector<bool>> &visited) {\n        visited[i][j] = true;\n        pair<int, int> res = make_pair(i, j);\n        for(auto &nbr: nbrs) {\n            int x = i + nbr[0];\n            int y = j + nbr[1];\n            if(x < 0 || y < 0 || x >= land.size() || y >= land[0].size() || visited[x][y] || land[x][y] != 1)\n                continue;\n            pair<int, int> ans = dfs(land, x, y, visited);\n            res.first = max(res.first, ans.first);\n            res.second = max(res.second, ans.second);\n        }\n        return res;\n    }\n    vector<vector<int>> findFarmland(vector<vector<int>>& land) {\n        int m = land.size();\n        int n = land[0].size();\n        vector<vector<bool>> visited(m, vector<bool>(n, false));\n        vector<vector<int>> ans;\n        for(int i = 0; i < m; i++) {\n            for(int j = 0; j < n; j++) {\n                if(!visited[i][j] && land[i][j] == 1) {\n                    pair<int, int> p = dfs(land, i, j, visited);\n                    vector<int> res;\n                    res.push_back(i);\n                    res.push_back(j);\n                    res.push_back(p.first);\n                    res.push_back(p.second);\n                    ans.push_back(res);\n                    cout << 1 << endl;\n                }\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Points You Can Obtain from Cards",
        "algo_input": "There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.\n\nIn one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\n\nYour score is the sum of the points of the cards you have taken.\n\nGiven the integer array cardPoints and the integer k, return the maximum score you can obtain.\n\n&nbsp;\nExample 1:\n\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\n\n\nExample 2:\n\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\n\n\nExample 3:\n\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= cardPoints.length &lt;= 105\n\t1 &lt;= cardPoints[i] &lt;= 104\n\t1 &lt;= k &lt;= cardPoints.length\n\n",
        "solution_py": "class Solution:\n    def maxScore(self, cardPoints: List[int], k: int) -> int:\n        total_cards = len(cardPoints)\n        total = sum(cardPoints)\n        window_size = total_cards - k\n        window_total = 0\n\n        if total_cards == k:\n            return total\n\n        for i in range(total_cards - k):\n            window_total += cardPoints[i]\n        max_diff = total - window_total\n        for i in range((total_cards - k), total_cards):\n            window_total += cardPoints[i]\n            window_total -= cardPoints[i-window_size]\n            if total - window_total > max_diff:\n                max_diff = total - window_total\n        return max_diff",
        "solution_js": "/**\n * @param {number[]} cardPoints\n * @param {number} k\n * @return {number}\n */\n\n// Obtaining k cards from the beginning or end of the row for the largest sum, meaning leaving the\n// array with n-k adjacent cards with the min sum\n// therefore, this transform the problem to finding the minSum of subarray of length n-k\n// we use slide window to calculate the minSubArraySum\nvar maxScore = function(cardPoints, k) {\n    const n = cardPoints.length, d = n-k // d is the window length\n    let sum = 0\n    for (let i = 0; i < d; i++) {\n        sum += cardPoints[i]\n    }\n    let minWindowSum = sum, totalSum = sum\n    console.log(sum)\n    for (let i = d; i < n; i++) {\n        // the sum of the next window will the the sum of previous window + the next card (the end card of the next window) - the beginning card of the previous window\n        sum += cardPoints[i] - cardPoints[i-d]\n        minWindowSum = Math.min(minWindowSum, sum)\n        totalSum += cardPoints[i]\n    }\n    // the ans will be the sum of all cards - the sum of min subArray\n    return totalSum - minWindowSum\n};",
        "solution_java": "class Solution {\n    public int maxScore(int[] cardPoints, int k) {\n        int n = cardPoints.length;\n        int[] totalSum = new int[n];\n        int sum = 0;\n        for(int i=0;i<n;i++){\n            sum += cardPoints[i];\n            totalSum[i] = sum;\n        }\n        if(n==k){\n            return sum;\n        }\n        int score =0;\n        for(int i=0;i<=k;i++){\n            int j = i+n-k-1;\n            int subsum = 0;\n            if(i==0){\n                subsum = totalSum[j];\n            }\n            else{\n                subsum = totalSum[j]-totalSum[i-1];\n            }\n\n            score = Math.max(score,sum-subsum);\n        }\n        return score;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxScore(vector<int>& cardPoints, int k) {\n\n        int max_s = 0, left =0, right = 0, n = cardPoints.size();\n\n        //getting sum of k right elements\n        for(int i = 0; i<k; i++){\n            right += cardPoints[n-i-1];\n        }\n\n        // Assumming max as sum of k right elements\n        max_s = right;\n        for(int i = 0; i<k; i++){\n            left += cardPoints[i];\n            right -= cardPoints[n-k+i];\n            max_s = max(max_s, left+right);\n        }\n        return max_s;\n    }\n};"
    },
    {
        "title": "Max Increase to Keep City Skyline",
        "algo_input": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.\n\nA city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.\n\nWe are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.\n\nReturn the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\nOutput: 35\nExplanation: The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n            [7, 4, 7, 7],\n            [9, 4, 8, 7],\n            [3, 3, 3, 3] ]\n\n\nExample 2:\n\nInput: grid = [[0,0,0],[0,0,0],[0,0,0]]\nOutput: 0\nExplanation: Increasing the height of any building will result in the skyline changing.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[r].length\n\t2 &lt;= n &lt;= 50\n\t0 &lt;= grid[r][c] &lt;= 100\n\n",
        "solution_py": "class Solution:\n\tdef maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n\t\tmxr = [max(i) for i in grid]\n\t\tmxc = [0 for _ in range(len(grid[0]))]\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[0])):\n\t\t\t\tmxc[j] = max(grid[i][j],mxc[j])\n\t\tans =0 \n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid)):\n\t\t\t\tans+=(min(mxr[i],mxc[j]) - grid[i][j]) \n\t\treturn ans",
        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar maxIncreaseKeepingSkyline = function(grid) {\n    let n = grid.length;\n    let sum = 0;\n    let cache = [];\n\n    for (let i = 0; i < n; i++) {\n        const rowMax = Math.max(...grid[i]);\n\n        for (let j = 0; j < n; j++) {\n            let colMax = cache[j];\n\n            if (!colMax) {\n                let max = Number.MIN_SAFE_INTEGER;\n                for (let c = 0; c < n; c++) {\n                    max = Math.max(max, grid[c][j]);\n                }\n                cache[j] = max;\n                colMax = max;\n            }\n\n            sum += Math.min(rowMax, colMax) - grid[i][j];\n        }\n    }\n\n    return sum;\n};",
        "solution_java": "class Solution {\n    public int maxIncreaseKeepingSkyline(int[][] grid) {\n        int n = grid.length;\n        int[] row = new int[n];\n        int[] col = new int[n];\n        int ans = 0;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                row[i] = Math.max(row[i],grid[i][j]);\n                col[i] = Math.max(col[i],grid[j][i]);\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                ans += Math.min(row[i],col[j])-grid[i][j];\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n        int n=grid.size();\n        //get max for every Column\n        vector<int> maxfromcol(n,INT_MIN);\n        for(int j=0;j<n;j++){\n            for(int i=0;i<n;i++){\n                maxfromcol[j]=max(maxfromcol[j],grid[i][j]);\n            }\n        }\n        int cost=0;\n        for(int i=0;i<n;i++){\n            //find maximum in ithrow\n            int mx=INT_MIN;\n            for(int j=0;j<n;j++){\n                mx=max(mx,grid[i][j]);   \n            }\n            cout<<mx<<endl;\n            //update every element in ith row with min of max of ith row and max of jth col\n            for(int j=0;j<n;j++){\n                int temp=grid[i][j];\n                grid[i][j]=min(mx,maxfromcol[j]);\n                cost+=grid[i][j]-temp;\n            }\n        }\n        return cost;\n    }\n};"
    },
    {
        "title": "Remove Comments",
        "algo_input": "Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\\n'.\n\nIn C++, there are two types of comments, line comments, and block comments.\n\n\n\tThe string \"//\" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.\n\tThe string \"/*\" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of \"*/\" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string \"/*/\" does not yet end the block comment, as the ending would be overlapping the beginning.\n\n\nThe first effective comment takes precedence over others.\n\n\n\tFor example, if the string \"//\" occurs in a block comment, it is ignored.\n\tSimilarly, if the string \"/*\" occurs in a line or block comment, it is also ignored.\n\n\nIf a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.\n\nThere will be no control characters, single quote, or double quote characters.\n\n\n\tFor example, source = \"string s = \"/* Not a comment. */\";\" will not be a test case.\n\n\nAlso, nothing else such as defines or macros will interfere with the comments.\n\nIt is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment.\n\nFinally, implicit newline characters can be deleted by block comments. Please see the examples below for details.\n\nAfter removing the comments from the source code, return the source code in the same format.\n\n&nbsp;\nExample 1:\n\nInput: source = [\"/*Test program */\", \"int main()\", \"{ \", \"  // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \"   multiline  \", \"   comment for \", \"   testing */\", \"a = b + c;\", \"}\"]\nOutput: [\"int main()\",\"{ \",\"  \",\"int a, b, c;\",\"a = b + c;\",\"}\"]\nExplanation: The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n  // variable declaration \nint a, b, c;\n/* This is a test\n   multiline  \n   comment for \n   testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n  \nint a, b, c;\na = b + c;\n}\n\n\nExample 2:\n\nInput: source = [\"a/*comment\", \"line\", \"more_comment*/b\"]\nOutput: [\"ab\"]\nExplanation: The original source string is \"a/*comment\\nline\\nmore_comment*/b\", where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string \"ab\", which when delimited by newline characters becomes [\"ab\"].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= source.length &lt;= 100\n\t0 &lt;= source[i].length &lt;= 80\n\tsource[i] consists of printable ASCII characters.\n\tEvery open block comment is eventually closed.\n\tThere are no single-quote or&nbsp;double-quote in the input.\n\n",
        "solution_py": "class Solution:\n    def removeComments(self, source: List[str]) -> List[str]:\n        ans, inComment = [], False\n        new_str = \"\"\n        for c in source:\n            if not inComment: new_str = \"\"\n            i, n = 0, len(c)\n            # inComment, we find */\n            while i < n:\n                if inComment:\n                    if c[i:i + 2] == '*/' and i + 1 < n:\n                        i += 2\n                        inComment = False\n                        continue\n                    i += 1\n                # not in Comment, we find /* // and common character\n                else:\n                    if c[i:i + 2] == '/*' and i + 1 < n:\n                        i += 2\n                        inComment = True\n                        continue\n                    if c[i:i + 2] == '//' and i + 1 < n:\n                        break\n                    new_str += c[i]\n                    i += 1\n            if new_str and not inComment:\n                ans.append(new_str)\n                    \n\n        return ans",
        "solution_js": "var removeComments = function(source) {\n    let result = [];\n    let multi_line_comment = false;\n    let str = \"\";\n\n    source.forEach(line => {\n        for(let idx=0; idx < line.length; ++idx) {\n            // if /* is not ongoing, check for start of a comment or not\n            if(!multi_line_comment) {\n                // if comment is //, ignore the rest of the line\n                if(line[idx] + line[idx+1] === '//') {\n                    break;\n                }\n                // if comment if /*, set multi-line flag and move to next index\n                else if(line[idx] + line[idx+1] === '/*') {\n                    multi_line_comment = true;\n                    ++idx;\n                }\n                // if not a comment start, add to string to be added to result\n                else {\n                    str += line[idx];\n                }\n            }\n            // if /* comment is ongoing\n            else {\n                // if closing comment */ is encountered, set multi-line flag off and move to next index\n                if(line[idx] + line[idx+1] === '*/') {\n                    multi_line_comment = false;\n                    ++idx;\n                }\n            }\n        }\n        // if /* comment is not ongoing and str is not empty, add to result as one code line\n        if(str.length && !multi_line_comment) {\n            result.push(str);\n            str = \"\"; //reset the str\n        }\n    })\n    return result;\n}",
        "solution_java": "class Solution {\n    public List<String> removeComments(String[] source) {\n        boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. \n\t\t//It is initally set to false since we haven't read anything until now. \n\n\n        List<String> result = new ArrayList<String>();\n        StringBuilder builder = new StringBuilder();\n        \n        //Read every line from the source input. \n        \n        for(String line: source){\n// Each time we move on to reading a new line, we check if it is a part of a block comment. \n//If it is already part of a block comment, it means we should skip the implicit newline characters as mentioned in the problem description. \n//For example if Line 1 was  \"int a /*Block comment Started\" and Line 2 was \"Block comment ends here */ b;\", and Line 3 was \"int c;\" \n//we want our output to be \"int ab\", \"int c\" instead of \"int a\", \"b;\", \"int c;\" \n            if(!blockActive){ \n                builder = new StringBuilder();\n            }\n            for(int i=0; i<line.length(); i++){ //Read every character of line\n                char c = line.charAt(i);\n                if(!blockActive){ //If we aren't currently in a block\n                    \n                    if(c=='/'){ //We check if we encounter the start of a regular comment\n                        //If so, then we need to check if the next character makes it a regular comment, a block comment, or neither of those two. \n                        \n                        if(i<line.length()-1 && line.charAt(i+1)=='/'){ //Checking if it's a regular comment\n                            break; //If it's a regular comment, we can simply skip everything else \n\t\t\t\t\t\t\t//until the end of the line, so we break from the loop and move on to the next line.\n                        } else if(i<line.length()-1 && line.charAt(i+1)=='*'){ //Or a block comment\n                            i++; //Since we verified it's a block comment, we simply increment i so that we don't re-read the '*' again, \n\t\t\t\t\t\t\t//and mark that we are now part of a block comment. \n                            blockActive = true;\n                        } else{ // If the second character is neither a / or *, it indicates that a first character must be a valid operator \n\t\t\t\t\t\t//(probably a mathematical operator such as multiplication or division, and not part of any comment, \n\t\t\t\t\t\t//so simply append it to the builder)\n                            builder.append(c);\n                        }\n                    } else  { //Append all other characters directly to the builder. \n                        builder.append(c);\n                    }\n                } else {\n                    //We skip all other characters in a block comment, and check for the closing block comment. \n\t\t\t\t\t//Once we find it, we mark the blockActive variable as false to indicate that it isn't part of the block anymore.  \n                    if(c=='*'){\n                        if(i<line.length()-1 && line.charAt(i+1)=='/'){\n                              blockActive = false;  \n                              i++;\n                        }\n                    }\n                } \n            }\n            //We append to the result when we aren't part of a block any more, and the builder contains 1 or more characters. \n            if(!blockActive && builder.length()!=0){\n                result.add(builder.toString());\n            }\n            \n        }\n        \n        return result;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> removeComments(vector<string>& source) {\n        bool commentStart = false;\n        vector<string> res;\n        \n        bool multiComment = false; // are we having a multi-line comment?\n        for (string &eachS : source) {\n            if (!multiComment) {\n                res.emplace_back();\n            }\n            for (int i = 0; i < eachS.size(); i++) {\n                if (!multiComment && eachS[i] == '/') {\n                    i++;\n                    if (eachS[i] == '/') {\n                        break;\n                    } else if (eachS[i] == '*') {\n                        multiComment = true;\n                    } else {\n                        res.back() += '/';\n                        res.back() += eachS[i];\n                    }\n                } else if (multiComment && eachS[i] == '*') {\n                    if (i + 1 < eachS.size() && eachS[i + 1] == '/') {\n                        i++;\n                        multiComment = false;\n                    }\n                } else {\n                    if (!multiComment) {\n                        res.back() += eachS[i];\n                    }\n                }\n            }\n            if (!multiComment && res.back().empty()) {\n                res.pop_back();\n            } \n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Parse Lisp Expression",
        "algo_input": "You are given a string expression representing a Lisp-like expression to return the integer value of.\n\nThe syntax for these expressions is given as follows.\n\n\n\tAn expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.\n\t(An integer could be positive or negative.)\n\tA let expression takes the form \"(let v1 e1 v2 e2 ... vn en expr)\", where let is always the string \"let\", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.\n\tAn add expression takes the form \"(add e1 e2)\" where add is always the string \"add\", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.\n\tA mult expression takes the form \"(mult e1 e2)\" where mult is always the string \"mult\", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.\n\tFor this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\", \"let\", and \"mult\" are protected and will never be used as variable names.\n\tFinally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.\n\n\n&nbsp;\nExample 1:\n\nInput: expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput: 14\nExplanation: In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.\n\n\nExample 2:\n\nInput: expression = \"(let x 3 x 2 x)\"\nOutput: 2\nExplanation: Assignment in let statements is processed sequentially.\n\n\nExample 3:\n\nInput: expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput: 5\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= expression.length &lt;= 2000\n\tThere are no leading or trailing spaces in expression.\n\tAll tokens are separated by a single space in expression.\n\tThe answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\n\tThe expression is guaranteed to be legal and evaluate to an integer.\n\n",
        "solution_py": "class Solution:\n    def evaluate(self, expression: str) -> int:\n        loc = {}\n        stack = []\n        for i, x in enumerate(expression): \n            if x == \"(\": stack.append(i)\n            elif x == \")\": loc[stack.pop()] = i\n        \n        def fn(lo, hi, mp): \n            \"\"\"Return value of given expression.\"\"\"\n            if expression[lo] == \"(\": return fn(lo+1, hi-1, mp)\n            i = lo\n            vals = []\n            while i < hi: \n                if expression[i:i+3] in (\"let\", \"add\"): \n                    op = expression[i:i+3]\n                    i += 3\n                elif expression[i:i+4] == \"mult\": \n                    op = \"mult\"\n                    i += 4\n                elif expression[i].isalpha(): \n                    x = \"\"\n                    while i < hi and expression[i].isalnum(): \n                        x += expression[i]\n                        i += 1\n                    if op in (\"add\", \"mult\"): vals.append(mp[x])\n                elif expression[i].isdigit() or expression[i] == \"-\": \n                    v = \"\"\n                    while i < hi and (expression[i].isdigit() or expression[i] == \"-\"): \n                        v += expression[i]\n                        i += 1\n                    if op == \"let\": mp[x] = int(v)\n                    else: vals.append(int(v))\n                elif expression[i] == \"(\": \n                    v = fn(i+1, loc[i], mp.copy())\n                    i = loc[i] + 1\n                    if op == \"let\": mp[x] = v\n                    else: vals.append(v)\n                else: i += 1\n            if op == \"let\": return int(v)\n            elif op == \"add\": return sum(vals)\n            else: return reduce(mul, vals)\n            \n        return fn(0, len(expression), {})",
        "solution_js": "/**\n * @param {string} expression\n * @return {number}\n */\nvar evaluate = function(expression) {\n    return helper(expression);\n};\n\nconst helper = (expr, map = {}) => {\n    if (expr[0] !== '(')\n        return /[0-9]|-/.test(expr[0]) ? +expr : map[expr];\n\n    map = Object.assign({}, map);\n    const start = expr[1] === 'm' ? 6 : 5;\n    const tokens = parse(expr.slice(start, expr.length - 1));\n\n    if (expr.startsWith('(m')) return helper(tokens[0], map) * helper(tokens[1], map);\n    if (expr.startsWith('(a')) return helper(tokens[0], map) + helper(tokens[1], map);\n\n    for (let i = 0; i < tokens.length - 2; i += 2)\n        map[tokens[i]] = helper(tokens[i + 1], map);\n\n    return helper(tokens.at(-1), map);\n}\n\nconst parse = expr => {\n    const tokens = [];\n    let [builder, par] = ['', 0];\n\n    for (let ch of expr) {\n        if (ch === '(') par++;\n        if (ch === ')') par--;\n        if (!par && ch === ' ') {\n            tokens.push(builder);\n            builder = '';\n        }\n        else builder += ch;\n    }\n\n    return builder ? [...tokens, builder] : tokens;\n}",
        "solution_java": "class Solution {\n    \n    String expression;\n    int index;\n    HashMap<String,Deque<Integer>> scope; \n    //variable may be assigned many times, we use the peek value \n    \n    public int evaluate(String expression) {\n        this.expression=expression;\n        index=0;\n        scope=new HashMap<>();\n        return evaluate();\n    }\n    \n    private int evaluate(){\n        \n        if(expression.charAt(index)=='('){\n            //this is an expression\n            index++; //skip '('\n            char begin=expression.charAt(index);\n            int ret;\n            if(begin=='l'){\n                //let\n                index += 4; //skip let and a blank space\n                ArrayList<String> vars=new ArrayList<>();\n                while(true){\n                    if(!Character.isLowerCase(expression.charAt(index))){\n                        ret=evaluate();\n                        break;\n                    }\n                    String var=parseVar();\n                    if(expression.charAt(index)==')'){\n                        ret=scope.get(var).peek();\n                        break;\n                    }\n                    vars.add(var);\n                    index++;\n                    int e=evaluate();\n                    scope.putIfAbsent(var, new LinkedList<>());\n                    scope.get(var).push(e); //assign a new value\n                    index++;\n                }\n                for (String var : vars) {\n                    scope.get(var).pop(); // remove all values of this scope\n                }\n\n            } else if(begin=='a') {\n                //add\n                index += 4;\n                int v1 = evaluate();\n                index++;\n                int v2 = evaluate();\n                ret = v1+v2;\n            } else {\n                //multi\n                index += 5;\n                int v1 = evaluate();\n                index++;\n                int v2 = evaluate();\n                ret =  v1*v2;\n            }\n            index++; // skip ')'\n            return ret;\n        } else {\n            //this is not a expression, this is an integer or a variable\n            if(Character.isLowerCase(expression.charAt(index))){\n\t\t\t\t//this is a variable, the current value is peek value\n                String var=parseVar();\n                return scope.get(var).peek();\n            } else {\n\t\t\t\t//this is an integer\n                return parseInt();\n            }\n        }\n    }\n    \n    //read an integer\n    private int parseInt(){\n        boolean negative=false;\n        if(expression.charAt(index)=='-'){\n            negative=true;\n            index++;\n        }\n        int ret=0;\n        while(Character.isDigit(expression.charAt(index))){\n            ret*=10;\n            ret+=expression.charAt(index)-'0';\n            index++;\n        }\n        if(negative) return -ret;\n        return ret;\n    }\n    \n    //read a variable\n    private String parseVar(){\n        StringBuilder sb=new StringBuilder();\n        char c=expression.charAt(index);\n        while(c!=' ' && c!=')'){\n            sb.append(c);\n            c=expression.charAt(++index);\n        }\n        return sb.toString();\n    }\n}",
        "solution_c": "class Context {\n  unordered_map<string_view, int> _map;\n  const Context *_parent{};\n  public:\n  Context(const Context *parent) : _parent{parent}\n  {\n    ;\n  }\n  const Context* Parent() const { return _parent; }\n  int GetValue(const string_view &key) const\n  {\n    auto it = _map.find(key);\n    if (it != _map.end()) return it->second;\n    if (_parent) return _parent->GetValue(key);\n    assert(0);\n    return numeric_limits<int>::min();\n  }\n  void AddValue(const string_view &key, int val) {\n    auto [it, isInserted] = _map.emplace(key, val);\n    if (!isInserted) it->second = val;\n  }\n};\nclass Solution {\n  string_view symbol(string_view &expr) {\n    string_view ret;\n    if (expr.empty() || !isalpha(expr[0])) {\n      return ret;\n    }\n    auto pos = expr.find_first_of(\" )\");\n    assert(pos != string_view::npos);\n    ret = expr.substr(0, pos);\n    expr.remove_prefix(pos);\n    return ret;\n  }\n  int evaluate(string_view &expr, Context *context) {\n    assert(!expr.empty());\n    if (expr[0] == '(') {\n      assert(expr.length() >= 4);\n      if (expr.substr(0, 4) == \"(add\") {\n        assert(expr.length() > 4);\n        expr.remove_prefix(4);\n        assert(!expr.empty() && expr[0] == ' ');\n        expr.remove_prefix(1);\n        int l = evaluate(expr, context);\n        assert(!expr.empty() && expr[0] == ' ');\n        expr.remove_prefix(1);\n        int r = evaluate(expr, context);\n        assert(!expr.empty() && expr[0] == ')');\n        expr.remove_prefix(1);\n        return l + r;\n      }\n      if (expr.substr(0, 4) == \"(mul\") {\n        assert(expr.length() > 5);\n        expr.remove_prefix(5);\n        assert(!expr.empty() && expr[0] == ' ');\n        expr.remove_prefix(1);\n        int l = evaluate(expr, context);\n        assert(!expr.empty() && expr[0] == ' ');\n        expr.remove_prefix(1);\n        int r = evaluate(expr, context);\n        assert(!expr.empty() && expr[0] == ')');\n        expr.remove_prefix(1);\n        return l * r;\n      }\n      if (expr.substr(0, 4) == \"(let\") {\n        assert(expr.length() > 4);\n        expr.remove_prefix(4);\n        Context nc(context);\n        while (1) {\n          assert(!expr.empty() && expr[0] == ' ');\n          expr.remove_prefix(1);\n          string_view sym = symbol(expr);\n          assert(!expr.empty());\n          if (sym.empty() || expr[0] == ')') {\n            int ret{};\n            if (sym.empty()) {\n              ret = evaluate(expr, &nc);\n            } else {\n              ret = nc.GetValue(sym);\n            }\n            assert(!expr.empty() && expr[0] == ')');\n            expr.remove_prefix(1);\n            return ret;\n          }\n          assert(!expr.empty() && expr[0] == ' ');\n          expr.remove_prefix(1);\n          int value = evaluate(expr, &nc);\n          nc.AddValue(sym, value);\n        }\n        assert(0);\n      }\n    } \n    if (isdigit(expr[0]) || expr[0] == '-') {\n      auto pos = expr.find_first_not_of(\"-0123456789\");\n      auto len = min(expr.length(), pos);\n      int num;\n      if (auto [ptr, ec] = from_chars(expr.data(), expr.data()+len, num); ec == errc()) {\n        expr.remove_prefix(len);\n      } else {\n        assert(0);\n      }\n      return num;\n    }\n    if (isalpha(expr[0])) {\n      string_view sym = symbol(expr);\n      assert(!expr.empty() && (expr[0] == ' ' || expr[0] == ')'));\n      return context->GetValue(sym);\n    }\n    assert(0);\n    return numeric_limits<int>::min();\n  }\npublic:\n    int evaluate(string expression) {\n      string_view expr(expression);\n      Context context(nullptr);\n      return evaluate(expr, &context);\n    }\n};"
    },
    {
        "title": "Longest Nice Substring",
        "algo_input": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not.\n\nGiven a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"YazaAay\"\nOutput: \"aAa\"\nExplanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.\n\n\nExample 2:\n\nInput: s = \"Bb\"\nOutput: \"Bb\"\nExplanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n\n\nExample 3:\n\nInput: s = \"c\"\nOutput: \"\"\nExplanation: There are no nice substrings.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of uppercase and lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def longestNiceSubstring(self, s: str) -> str:\n        def divcon(s):\n\t\t    # string with length 1 or less arent considered nice\n            if len(s) < 2:\n                return \"\"\n            \n            pivot = []\n            # get every character that is not nice\n            for i, ch in enumerate(s):\n                if ch.isupper() and ch.lower() not in s:\n                    pivot.append(i)\n                if ch.islower() and ch.upper() not in s:\n                    pivot.append(i)\n\t\t\t# if no such character return the string\n            if not pivot:\n                return s\n\t\t\t# divide the string in half excluding the char that makes the string not nice\n            else:\n                mid = (len(pivot)) // 2\n                return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)\n        \n        return divcon(s)",
        "solution_js": "const swapCase = (str) => str.split('').map((c) => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()).join('');\n\nvar longestNiceSubstring = function(s) {\n    let ans = \"\";\n        for (let i = 0; i < s.length; i++) {\n            for (let ii = i + 1; ii < s.length + 1; ii++) {\n                let substring = s.slice(i, ii); // we take a substring\n\n                let invertedCaseChars = [...substring].map(swapCase); // we create an array of chars from the substring and invert case of this chars\n                \n                if (invertedCaseChars.every(char => substring.includes(char))) { // we check that substring includes every case inverted char (see the illustration above)\n                    ans = substring.length > ans.length ? substring : ans; // we select the longest substring which satisfies our condition\n                }\n            } \n        }\n        return ans \n};",
        "solution_java": "class Solution {\n    public String longestNiceSubstring(String s) {\n        String result = \"\";\n        // take first index, go from 0 to length-1 of the string\n\t\tfor (int i = 0;i<s.length(); i++){        \n            // take second index, this should go up to the length of the string <=\n\t\t\tfor (int j = i+1;j<=s.length(); j++){\n                //get the substring for the index range from i to j\n\t\t\t\tString temp = s.substring(i, j);\n                // if length of the substring should be greater than 1\n\t\t\t\t// if the length should be greater that the previous computed result\n\t\t\t\t// if the substring is valid Nice String\n\t\t\t\t// then update the result with the current substring from range i and j\n\t\t\t\tif (temp.length() > 1 && result.length() < temp.length() && checkNice(temp)) result = temp;\n            }    \n        }\n        return result;\n    }\n    \n\t//validate Nice String check\n    public boolean checkNice(String temp){\n        //add substring to the set\n\t\tSet<Character> s = new HashSet<>();\n        for (char ch : temp.toCharArray()) s.add(ch);\n        \n\t\t// return false If you do not find both lower case and upper case in the sub string\n\t\t//for e.g 'aAa' substring added to set will have both a and A in the substring which is valid\n\t\t// 'azaA' substring will fail for 'z'\n\t\t// 'aaaaaaaa' will return \"\" as result\n\t\t//make sure that the substring contains both lower and upper case\n        for (char ch : s)\n            if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch))) return false;  \n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    string longestNiceSubstring(string s) {\n        int arr1[26]={};\n        int arr2[26]={};\n        if(s.length()<2)\n            return \"\";\n        for(char ch:s)\n        {\n            if(ch>='A' && ch<='Z')\n                arr1[(ch|32)-'a']++;\n            else\n                arr2[ch-'a']++;\n        }\n        vector<int> index;\n        index.push_back(-1);\n        for(int i=0;i<s.length();i++)\n        {\n            if((arr1[(s[i]|32)-'a']>=1 && arr2[(s[i]|32)-'a']==0) || (arr1[(s[i]|32)-'a']==0 && arr2[(s[i]|32)-'a']>=1))\n                index.push_back(i);\n        }\n        //index.push_back(2);\n        index.push_back(s.length());\n        if(index.size()==2)\n            return s;\n        string minn=\"\";\n        for(int i=0;i<index.size()-1;i++)\n        {\n            string temp = longestNiceSubstring(s.substr(index[i]+1,index[i+1]-index[i]-1));\n            minn = temp.length()>minn.length()?temp:minn;\n        }\n        return minn;\n    }\n};"
    },
    {
        "title": "Smallest Index With Equal Value",
        "algo_input": "Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.\n\nx mod y denotes the remainder when x is divided by y.\n\n&nbsp;\nExample 1:\n\nInput: nums = [0,1,2]\nOutput: 0\nExplanation: \ni=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.\n\n\nExample 2:\n\nInput: nums = [4,3,2,1]\nOutput: 2\nExplanation: \ni=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,6,7,8,9,0]\nOutput: -1\nExplanation: No index satisfies i mod 10 == nums[i].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 9\n\n",
        "solution_py": "class Solution:\n    def smallestEqual(self, nums: List[int]) -> int:\n        for idx, n in enumerate(nums):\n            if idx%10==n:\n                return idx\n        return -1 ",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar smallestEqual = function(nums) {\n    return nums.findIndex((n, i) => i % 10 === n)\n};",
        "solution_java": "class Solution {\n    public int smallestEqual(int[] nums) {\n        int index = 0;\n        for (int i = 0 ; i < nums.length; i++) {\n            if (index == nums[i]) {\n                return i;\n            }\n            if (++index== 10) {\n               index = 0;\n            }\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int smallestEqual(vector<int>& nums) {\n        int i = 0;\n        while (i < nums.size() && i % 10 != nums[i]) i++;\n        return i >= nums.size() ? -1 : i;\n    }\n};"
    },
    {
        "title": "The Skyline Problem",
        "algo_input": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.\n\nThe geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:\n\n\n\tlefti is the x coordinate of the left edge of the ith building.\n\trighti is the x coordinate of the right edge of the ith building.\n\theighti is the height of the ith building.\n\n\nYou may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\n\nThe skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.\n\nNote: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]\n\n&nbsp;\nExample 1:\n\nInput: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:\nFigure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n\n\nExample 2:\n\nInput: buildings = [[0,2,3],[2,5,3]]\nOutput: [[0,3],[5,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= buildings.length &lt;= 104\n\t0 &lt;= lefti &lt; righti &lt;= 231 - 1\n\t1 &lt;= heighti &lt;= 231 - 1\n\tbuildings is sorted by lefti in&nbsp;non-decreasing order.\n\n",
        "solution_py": "class Solution:\n    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n        d = collections.defaultdict(list)\n        \n        for i,(start, end, height) in enumerate(buildings):\n            d[start].append(height)\n            d[end].append(-height)\n            \n        l = list(d.keys())\n        l.sort()\n        \n        result = []\n        \n        active = []\n        \n        for key in l:\n            o = d[key]\n            o.sort(reverse=True)\n            for j in o:\n                if j > 0:\n                    if not result or not active:\n                        result.append([key, j])\n                        active.append(j)\n                    else:\n                        if j > active[-1]:\n                            result.append([key, j])\n                            active.append(j)\n                        else:\n                            active.insert(bisect_left(active, j), j)\n                else:\n                    idx = active.index(-j)\n                    if idx == len(active) - 1:\n                        active.pop()\n                        if active:\n                            result.append([key, active[-1]])\n                        else:\n                            result.append([key, 0])\n                    else:\n                        active.pop(idx)\n        \n        return result\n                        ",
        "solution_js": "var getSkyline = function(buildings) {\n    \n    let results = [];\n    \n    let points = [];\n    \n    for (let building of buildings) {\n        points.push([building[0],building[2]])\n        points.push([building[1],-building[2]])\n    }\n    \n    let heights = [];\n    \n    points.sort((a,b)=>(b[1]-a[1]))\n    points.sort((a,b)=>(a[0]-b[0]))\n    \n    for (let point of points) {\n        if(point[1] >0) {\n            heights.push(point[1])\n        }\n        else {\n            heights.splice(heights.indexOf(-point[1]),1)\n        }\n        let curHeight = (heights.length == 0?0:Math.max(...heights))\n        \n        if(results.length == 0 || results[results.length-1][1] != curHeight) results.push([point[0], curHeight]);\n    }\n    \n    \n    return results;\n};",
        "solution_java": "class height implements Comparable<height>{\n    int val = -1;\n    int pos = -1;\n    boolean isStart = false;\n    height(int a, int b, boolean c){\n        val = a;\n        pos = b;\n        isStart = c;\n    }\n    public int compareTo(height h){\n        if(this.pos != h.pos)\n            return this.pos-h.pos;\n        if(isStart)\n            return -1;\n        if(h.isStart)\n            return 1;\n        \n        return this.val-h.val;\n    }\n}\nclass Solution {\n    public List<List<Integer>> getSkyline(int[][] buildings) {\n        \n        PriorityQueue<height> mQ = new PriorityQueue<>();\n        int len = buildings.length;\n        for(int[] b: buildings) {\n            mQ.add(new height(b[2],b[0],true));\n            mQ.add(new height(b[2],b[1],false));\n        }\n        PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());\n        heap.add(0);\n        int prevHeight = 0;\n        List<List<Integer>> res = new ArrayList<>();\n        List<Integer> lst;\n        while(mQ.size()>0) {\n            height h = mQ.poll();\n            if(h.isStart){\n                heap.offer(h.val);\n            } else {\n                heap.remove(h.val);\n            }\n            \n            if(prevHeight != heap.peek()){\n                lst = new ArrayList<>();\n                lst.add(h.pos);\n                \n                if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){\n                    lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1)));\n                    res.remove(res.size()-1);\n                } else \n                    lst.add(heap.peek());\n                res.add(lst);\n                prevHeight = heap.peek();\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "/*\n1.mark the starting and ending pt of each building\n    -> let height of starting pt be negative and ending pt be positive   [2,4,10] -> [[2,-10],[4,10]]\n2.mark all consecutive building\n    ->store every pair of x and y in pair sort it acc to x\n3.get max y for all x values\n    ->use heap-->(multiset) to store all buildings, insert new height of building else erase buiding height\n4.remove pts of same height and store ans in results\n*/\nclass Solution {\npublic:\n    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {\n\t\t//step1\n        vector<pair<int,int>> coordinate;\n        for(auto building: buildings){\n            coordinate.push_back({building[0],-building[2]});\n            coordinate.push_back({building[1],building[2]});\n        }\n\t\t//step2\n        sort(coordinate.begin(), coordinate.end());\n        \n\t\t//step3\n        multiset<int,greater<int>> pq = {0};\n        vector<vector<int>> result;\n        int prev = 0;\n        for(auto p: coordinate){\n            if (p.second<0) pq.insert(-p.second);\n            else pq.erase(pq.find(p.second));\n            int cur=*pq.begin();\n            if (prev!=cur) {\n                result.push_back({p.first,cur});\n                prev=cur;\n            }\n        }\n        return result;\n    }\n};"
    },
    {
        "title": "Non-overlapping Intervals",
        "algo_input": "Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.\n\n&nbsp;\nExample 1:\n\nInput: intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput: 1\nExplanation: [1,3] can be removed and the rest of the intervals are non-overlapping.\n\n\nExample 2:\n\nInput: intervals = [[1,2],[1,2],[1,2]]\nOutput: 2\nExplanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.\n\n\nExample 3:\n\nInput: intervals = [[1,2],[2,3]]\nOutput: 0\nExplanation: You don't need to remove any of the intervals since they're already non-overlapping.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= intervals.length &lt;= 105\n\tintervals[i].length == 2\n\t-5 * 104 &lt;= starti &lt; endi &lt;= 5 * 104\n\n",
        "solution_py": "class Solution:\n    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1)\n        intervals.sort()\n        res = 0\n        prevEnd = intervals[0][1]\n\n        for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value\n            if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one\n                prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval\n            else: # Overlapping when new interval starts in between or from the previous one\n                res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2]\n                prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last\n\n        return res",
        "solution_js": "var eraseOverlapIntervals = function(intervals) {\n    // sort by end's small to big\n    intervals.sort((a, b) => a[1] - b[1]);\n    \n    let total = 1;\n    let maxEnd = intervals[0][1];\n    \n    for (let i = 1; i < intervals.length; i++) {\n        let [start, end] = intervals[i];\n        if (start >= maxEnd) {\n            total++;\n            maxEnd = end\n        }\n    }\n    \n    return intervals.length - total;\n};",
        "solution_java": "// |-------|\n//   |--|\n\n// |-------|\n//.   |-------|\n\n// |-------|\n//.           |-------|\n\nclass Solution {\n    public int eraseOverlapIntervals(int[][] intervals) {\n        Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n        \n        int start = intervals[0][0];\n        int end = intervals[0][1];\n        int res = 0;\n        \n        for (int i = 1; i < intervals.length; i++){\n            int[] interval = intervals[i];\n            \n            if(interval[0] >= start && interval[0] < end){\n                res++;\n                if (interval[1] >= end)\n                    continue;\n            }\n            start = interval[0];\n            end = interval[1];\n    }\n        \n        return res;\n    }\n}",
        "solution_c": "class Solution {\n        void solve(priority_queue <pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> &pq,int e,int &cnt){\n\n       while(!pq.empty() && pq.top().first<e){\n           e = min(e,pq.top().second);\n             pq.pop();\n             cnt++;\n        }\n       \n    }\n\npublic:\n    int eraseOverlapIntervals(vector<vector<int>>& grid) {\n           priority_queue <pair<int,int>, \n           vector<pair<int,int>>, greater<pair<int,int>> > pq;\n\n       for(int i =0; i<grid.size(); i++){\n           pq.push({grid[i][0],grid[i][1]});\n       }\n       int cnt =0;\n       while(!pq.empty()){\n           int e = pq.top().second;\n           pq.pop();\n           solve(pq,e,cnt);\n       }\n       return cnt;\n    }\n};"
    },
    {
        "title": "Find Original Array From Doubled Array",
        "algo_input": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.\n\nGiven an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.\n\n&nbsp;\nExample 1:\n\nInput: changed = [1,3,4,2,6,8]\nOutput: [1,3,4]\nExplanation: One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].\n\n\nExample 2:\n\nInput: changed = [6,3,0,1]\nOutput: []\nExplanation: changed is not a doubled array.\n\n\nExample 3:\n\nInput: changed = [1]\nOutput: []\nExplanation: changed is not a doubled array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= changed.length &lt;= 105\n\t0 &lt;= changed[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findOriginalArray(self, changed: List[int]) -> List[int]:\n        counter = collections.Counter(changed)\n        res = []\n        for k in counter.keys():\n            \n            if k == 0:\n                # handle zero as special case\n                if counter[k] % 2 > 0:\n                    return []\n                res += [0] * (counter[k] // 2)\n                \n            elif counter[k] > 0:\n                x = k\n                \n                # walk down the chain\n                while x % 2 == 0 and x // 2 in counter:\n                    x = x // 2\n                    \n                # walk up and process all numbers within the chain. mark the counts as 0\n                while x in counter:\n                    if counter[x] > 0:\n                        res += [x] * counter[x]\n                        if counter[x+x] < counter[x]:\n                            return []\n                        counter[x+x] -= counter[x]\n                        counter[x] = 0\n                    x += x\n        return res",
        "solution_js": "// Idea is to sort the input array first then start traversing the array\n// now if we saw half of the current element before and that half is unmatched then\n// match both of them otherwise note the occurence of current element inorder\n// to match it with its double element in the future\n\n// Time -> O(nlogn) due to sorting\n// Space -> O(n) due to map\n\n/**\n * @param {number[]} changed\n * @return {number[]}\n */\nvar findOriginalArray = function(changed) {\n    \n    const n = changed.length\n    if(n%2 === 1) return []\n    \n    let original = []\n    let map = new Map()\n    \n    changed.sort((a,b) => {\n        return a-b\n    })\n    \n    for(let ele of changed) {\n        const half = ele/2\n        if(map.has(half) && map.get(half) > 0) {\n            original.push(half)\n            map.set(half, map.get(half)-1)\n        } else {\n            map.set(ele, map.has(ele) ? map.get(ele)+1: 1)\n        }\n    }\n    \n    if(original.length !== n/2) return []\n    \n    return original\n};",
        "solution_java": "class Solution {\n    public int[] findOriginalArray(int[] changed) {\n\n        Arrays.sort(changed);\n\n        if(changed.length%2!=0) return new int[0];\n\n        int mid = changed.length/2;\n\n        int[] res = new int[mid];\n\n        int[] freq = new int[100001];\n\n        for(int no : changed)\n            freq[no]++;\n\n        int idx=0;\n\n        for(int no: changed){\n            if(freq[no] > 0 && no*2 <= 100000 && freq[no*2]>0){\n                freq[no]--;\n                freq[no*2]--;\n                res[idx++] = no;\n            }\n        }\n\n        for(int i=0; i<freq.length; i++){\n            if(freq[i]!=0) return new int[0];\n        }\n\n        return res;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findOriginalArray(vector<int>& changed) {\n        unordered_map<int, int> freq;\n        for (auto num : changed) freq[num]++;\n        \n        sort(changed.begin(), changed.end());\n        \n        vector<int> res;\n        for (auto num : changed) {\n            if (freq[num] && freq[num*2]) {\n                freq[num]--;\n                freq[num*2]--;\n                res.push_back(num);\n            }\n        }\n        \n        for (auto [a, b] : freq)\n            if (b) return {};\n        \n        return res;\n    }\n};"
    },
    {
        "title": "Minimum Suffix Flips",
        "algo_input": "You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.\n\nIn one operation, you can pick an index i where 0 &lt;= i &lt; n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.\n\nReturn the minimum number of operations needed to make s equal to target.\n\n&nbsp;\nExample 1:\n\nInput: target = \"10111\"\nOutput: 3\nExplanation: Initially, s = \"00000\".\nChoose index i = 2: \"00000\" -&gt; \"00111\"\nChoose index i = 0: \"00111\" -&gt; \"11000\"\nChoose index i = 1: \"11000\" -&gt; \"10111\"\nWe need at least 3 flip operations to form target.\n\n\nExample 2:\n\nInput: target = \"101\"\nOutput: 3\nExplanation: Initially, s = \"000\".\nChoose index i = 0: \"000\" -&gt; \"111\"\nChoose index i = 1: \"111\" -&gt; \"100\"\nChoose index i = 2: \"100\" -&gt; \"101\"\nWe need at least 3 flip operations to form target.\n\n\nExample 3:\n\nInput: target = \"00000\"\nOutput: 0\nExplanation: We do not need any operations since the initial s already equals target.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == target.length\n\t1 &lt;= n &lt;= 105\n\ttarget[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def minFlips(self, target: str) -> int:\n        flip = False\n        res = 0\n        for c in target:\n            if (c == '1') != flip:\n                flip = not flip\n                res += 1\n        \n        return res",
        "solution_js": "var minFlips = function(target) {\n    target = \"0\" + target;\n    let count = (target.match(/01/g) || []).length * 2;\n    return target[target.length -1] ===\"0\" ? count : count - 1;\n};",
        "solution_java": "class Solution {\n    public int minFlips(String target) {\n\n        boolean lastBit = false;\n\n        int flips = 0;\n        for(int i=0;i<target.length();i++){\n\n            if(target.charAt(i)=='1' && !lastBit){\n                flips++;\n                lastBit = !lastBit;\n            }\n            else if(target.charAt(i)=='0' && lastBit){\n                flips++;\n                lastBit = !lastBit;\n            }\n\n        }\n\n        return flips;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minFlips(string target) {\n\tint count=0;\n\t\t// we see thye number of times the change occur\n        for(int i=0; i<target.size()-1;i++){\n            if(target[i] != target[i+1] ){\n                count++;\n            }}\n        if(target[0]=='0'){return count;}\n        else{return count+1;}\n        return 0;\n    }\n};"
    },
    {
        "title": "Sum of Left Leaves",
        "algo_input": "Given the root of a binary tree, return the sum of all left leaves.\n\nA leaf is a node with no children. A left leaf is a leaf that is the left child of another node.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 24\nExplanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.\n\n\nExample 2:\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, 1000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",
        "solution_py": "def is_leaf(x):\n    return x.left is None and x.right is None\n\nclass Solution:\n    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n        if root is None:\n            return 0\n        if root.left and is_leaf(root.left):\n            left = root.left.val\n        else:\n            left = self.sumOfLeftLeaves(root.left)\n        return left + self.sumOfLeftLeaves(root.right)",
        "solution_js": "var sumOfLeftLeaves = function(root) {\n    let total = 0;\n    \n    const go = (node, isLeft) => {\n        if (isLeft && !node.left && !node.right) {\n            total += node.val;\n            return;\n        }\n        if (node.left) go(node.left, true);\n        if (node.right) go(node.right, false)\n    }\n    \n    go(root, false)\n    \n    return total;\n};",
        "solution_java": "class Solution {\n    public int sumOfLeftLeaves(TreeNode root) {\n\n        if(root==null)\n            return 0;\n\n        if(root.left!=null && root.left.left==null && root.left.right==null){\n            return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n        }else{\n            return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n        }\n\n    }\n}",
        "solution_c": "class Solution {\n    int sum=0;\npublic:\n    bool solve(TreeNode* root){\n        if(root==NULL) return false;\n        if(root->left==NULL && root->right==NULL) return true;\n        if(solve(root->left)) sum+=root->left->val;\n        solve(root->right);\n        return false;\n    }\n    int sumOfLeftLeaves(TreeNode* root) {\n        solve(root);\n        return sum;\n    }\n};"
    },
    {
        "title": "Minimum Initial Energy to Finish Tasks",
        "algo_input": "You are given an array tasks where tasks[i] = [actuali, minimumi]:\n\n\n\tactuali is the actual amount of energy you spend to finish the ith task.\n\tminimumi is the minimum amount of energy you require to begin the ith task.\n\n\nFor example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.\n\nYou can finish the tasks in any order you like.\n\nReturn the minimum initial amount of energy you will need to finish all the tasks.\n\n&nbsp;\nExample 1:\n\nInput: tasks = [[1,2],[2,4],[4,8]]\nOutput: 8\nExplanation:\nStarting with 8 energy, we finish the tasks in the following order:\n    - 3rd task. Now energy = 8 - 4 = 4.\n    - 2nd task. Now energy = 4 - 2 = 2.\n    - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n\nExample 2:\n\nInput: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput: 32\nExplanation:\nStarting with 32 energy, we finish the tasks in the following order:\n    - 1st task. Now energy = 32 - 1 = 31.\n    - 2nd task. Now energy = 31 - 2 = 29.\n    - 3rd task. Now energy = 29 - 10 = 19.\n    - 4th task. Now energy = 19 - 10 = 9.\n    - 5th task. Now energy = 9 - 8 = 1.\n\nExample 3:\n\nInput: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput: 27\nExplanation:\nStarting with 27 energy, we finish the tasks in the following order:\n    - 5th task. Now energy = 27 - 5 = 22.\n    - 2nd task. Now energy = 22 - 2 = 20.\n    - 3rd task. Now energy = 20 - 3 = 17.\n    - 1st task. Now energy = 17 - 1 = 16.\n    - 4th task. Now energy = 16 - 4 = 12.\n    - 6th task. Now energy = 12 - 6 = 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tasks.length &lt;= 105\n\t1 &lt;= actual​i&nbsp;&lt;= minimumi&nbsp;&lt;= 104\n\n",
        "solution_py": "class Solution:\n    def minimumEffort(self, tasks: List[List[int]]) -> int:\n        tasks.sort(key=lambda x: x[0]-x[1])\n        def ok(mid):\n            for actual, minimum in tasks:\n                if minimum > mid or actual > mid: return False\n                if minimum <= mid: mid -= actual\n            return True\n        l, r = 0, 10 ** 9\n        while l <= r:\n            mid = (l+r) // 2\n            if ok(mid): r = mid - 1\n            else: l = mid + 1\n        return l",
        "solution_js": "var minimumEffort = function(tasks) {\n  let minimumStartingEnergy = 0;\n  let currentEnergy = 0;\n  \n  tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]) );\n  \n  for (let task of tasks) {\n    if (task[1] > currentEnergy) {\n      minimumStartingEnergy += (task[1] - currentEnergy);\n      currentEnergy = task[1];\n    }\n    currentEnergy -= task[0];\n  }\n  \n  return minimumStartingEnergy;\n};",
        "solution_java": "import java.util.*;\nclass Solution {\n    public int minimumEffort(int[][] tasks)\n    {\n        Arrays.sort(tasks, new Comparator<int[]>(){\n            @Override\n            public int compare(int[] a, int[] b)\n            {\n                return (b[1]-b[0])-(a[1]-a[0]);\n            }\n        });\n        int sum=0, max=0;\n        for(int i=0;i<tasks.length;i++)\n        {\n            max=Math.max(max, sum+tasks[i][1]);\n            sum+=tasks[i][0];\n        }\n        \n        return max;\n        \n    }\n}```",
        "solution_c": "class Solution {\npublic:\n    int minimumEffort(vector<vector<int>>& tasks) {\n        int diff=INT_MAX,ans=0;\n        for(auto i : tasks){\n            diff=min(diff,i[1]-i[0]);\n            ans+=i[0];\n        }\n        int val=0;\n        for(auto i : tasks)\n            val=max(val,i[1]);\n        return max(ans+diff,val);\n    }\n};"
    },
    {
        "title": "Combination Sum III",
        "algo_input": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true:\n\n\n\tOnly numbers 1 through 9 are used.\n\tEach number is used at most once.\n\n\nReturn a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.\n\n&nbsp;\nExample 1:\n\nInput: k = 3, n = 7\nOutput: [[1,2,4]]\nExplanation:\n1 + 2 + 4 = 7\nThere are no other valid combinations.\n\nExample 2:\n\nInput: k = 3, n = 9\nOutput: [[1,2,6],[1,3,5],[2,3,4]]\nExplanation:\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\n\n\nExample 3:\n\nInput: k = 4, n = 1\nOutput: []\nExplanation: There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= k &lt;= 9\n\t1 &lt;= n &lt;= 60\n\n",
        "solution_py": "class Solution:\n    \n    def solve(self,k,target,ans,temp,idx,nums):\n        \n        if idx==len(nums):\n            if target==0 and k==0:\n                ans.append(list(temp))\n            return\n        \n        if nums[idx]<=target:\n            \n            temp.append(nums[idx])\n            self.solve(k-1,target-nums[idx],ans,temp,idx+1,nums)\n            temp.pop()\n        \n        self.solve(k,target,ans,temp,idx+1,nums)\n        \n\n    \n    def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n        \n        ans = []\n        temp = []\n        idx = 0\n        nums = list(range(1,10))\n        \n        self.solve(k,n,ans,temp,idx,nums)\n        return ans\n                ",
        "solution_js": "/**\n * @param {number} k\n * @param {number} n\n * @return {number[][]}\n */\nvar combinationSum3 = function(k, n) {\n    const ans = [];\n    const st = [];\n\n    function dfs(start, t) {\n        if (t === 0 && st.length === k) {\n            ans.push(Array.from(st));\n            return;\n        }\n        for (let i = start; i <= 9 && st.length < k; i++) {\n            if (i > t) break;\n            st.push(i);\n            dfs(i + 1, t - i);\n            st.pop();\n        }\n    }\n\n    dfs(1, n);\n\n    return ans;\n};",
        "solution_java": "//Recursion\n\nclass Solution {\n    public List<List<Integer>> combinationSum3(int k, int n) {\n        List<List<Integer>> ans = new ArrayList<List<Integer>>();\n        //int[] arr = new int{1,2,3,4,5,6,7,8,9};\n        List<Integer> ds = new ArrayList<>();\n        helper(1, n, k, ds, ans);\n        return ans;\n    }\n    private static void helper(int i, int tar, int k, List<Integer> ds, List<List<Integer>> ans){\n        //base\n        if(k == 0) {\n            if(tar == 0){\n                ans.add(new ArrayList<>(ds));\n            }\n            return;\n        }\n        if(tar == 0) return; //bcz if k is not zero and tar is zero then no possible valid combination\n        if(i > tar) return;\n        if(i > 9) return;\n\n        //Take\n        if(i <= tar) {\n            ds.add(i);\n            helper(i+1, tar - i, k-1 , ds, ans);\n            ds.remove(ds.size()-1);\n        }\n        // Not take\n        helper(i+1 , tar, k , ds, ans);\n\n        return;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> ans;\n    //declare temp global vector in this vector we will store temprary combinations\n    vector<int> temp;\n    void solve(int k,int n,int order){\n        //check if our target became zero and combination size became zero then push temp vector inside the ans it means this temp vector combination having sum is equal to target and size of vector is equal to k\n        if(n==0 && k==0){\n            ans.push_back(temp);\n            return;\n        }\n        //check if our target is less than zero then return \n        if(n<0) return;\n         // take for loop and check for all posibility ahead of order\n        for(int i=order;i<=9;i++){\n            //push current index value\n            temp.push_back(i);\n            // call solve function for further posiblity\n            solve(k-1,n-i,i+1);\n            //Pop last push value \n            temp.pop_back();\n        }\n    }\n    vector<vector<int>> combinationSum3(int k, int n) {\n        solve(k,n,1);\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Value to Get Positive Step by Step Sum",
        "algo_input": "Given an array of integers&nbsp;nums, you start with an initial positive value startValue.\n\nIn each iteration, you calculate the step by step sum of startValue&nbsp;plus&nbsp;elements in nums&nbsp;(from left to right).\n\nReturn the minimum positive value of&nbsp;startValue such that the step by step sum is never less than 1.\n\n&nbsp;\nExample 1:\n\nInput: nums = [-3,2,-3,4,2]\nOutput: 5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3\n  (1 +2 ) = 3  | (2 +2 ) = 4    |   2\n  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3\n  (0 +4 ) = 4  | (1 +4 ) = 5    |   4\n  (4 +2 ) = 6  | (5 +2 ) = 7    |   2\n\n\nExample 2:\n\nInput: nums = [1,2]\nOutput: 1\nExplanation: Minimum start value should be positive. \n\n\nExample 3:\n\nInput: nums = [1,-2,-3]\nOutput: 5\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t-100 &lt;= nums[i] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def minStartValue(self, nums: List[int]) -> int:\n        return max(1, 1 - min(accumulate(nums)))",
        "solution_js": "var minStartValue = function(nums) {\n    var min = 1;\n    var sum = 0;\n\t\n    for(var i=0;i<nums.length;i++){\n        sum = sum+nums[i];\n        min = Math.min(min,sum);\n    }\n    if(min == 1){\n        return min;\n    }\n\t// add 1 to negative of min value obtained to keep the sum always positive\n    return (-1*min)+1;\n};",
        "solution_java": "class Solution {\n    public int minStartValue(int[] nums) {\n        int lowest_sum = 0;\n        int sum = 0;\n        for(int i=0; i<nums.length; i++) {\n            sum += nums[i];\n            if(lowest_sum > sum) {\n                lowest_sum = sum;\n            }\n        }\n        return 1-lowest_sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minStartValue(vector<int>& nums) {\n        int result=min(nums[0],0);\n        for(int i=1;i<nums.size();i++){\n            nums[i]+=nums[i-1];\n            result = min(result,nums[i]);\n        }\n        return abs(result)+1;\n    }\n};"
    },
    {
        "title": "K-diff Pairs in an Array",
        "algo_input": "Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.\n\nA k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:\n\n\n\t0 &lt;= i, j &lt; nums.length\n\ti != j\n\tnums[i] - nums[j] == k\n\n\nNotice that |val| denotes the absolute value of val.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,1,4,1,5], k = 2\nOutput: 2\nExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number of unique pairs.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5], k = 1\nOutput: 4\nExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n\n\nExample 3:\n\nInput: nums = [1,3,1,5,4], k = 0\nOutput: 1\nExplanation: There is one 0-diff pair in the array, (1, 1).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-107 &lt;= nums[i] &lt;= 107\n\t0 &lt;= k &lt;= 107\n\n",
        "solution_py": "class Solution:\n    def findPairs(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        dict1={}\n        s=0\n        res=[]\n        for n in nums:\n            if dict1.get(n,None) is not None:\n                res.append(n)\n            dict1[n+k]=n\n        res=list(set(res))\n        return len(res)",
        "solution_js": "var findPairs = function(nums, k) {\n\tnums.sort((a, b) => b - a);\n\tconst { length } = nums;\n\tconst hash = new Set();\n\tlet left = 0;\n\tlet right = 1;\n\n\twhile (left < length - 1) {\n\t\twhile (right < length) {\n\t\t\tconst diff = nums[left] - nums[right];\n\n\t\t\tdiff === k && hash.add(`${nums[left]},${nums[right]}`);\n\t\t\tdiff > k\n\t\t\t\t? right = length\n\t\t\t\t: right += 1;\n\t\t}\n\t\tleft += 1;\n\t\tright = left + 1;\n\t}\n\treturn hash.size;\n};",
        "solution_java": " // O(n) Time Solution\n\n class Solution {\n \t\tpublic int findPairs(int[] nums, int k) {\n \t\t\tMap<Integer, Integer> map = new HashMap();\n \t\t\tfor (int num : nums)\n \t\t\t\tmap.put(num, map.getOrDefault(num, 0) + 1);\n\n \t\t\tint result = 0;\n \t\t\tfor (int i : map.keySet())\n \t\t\t\tif (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)\n \t\t\t\t\tresult++;\n \t\t\treturn result;\n \t\t}\n \t}",
        "solution_c": "class Solution {\npublic:\n    int findPairs(vector<int>& nums, int k) {\n        unordered_map<int,int> a;\n        for(int i:nums)\n            a[i]++;\n        int ans=0;\n        for(auto x:a)\n        {\n            if(k==0)\n            {    \n                if(x.second>1)\n                ans++;\n            }\n             else if(a.find(x.first+k)!=a.end())\n                ans++;\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Binary Tree Preorder Traversal",
        "algo_input": "Given the root of a binary tree, return the preorder traversal of its nodes' values.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,2,3]\nOutput: [1,2,3]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [1]\nOutput: [1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 100].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow up: Recursive solution is trivial, could you do it iteratively?\n",
        "solution_py": "from collections import deque\nfrom typing import List, Optional\n\nclass Solution:\n    \"\"\"\n    Time: O(n)\n    \"\"\"\n\n    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n        if root is None:\n            return []\n\n        queue = deque([root])\n        preorder = []\n\n        while queue:\n            node = queue.pop()\n            preorder.append(node.val)\n\n            if node.right is not None:\n                queue.append(node.right)\n            if node.left is not None:\n                queue.append(node.left)\n\n        return preorder\n\nclass Solution:\n    \"\"\"\n    Time: O(n)\n    \"\"\"\n\n    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n        return list(self.preorder_generator(root))\n\n    @classmethod\n    def preorder_generator(cls, tree: Optional[TreeNode]):\n        if tree is not None:\n            yield tree.val\n            yield from cls.preorder_generator(tree.left)\n            yield from cls.preorder_generator(tree.right)",
        "solution_js": "var preorderTraversal = function(root) {\n    let res = []\n    \n    const check = node => {\n        if(node === null) return\n        else res.push(node.val)\n        \n        if(node.left !== null) check(node.left)\n        if(node.right !== null) check(node.right)\n    }\n    \n    check(root)\n    \n    return res\n};",
        "solution_java": "class Solution {\n     public List<Integer> preorderTraversal(TreeNode root) {\n        List<Integer> result = new ArrayList<>();\n        preorderTraversal2(root, result);\n        return result;\n    }\n\n\n    public List<Integer> preorderTraversal2(TreeNode root,List<Integer> result) {\n        if(root!=null){\n               result.add(root.val);\n            if(root.left!=null){\n                preorderTraversal2(root.left,result);\n            }\n            if(root.right!=null){\n                preorderTraversal2(root.right,result);\n            }\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution {\n    void solve(TreeNode *root, vector<int> &ans){\n        if(root == NULL) return;\n        ans.push_back(root->val);\n        solve(root->left, ans);\n        solve(root->right, ans);\n    }\npublic:\n    vector<int> preorderTraversal(TreeNode* root) {\n        vector<int> ans;\n        solve(root, ans);\n        return ans;\n    }\n};"
    },
    {
        "title": "Process Restricted Friend Requests",
        "algo_input": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.\n\nYou are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.\n\nInitially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.\n\nA friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.\n\nReturn a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.\n\nNote: If uj and vj are already direct friends, the request is still successful.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).\n\n\nExample 2:\n\nInput: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).\n\n\nExample 3:\n\nInput: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput: [true,false,true,false]\nExplanation:\nRequest 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 1000\n\t0 &lt;= restrictions.length &lt;= 1000\n\trestrictions[i].length == 2\n\t0 &lt;= xi, yi &lt;= n - 1\n\txi != yi\n\t1 &lt;= requests.length &lt;= 1000\n\trequests[j].length == 2\n\t0 &lt;= uj, vj &lt;= n - 1\n\tuj != vj\n\n",
        "solution_py": "class UnionFindSet(object):\n    def __init__(self, n):\n        self.data = range(n)\n\n    def find(self, x):\n        while x <> self.data[x]:\n            x = self.data[x]\n        return x\n\n    def union(self, x, y):\n        self.data[self.find(x)] = self.find(y)\n\n    def speedup(self):\n        for i in range(len(self.data)):\n            self.data[i] = self.find(i)\n\n\nclass Solution(object):\n    def friendRequests(self, n, restrictions, requests):\n        uf = UnionFindSet(n)\n        ret = [True] * len(requests)\n        for k, [x, y] in enumerate(requests):  # Process Requests Sequentially\n            xh = uf.find(x)  # backup the head of x for undo\n            uf.union(x, y)  # link [x, y] and verify if any restriction triggers\n            for [i, j] in restrictions:\n                if uf.find(i) == uf.find(j):\n                    ret[k] = False\n                    break\n            if not ret[k]:  # if any restriction triggers, undo\n                uf.data[xh] = xh\n            else:\n                uf.speedup()\n        return ret",
        "solution_js": "/*\nDSU Class Template\n*/\nclass DSU {\n    constructor() {\n        this.parents = new Map();\n        this.rank = new Map();\n    }\n\n    add(x) {\n        this.parents.set(x, x);\n        this.rank.set(x, 0);\n    }\n\n    find(x) {\n        const parent = this.parents.get(x);\n        if (parent === x) return x;\n        const setParent = this.find(parent);\n        this.parents.set(x, setParent);\n        return setParent;\n    }\n\n    union(x, y) {\n        const xParent = this.find(x), yParent = this.find(y);\n        const xRank = this.rank.get(xParent), yRank = this.rank.get(yParent);\n        if (xParent === yParent) return;\n        if (xRank > yRank) {\n            this.parents.set(yParent, xParent);\n        } else if (yRank > xRank) {\n            this.parents.set(xParent, yParent);\n        } else {\n            this.parents.set(xParent, yParent);\n            this.rank.set(yParent, yRank + 1);\n        }\n    }\n}\n\n/*\nFriend Requests\n*/\nvar friendRequests = function(n, restrictions, requests) {\n    const dsu = new DSU(), result = [];\n    for (let i = 0; i < n; i++) dsu.add(i);\n\n    for (let [friend1, friend2] of requests) {\n        const parent1 = dsu.find(friend1), parent2 = dsu.find(friend2);\n        let friendshipPossible = true;\n        for (let [enemy1, enemy2] of restrictions) {\n            const enemyParent1 = dsu.find(enemy1), enemyParent2 = dsu.find(enemy2);\n            const condition1 = (enemyParent1 === parent1 && enemyParent2 === parent2);\n            const condition2 = (enemyParent1 === parent2 && enemyParent2 === parent1);\n            if (condition1 || condition2) {\n                friendshipPossible = false;\n                break;\n            }\n        }\n        if (friendshipPossible) dsu.union(friend1, friend2);\n        result.push(friendshipPossible);\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    int[] parent;\n    boolean[] result;\n    \n    public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n        parent = new int[n];\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n        result = new boolean[requests.length];\n        \n        for (int i = 0; i < requests.length; i++) {\n            // personA and personB can become friends if for all restrictions\n            // person x_i and person y_i are not in the same set as personA and personB\n            // and vice versa\n            int personA = requests[i][0];\n            int personB = requests[i][1];\n            int personASetRepresentative = find(personA);\n            int personBSetRepresentative = find(personB);\n            boolean flag = true;\n            for (int[] restriction : restrictions) {\n                int blackListPersonARepresentative = find(restriction[0]);\n                int blackListPersonBRepresentative = find(restriction[1]);\n                if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) {\n                    flag = false;\n                }\n                if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) {\n                    flag = false;\n                }\n            }\n            if (flag) {\n                union(personA, personB);\n            }\n            result[i] = flag;\n        }\n        return result;\n    }\n    \n    private int find(int node) {\n        int root = node;\n        while (parent[root] != root) {\n            root = parent[root];\n        }\n        \n        //path compression\n        int curr = node;\n        while (parent[curr] != root) {\n            int next = parent[curr];\n            parent[curr] = root;\n            curr = next;\n        }\n        return root;\n    }\n    \n    private boolean union(int node1, int node2) {\n        int root1 = find(node1);\n        int root2 = find(node2);\n        if (root1 == root2) {\n            return false;\n        }\n        parent[root2] = root1;\n        return true;\n    }\n}",
        "solution_c": "/ Standard DSU Class\nclass DSU {\n    vector<int> parent, size;\npublic:\n\n    DSU(int n) {\n        for(int i=0; i<=n; i++) {\n            parent.push_back(i);\n            size.push_back(1);\n        }\n    }\n\n    int findParent(int num) {\n        if(parent[num] == num) return num;\n        return parent[num] = findParent(parent[num]);\n    }\n\n    // Directly getting parents of u and v\n    // To avoid finding parent multiple times\n    void unionBySize(int parU, int parV) {\n\n        if(size[parU] < size[parV]) {\n            size[parV] += size[parU];\n            parent[parU] = parV;\n        }\n        else {\n            size[parU] += size[parV];\n            parent[parV] = parU;\n        }\n    }\n};\n\nclass Solution {\npublic:\n    vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) {\n\n        DSU dsu(n);\n\n        vector<bool> successful;\n\n        for(auto& request : requests) {\n\n            int u = request[0], v = request[1];\n\n            int parU = dsu.findParent(u), parV = dsu.findParent(v);\n\n            bool flag = true;\n\n            if(parU != parV) {\n\n                // Check if current friend requested is restricted or not.\n                for(auto& restriction : restrictions) {\n                    int restricted_U = restriction[0], restricted_V = restriction[1];\n\n                    int restricted_parU = dsu.findParent(restricted_U);\n                    int restricted_parV = dsu.findParent(restricted_V);\n\n                    if((parU == restricted_parU && parV == restricted_parV) || (parU == restricted_parV && parV == restricted_parU)) {\n                        flag = false;\n                        break;\n                    }\n                }\n\n                // Union u and v by passing parents\n                // Since it is already calculated above\n                if(flag) {\n                    dsu.unionBySize(parU, parV);\n                }\n            }\n\n            successful.push_back(flag);\n        }\n\n        return successful;\n    }\n};"
    },
    {
        "title": "Maximum Number of Consecutive Values You Can Make",
        "algo_input": "You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.\n\nReturn the maximum number of consecutive integer values that you can make with your coins starting from and including 0.\n\nNote that you may have multiple coins of the same value.\n\n&nbsp;\nExample 1:\n\nInput: coins = [1,3]\nOutput: 2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.\n\nExample 2:\n\nInput: coins = [1,1,1,4]\nOutput: 8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.\n\nExample 3:\n\nInput: nums = [1,4,10,3,1]\nOutput: 20\n\n&nbsp;\nConstraints:\n\n\n\tcoins.length == n\n\t1 &lt;= n &lt;= 4 * 104\n\t1 &lt;= coins[i] &lt;= 4 * 104\n\n",
        "solution_py": "class Solution:\n    def getMaximumConsecutive(self, coins: List[int]) -> int:\n        coins.sort()\n        \n        res = 1\n        \n        for coin in coins:\n            if (res >= coin):\n                res += coin\n        \n        return res",
        "solution_js": "// we iterate from the smallest number while maintaining an integer sum. sum means that we can produce all number from 0 to sum.\n// when we can make numbers from 0 to sum, and we encounter a new number, lets say arr[2].\n// it is obvious that we can create all numbers from sum to sum + arr[2].\n// if there is a gap if(arr[i] > sum+1) it means no combinations could create that number and we stop.\nvar getMaximumConsecutive = function(coins) {\n    coins.sort((a,b) => a-b);\n    let sum = 1;\n    for(let i = 0; i < coins.length; i++) {\n        if(coins[i] <= sum) {\n            sum += coins[i];\n        } else {\n            break;\n        }\n    }\n    return sum;\n};",
        "solution_java": "class Solution {\n    public int getMaximumConsecutive(int[] coins) {\n      if(coins.length==0 && coins==null)\n          return 0;\n      TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();\n      for(int i:coins)\n          map.put(i,map.getOrDefault(i,0)+1);\n      int range=0;\n      for(int i:map.keySet()){\n       if(range==0 && i==1)\n       range=i*map.get(i);\n       else if(range!=0 && range+1>=i)\n         range+=i*map.get(i);\n       else \n        break;\n      }\n     return range+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getMaximumConsecutive(vector<int>& coins) {\n        sort(coins.begin(), coins.end());\n        int n = coins.size();\n        int ans = 1;\n        for(int i = 0; i < n; i++) {\n            if(coins[i] > ans) return ans;\n            ans += coins[i]; \n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Ways to Split Array Into Three Subarrays",
        "algo_input": "A split of an integer array is good if:\n\n\n\tThe array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.\n\tThe sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.\n\n\nGiven nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,1]\nOutput: 1\nExplanation: The only good way to split nums is [1] [1] [1].\n\nExample 2:\n\nInput: nums = [1,2,2,2,5,0]\nOutput: 3\nExplanation: There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]\n\n\nExample 3:\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: There is no good way to split nums.\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 104\n",
        "solution_py": "class Solution:\n    def waysToSplit(self, nums: List[int]) -> int:\n        prefix = [0]\n        for x in nums: prefix.append(prefix[-1] + x)\n        \n        ans = 0\n        for i in range(1, len(nums)): \n            j = bisect_left(prefix, 2*prefix[i])\n            k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n            ans += max(0, min(len(nums), k) - max(i+1, j))\n        return ans % 1_000_000_007",
        "solution_js": "var waysToSplit = function(nums) {\n    const mod = 1000000007;\n    const lastIndex = nums.length - 2;\n    const total = nums.reduce((sum, num) => sum + num)\n\n    let midLeftPtr = -1;\n    let midRightPtr = -1;\n    \n    let leftSum = 0;\n    let midLeftSum = 0;\n    let midRightSum = 0;\n    \n    let numWaysToSplit = 0;\n    \n    for (let leftPtr = 0; leftPtr < nums.length; leftPtr++) {\n        leftSum += nums[leftPtr];        \n        midLeftSum -= nums[leftPtr];\n        midRightSum -= nums[leftPtr];\n\n       // find the first index that satisfies the middle sum\n\t   // being greater than or equal to the left sum\n        while (midLeftPtr <= lastIndex && \n               (midLeftPtr <= leftPtr || midLeftSum < leftSum)) {\n            midLeftPtr++;\n            midLeftSum += nums[midLeftPtr]\n        }\n\n        // find the first index that makes the middle sum greater than the right sum\n        while (midRightPtr <= lastIndex && \n               (midLeftPtr > midRightPtr || midRightSum <= total - midRightSum - leftSum)) {\n            midRightPtr++\n            midRightSum += nums[midRightPtr]\n        }\n        numWaysToSplit = (numWaysToSplit + midRightPtr - midLeftPtr) % mod;\n    }\n    return numWaysToSplit\n};",
        "solution_java": "class Solution {\n    public int waysToSplit(int[] nums) {\n        int size = nums.length;\n        for (int i = 1; i < size; ++i) {\n            nums[i] += nums[i - 1];\n        }\n        int res = 0;\n        int mod = 1_000_000_007;\n        for (int i = 0; i < size - 2; ++i) {\n            int left = searchLeft(nums, i, size - 1);\n            int right = searchRight(nums, i, size - 1);\n            if (left == -1 || right == -1) {\n                continue;\n            }\n            res = (res + right - left + 1) % mod;\n        }\n        return res;\n    }\n    \n    private int searchLeft(int[] nums, int left, int right) {\n        int pos = -1;\n        int min = nums[left];\n        int lo = left + 1, hi = right - 1;\n        while (lo <= hi) {\n            int mi = lo + (hi - lo) / 2;\n            int mid = nums[mi] - min;\n            int max = nums[right] - nums[mi];\n            if (mid < min) {\n                lo = mi + 1;\n            } else if (max < mid){\n                hi = mi - 1;\n            } else {\n                pos = mi;\n                hi = mi - 1;\n            }\n        }\n        return pos;\n    }\n    \n    private int searchRight(int[] nums, int left, int right) {\n        int pos = -1;\n        int min = nums[left];\n        int lo = left + 1, hi = right - 1;\n        while (lo <= hi) {\n            int mi = lo + (hi - lo) / 2;\n            int mid = nums[mi] - min;\n            int max = nums[right] - nums[mi];\n            if (mid < min) {\n                lo = mi + 1;\n            } else if (max < mid){\n                hi = mi - 1;\n            } else {\n                pos = mi;\n                lo = mi + 1;\n            }\n        }\n        return pos;\n    }\n    \n}",
        "solution_c": "class Solution {\npublic:\n    int waysToSplit(vector<int>& nums) {\n        int n = nums.size(), mod = 1e9 + 7;  long long ans = 0;\n        vector<int> prefix(n);\n        partial_sum(nums.begin(), nums.end(),prefix.begin());\n        for (int i = 0; i < n - 2; i++) {\n            int left = prefix[i], remain = (prefix[n - 1] - prefix[i]);\n                if (remain < left * 2) break;\n            int leftPtr = lower_bound(prefix.begin() + i + 1, prefix.end() - 1, left * 2) - prefix.begin();\n            int rightPtr = upper_bound(prefix.begin() + i + 1, prefix.end() - 1, left + remain / 2) - prefix.begin() - 1;\n\n            if (rightPtr - leftPtr + 1 > 0) ans += rightPtr - leftPtr + 1;\n        }\n        \n        return ans % mod;\n    }\n};"
    },
    {
        "title": "Maximum Points in an Archery Competition",
        "algo_input": "Alice and Bob are opponents in an archery competition. The competition has set the following rules:\n\n\n\tAlice first shoots numArrows arrows and then Bob shoots numArrows arrows.\n\tThe points are then calculated as follows:\n\t\n\t\tThe target has integer scoring sections ranging from 0 to 11 inclusive.\n\t\tFor each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak &gt;= bk, then Alice takes k points. If ak &lt; bk, then Bob takes k points.\n\t\tHowever, if ak == bk == 0, then nobody takes k points.\n\t\n\t\n\n\n\n\t\n\tFor example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.\n\t\n\n\nYou are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.\n\nReturn the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.\n\nIf there are multiple ways for Bob to earn the maximum total points, return any one of them.\n\n&nbsp;\nExample 1:\n\nInput: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\nOutput: [0,0,0,0,1,1,0,0,1,2,3,1]\nExplanation: The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.\n\n\nExample 2:\n\nInput: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\nOutput: [0,0,0,0,0,0,0,0,1,1,1,0]\nExplanation: The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= numArrows &lt;= 105\n\taliceArrows.length == bobArrows.length == 12\n\t0 &lt;= aliceArrows[i], bobArrows[i] &lt;= numArrows\n\tsum(aliceArrows[i]) == numArrows\n\n",
        "solution_py": "class Solution:\n    def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n        self.bestScore = 0\n        self.bestBobArrows = None\n        \n        def backtracking(k, remainArrows, score, bobArrows):\n            if k == 12:\n                if score > self.bestScore:\n                    self.bestScore = score\n                    self.bestBobArrows = bobArrows[::]\n                return\n            \n            backtracking(k+1, remainArrows, score, bobArrows)  # Bob loses\n            \n            # Bob wins\n            arrowsNeeded = aliceArrows[k] + 1\n            if remainArrows >= arrowsNeeded:\n                old = bobArrows[k]\n                bobArrows[k] = arrowsNeeded  # set new\n                backtracking(k+1, remainArrows - arrowsNeeded, score + k, bobArrows)\n                bobArrows[k] = old  # backtrack\n                \n        backtracking(0, numArrows, 0, [0] * 12)\n\t\t# In case of having remain arrows then it means in all sections Bob always win \n        # then we can distribute the remain to any section, here we simple choose first section.\n        self.bestBobArrows[0] += numArrows - sum(self.bestBobArrows)\n        return self.bestBobArrows",
        "solution_js": "var maximumBobPoints = function(numArrows, aliceArrows) {\n  let max = 0, n = aliceArrows.length, res;\n  backtrack(numArrows, 0, 0, Array(n).fill(0));\n  return res;\n\n  function backtrack(arrows, idx, points, bobArrows) {\n    if (idx === n || arrows === 0) {\n      let origVal = bobArrows[n - 1];\n      if (arrows > 0) bobArrows[n - 1] += arrows; // put extra arrows in any slot\n      if (points > max) {\n        max = points;\n        res = [...bobArrows]; \n      }\n      bobArrows[n - 1] = origVal;\n      return;\n    }\n\n    backtrack(arrows, idx + 1, points, bobArrows); // don't use any arrows\n    if (aliceArrows[idx] + 1 <= arrows) { // use aliceArrows[idx] + 1 arrows to gain idx points\n      bobArrows[idx] = aliceArrows[idx] + 1;\n      backtrack(arrows - (aliceArrows[idx] + 1), idx + 1, points + idx, bobArrows);\n      bobArrows[idx] = 0;\n    }\n  }  \n};",
        "solution_java": "   class Solution {\n        int bobPoint = 0;\n        int[] maxbob = new int[12];\n        public int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n            int[] bob = new int[12];\n            calculate(aliceArrows, bob, 11, numArrows, 0); //Start with max point that is 11\n            return maxbob;\n        }\n        public void calculate(int[] alice, int[] bob, int index, int remainArr, int point) {\n            if(index < 0 || remainArr <= 0) {\n                if(remainArr > 0)\n                    bob[0] += remainArr;\n                if(point > bobPoint) { // Update the max points and result output\n                    bobPoint = point;\n                    maxbob = bob.clone();\n                }\n                return;\n            }\n            //part 1: assign 1 more arrow than alice\n            if(remainArr >= alice[index]+1) {\n                bob[index] = alice[index] + 1;\n                calculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index);\n                bob[index] = 0;\n            }\n            //part 2: assign no arrow and move to next point\n            calculate(alice, bob, index-1, remainArr, point);\n            bob[index] = 0;\n        }\n    }",
        "solution_c": "class Solution {\npublic:\n    int maxscore; \n    vector<int> ans;\n    \n    void helper(vector<int> &bob, int i, vector<int>& alice, int remarrows, int score)\n    {\n        if(i == -1  or  remarrows <= 0)\n        {\n            if(score >= maxscore)\n            {\n                maxscore = score; \n                ans = bob; \n            }\n            return; \n        }\n        \n        helper(bob, i-1, alice, remarrows, score);\n        if(remarrows > alice[i])\n        {\n            bob[i] = alice[i] + 1;\n            remarrows -= (alice[i] + 1);\n            score += i; \n            helper(bob, i-1, alice, remarrows, score);\n            bob[i] = 0;\n        } \n    }\n    \n    vector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) {\n        vector<int> bob(12, 0);\n        maxscore = INT_MIN; \n        helper(bob, 11, aliceArrows, numArrows, 0);\n        \n        int arrows_used = 0; \n        for(int a : ans)\n            arrows_used += a; \n        if(arrows_used < numArrows)\n            ans[0] += (numArrows - arrows_used);\n        return ans; \n    }\n};"
    },
    {
        "title": "Sum of Mutated Array Closest to Target",
        "algo_input": "Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.\n\nIn case of a tie, return the minimum such integer.\n\nNotice that the answer is not neccesarilly a number from arr.\n\n&nbsp;\nExample 1:\n\nInput: arr = [4,9,3], target = 10\nOutput: 3\nExplanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\n\n\nExample 2:\n\nInput: arr = [2,3,5], target = 10\nOutput: 5\n\n\nExample 3:\n\nInput: arr = [60864,25176,27249,21296,20204], target = 56803\nOutput: 11361\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t1 &lt;= arr[i], target &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findBestValue(self, arr: List[int], t: int) -> int:\n        def getsum(x):\n            s = 0\n            for i in range(n):\n                if arr[i] > x:\n                    s += x*(n-i)\n                    break\n                else:\n                    s += arr[i]\n            return s\n\t\t\t\n\t\tarr.sort()\n        n = len(arr)\n        l, r = 0, max(arr)\n        ans = [inf, inf]\n        while l <= r:\n            m = l+(r-l)//2\n            if abs(getsum(m)-t) <= ans[0]:\n                if abs(getsum(m)-t) == ans[0]:\n                    ans[1] = min(m, ans[1])\n                else:\n                    ans = [abs(getsum(m)-t), m]\n            if getsum(m) > t:\n                r = m-1\n            else:\n                l = m+1\n        \n        return ans[1]",
        "solution_js": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nvar findBestValue = function(arr, target) {\n    const sortedArr = [...arr].sort(function (a, b) {  return a - b;  });\n    var lowestValue = Math.min(sortedArr[arr.length-1], Math.floor(target/arr.length));\n    var higestValue = Math.min(sortedArr[arr.length-1], target);\n    var value, deltaLeft, deltaRight;\n    \n    while (true) {\n        candidateRight = Math.ceil((lowestValue + higestValue)/2)\n        candidateLeft = candidateRight - 1\n        deltaLeft = calculateDeltaForCandidate(sortedArr, target, candidateLeft)\n        if (deltaLeft == 0) {\n            return candidateLeft\n        }\n        deltaRight = calculateDeltaForCandidate(sortedArr, target, candidateRight)\n        if (deltaRight == 0) {\n            return candidateRight\n        }\n        if (deltaRight == 0) {\n            return candidateRight\n        }\n        if (candidateRight == higestValue) {\n            return deltaLeft <= deltaRight ? candidateLeft : candidateRight;\n        }\n        if (deltaLeft <= deltaRight) {\n            higestValue = candidateLeft\n        } else {\n            lowestValue = candidateRight\n        }\n    }\n};\n\nvar calculateDeltaForCandidate = function(sArr, target, candidate) {\n    var sum\n    //find idx lover then candidate\n    for (var i=0; i < sArr.length; i++) {\n        if (sArr[i] >= candidate) {\n            sum = sArr.slice(0, i).reduce((partialSum, a) => partialSum + a, 0) + (sArr.length - i) * candidate;\n            return Math.abs(sum - target)\n        };\n    }\n    return NaN\n};",
        "solution_java": "class Solution {\n    int max = 0;\n    int len;\n    public int findBestValue(int[] arr, int target) {\n        this.len = arr.length;\n\n        for (int i = 0; i < len; i++)\n            max = Math.max(max, arr[i]);\n\n        int l = 0;\n        int r = max;\n        while(l < r){\n            int mid = l + (r-l) / 2;\n\n            if(check(arr, mid, target) <= check(arr, mid+1, target))\n                r = mid;\n            else\n                l = mid + 1;\n        }\n        return l;\n    }\n\n    private int check(int[] arr, int value, int target){\n        int sum = 0;\n        for(int e : arr){\n            if(e > value)\n                sum += value;\n            else\n                sum += e;\n        }\n\n        return Math.abs(sum-target);\n    }\n}",
        "solution_c": "// This Question Includes Both Binary Search And bit of Greedy Concept also.\n// See We Know Ans Always Lies Between 0 and maximum element according to given question condition Because\n// sum value at maximum element is same as any other element greater than it.\n// So we get our sum from getval function after that you need to choose as to move forward(l = mid+1) or backward\n// i.e.(h = mid-1) so if sum value we obtain is less than target then l = mid+1 why so??\n// Because 2 3 5 lets suppose you are having this array if we pick 2 as mid then sum value will be 6 whereas if we pick 3 then sum value will be 8 and 10 when we pick 5 so notice that sum will increase when we increase value and\n// correspondingly decrease when we decrease value...So yess This is all what we did and got Accepted.\nclass Solution {\npublic:\n    int getval(int mid , vector<int>&arr)\n    {\n        int sum = 0;\n        for(int i = 0 ; i < arr.size() ; i++)\n        {\n            if(arr[i] > mid)\n                sum+=mid;\n            else\n                sum+=arr[i];\n        }\n        return sum;\n    }\n    int findBestValue(vector<int>& arr, int target) {\n        int n = arr.size();\n        int l = 0 , h = *max_element(arr.begin(),arr.end());\n        int ans = 0, min1 = INT_MAX;\n        while(l<=h)\n        {\n            int mid = l + (h-l)/2;\n            int k = getval(mid,arr);\n            if(k==target)\n            {\n                return mid;\n            }\n            else if(k<target)\n            {\n                l = mid+1;\n            }\n            else\n                h = mid -1;\n\n            int j = abs(k - target);\n            if(j<min1)\n            {\n                min1 = j;\n                ans = mid;\n            }\n            else if(j==min1)\n            {\n                ans = min(ans , mid);\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Check Whether Two Strings are Almost Equivalent",
        "algo_input": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.\n\nGiven two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.\n\nThe frequency of a letter x is the number of times it occurs in the string.\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"aaaa\", word2 = \"bccb\"\nOutput: false\nExplanation: There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.\n\n\nExample 2:\n\nInput: word1 = \"abcdeef\", word2 = \"abaaacc\"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.\n\n\nExample 3:\n\nInput: word1 = \"cccddabba\", word2 = \"babababab\"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == word1.length == word2.length\n\t1 &lt;= n &lt;= 100\n\tword1 and word2 consist only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def checkAlmostEquivalent(self, w1: str, w2: str) -> bool:\n\t\treturn all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())",
        "solution_js": "var checkAlmostEquivalent = function(word1, word2) {\n    const hm = new Map()\n    const addToHm = (ch, add) => {\n        if (hm.has(ch)) \n            hm.set(ch, hm.get(ch) + (add ? +1 : -1))\n        else \n            hm.set(ch, (add ? +1 : -1))  \n    }\n    \n    for (let i = 0; i < word1.length; i++) {\n        addToHm(word1[i], true) \n        addToHm(word2[i], false) \n    }\n    \n    for (const val of hm.values())\n        if (Math.abs(val) > 3)\n\t\t\treturn false\n    \n    return true\n};",
        "solution_java": "class Solution { \n    public boolean checkAlmostEquivalent(String word1, String word2) {\n        Map<Character,Integer> map = new HashMap();\n        for (int i = 0; i < word1.length(); i++) {\n            map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1);\n            map.put(word2.charAt(i), map.getOrDefault(word2.charAt(i), 0) - 1);\n        }\n        for (int i : map.values()) { //get value set\n            if (i > 3 || i < -3) { \n                return false;\n            }\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool checkAlmostEquivalent(string word1, string word2) {\n\t\tunordered_map<char, int> m;\n\t\tfor(int i = 0; i < word1.size(); i++){\n\t\t\tm[word1[i]]++;\n\t\t}\n\t\tfor(int i = 0; i < word2.size(); i++){\n\t\t\tm[word2[i]]--;\n\t\t}\n\t\tfor(auto i : m){\n\t\t\tif(abs(i.second) > 3){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};"
    },
    {
        "title": "Minimum Window Substring",
        "algo_input": "Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\".\n\nThe testcases will be generated such that the answer is unique.\n\nA substring is a contiguous sequence of characters within the string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ADOBECODEBANC\", t = \"ABC\"\nOutput: \"BANC\"\nExplanation: The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.\n\n\nExample 2:\n\nInput: s = \"a\", t = \"a\"\nOutput: \"a\"\nExplanation: The entire string s is the minimum window.\n\n\nExample 3:\n\nInput: s = \"a\", t = \"aa\"\nOutput: \"\"\nExplanation: Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == s.length\n\tn == t.length\n\t1 &lt;= m, n&nbsp;&lt;= 105\n\ts and t consist of uppercase and lowercase English letters.\n\n\n&nbsp;\nFollow up: Could you find an algorithm that runs in O(m + n) time?",
        "solution_py": "# Added on 2022-08-18 15:51:55.963915\n\nvar minWindow = function(s, t) {\n    const tf = {}, sf = {};\n    for(let c of t) {\n        tf[c] = (tf[c] || 0) + 1;\n    }\n    let l = 0, r = 0, rs = t.length;\n    let ml = -1, mr = -1;\n    for(; r < s.length; r++) {\n        const c = s[r];\n\n        if(!tf[c]) continue;\n\n        const sc = sf[c] || 0;\n        sf[c] = sc + 1;\n        if(sf[c] <= tf[c]) {\n            rs--;\n        }\n\n        if(rs == 0) {\n            while(true) {\n                if(mr == -1 || mr - ml > r - l) {\n                    [mr, ml] = [r, l];\n                }\n\n                const c = s[l];\n                if(!tf[c]) {\n                    l++;\n                }\n                else if(sf[c] - 1 < tf[c]) {\n                    sf[c]--, l++, rs++;\n                    break;\n                } else {\n                    sf[c]--;\n                    l++;\n                }\n            }\n        }\n    }\n    if(mr == -1) return '';\n    return s.slice(ml, mr + 1);\n};",
        "solution_js": "var minWindow = function(s, t) {\n    const tf = {}, sf = {};\n    for(let c of t) {\n        tf[c] = (tf[c] || 0) + 1;\n    }\n    let l = 0, r = 0, rs = t.length;\n    let ml = -1, mr = -1;\n    for(; r < s.length; r++) {\n        const c = s[r];\n\n        if(!tf[c]) continue;\n\n        const sc = sf[c] || 0;\n        sf[c] = sc + 1;\n        if(sf[c] <= tf[c]) {\n            rs--;\n        }\n\n        if(rs == 0) {\n            while(true) {\n                if(mr == -1 || mr - ml > r - l) {\n                    [mr, ml] = [r, l];\n                }\n\n                const c = s[l];\n                if(!tf[c]) {\n                    l++;\n                }\n                else if(sf[c] - 1 < tf[c]) {\n                    sf[c]--, l++, rs++;\n                    break;\n                } else {\n                    sf[c]--;\n                    l++;\n                }\n            }\n        }\n    }\n    if(mr == -1) return '';\n    return s.slice(ml, mr + 1);\n};",
        "solution_java": "class Solution {\n    public String minWindow(String s, String t) {\n        HashMap<Character, Integer> child = new HashMap<>();\n        HashMap<Character, Integer> parent = new HashMap<>();\n\n        int left = -1, right = -1, match = 0;\n        String window = \"\";\n\n        for(int i = 0; i < t.length(); i++){\n            char c = t.charAt(i);\n            child.put(c, child.getOrDefault(c, 0) + 1); //Child frequency map\n            }\n\n        while(true){\n            boolean f1 = false, f2 = false;\n\n            while(right < s.length() - 1 && match < t.length()){\n                right++;\n                char c = s.charAt(right);\n                parent.put(c, parent.getOrDefault(c, 0) + 1); // Acquiring characters till\n                if(parent.getOrDefault(c, 0) <= child.getOrDefault(c, 0)) // match count is equal\n                    match++;\n\n                f1 = true;\n            }\n            while(left < right && match == t.length()){\n                String potstring = s.substring(left + 1, right + 1);\n                if(window.length() == 0 || window.length() > potstring.length())\n                    window = potstring; //Calculating length of window\n\n                    left++;\n                    char c = s.charAt(left);\n                    parent.put(c, parent.getOrDefault(c, 0) - 1);\n                    if(parent.get(c) == 0) //Releasing characters by\n                        parent.remove(c); //left pointer for finding smallest window\n\n                    if(parent.getOrDefault(c, 0) < child.getOrDefault(c, 0))\n                        match--;\n\n                 f2 = true;\n            }\n\n            if(f1 == false && f2 == false)\n                break;\n        }\n\n        return window;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string minWindow(string s, string t) {\n        unordered_map<char,int> ump;\n    for(auto i:t){\n        ump[i]++;\n    }\n\n    int i =0,j =0,count =0;\n    int ans =INT_MAX,answer =0;\n    for (;j < s.size();j++)\n    {\n        if(ump[s[j]]>0) {\n            count++;\n         }\n        ump[s[j]]--;\n        if(count==t.size()){\n\n            while (i < j && ump[s[i]]<0)\n            {\n                ump[s[i]]++;\n                i++;\n            }\n            if(ans > j-i+1){\n                ans  = j-i+1;\n                answer = i;\n            }\n            ump[s[i]]++;\n            i++;\n            count--;\n        }\n    }\n    return ans==INT_MAX?\"\":s.substr(answer,ans);\n    }\n};"
    },
    {
        "title": "Incremental Memory Leak",
        "algo_input": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.\n\nAt the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.\n\nReturn an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.\n\n&nbsp;\nExample 1:\n\nInput: memory1 = 2, memory2 = 2\nOutput: [3,1,0]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n\n\nExample 2:\n\nInput: memory1 = 8, memory2 = 11\nOutput: [6,0,4]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= memory1, memory2 &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def memLeak(self, memory1: int, memory2: int) -> List[int]:\n        \n        inverted = False \n        if memory2>memory1:\n            memory2, memory1 = memory1, memory2\n            inverted = True \n\n\t\t#Compute the number of steps in first stage - 1\n        i_start = solve_quadratic(1,2*(memory1-memory2))\n        \n        memory1-= i_start*(i_start+1)//2\n\t\t\n\t\tif memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion)\n            inverted = False \n       \n        #Compute number of steps in stage - 2\n        n_end = solve_quadratic((i_start+1), memory2)\n        \n\t\t#Compute sums of respective arithmetic sequences\n        i_end_1 = i_start - 1 + 2*n_end\n        i_end_2 = i_start + 2*n_end\n        \n        sum1 = n_end * (i_start+1 + i_end_1)//2\n        sum2 = n_end * (i_start+2 + i_end_2)//2\n        \n\t\t#Compute updated memories \n        memory1-=sum1\n        memory2-=sum2\n        \n        full_cnt=2*n_end+i_start\n        \n        if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it.\n            memory1-=(i_end_2+1)\n            full_cnt+=1\n            \n        return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2]\n            \n\t\t ```",
        "solution_js": "var memLeak = function(memory1, memory2) {\n    var count=1;\n    while(true)\n        {\n            if(memory1>=memory2 && memory1>=count)\n                memory1-=count;\n            else if(memory2>=memory1 && memory2>=count)\n                memory2-=count\n            else\n                return [count, memory1, memory2];\n            count++;\n        }\n};",
        "solution_java": "class Solution {\n    public int[] memLeak(int memory1, int memory2) {\n        int i = 1;\n        while(Math.max(memory1, memory2) >= i){\n            if(memory1 >= memory2)\n                memory1 -= i;\n            else\n                memory2 -= i;\n            i++;\n        }\n        return new int[]{i, memory1, memory2};\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> memLeak(int memory1, int memory2) {\n        int time = 1;\n        while (max(memory1, memory2) >= time) {\n            if (memory1 >= memory2) {\n                memory1 -= time;\n            } else {\n                memory2 -= time;\n            }\n            ++time;\n        }\n        return {time, memory1, memory2};\n    }\n};"
    },
    {
        "title": "Sliding Puzzle",
        "algo_input": "On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\n\nThe state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\n\nGiven the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n\n&nbsp;\nExample 1:\n\nInput: board = [[1,2,3],[4,0,5]]\nOutput: 1\nExplanation: Swap the 0 and the 5 in one move.\n\n\nExample 2:\n\nInput: board = [[1,2,3],[5,4,0]]\nOutput: -1\nExplanation: No number of moves will make the board solved.\n\n\nExample 3:\n\nInput: board = [[4,1,2],[5,0,3]]\nOutput: 5\nExplanation: 5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\tboard.length == 2\n\tboard[i].length == 3\n\t0 &lt;= board[i][j] &lt;= 5\n\tEach value board[i][j] is unique.\n\n",
        "solution_py": "class Solution:\n    def slidingPuzzle(self, board: List[List[int]]) -> int:\n        def findNei(board):\n            directs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n            boards = []\n            for i in range(2):\n                for j in range(3):\n                    if board[i][j] == 0:\n                        for dr, dc in directs:\n                            tmp = [row.copy() for row in board]\n                            r, c = i + dr, j + dc\n                            if r in range(2) and c in range(3):\n                                tmp[r][c], tmp[i][j] = tmp[i][j], tmp[r][c]\n                                boards.append(tmp)\n            return boards\n\n        visited = set()\n        target = [[1, 2, 3], [4, 5, 0]]\n        if board == target:\n            return 0\n        rows, cols = len(board), len(board[0])\n        q = collections.deque()\n        step = 1\n\n        for row in range(rows):\n            for col in range(cols):\n                if board[row][col] == 0:\n                    boards = findNei(board)\n                    for b in boards:\n                        if b == target:\n                            return step\n                        visited.add(tuple([tuple(row) for row in b]))\n                        q.append(b)\n                    break\n\n        while q:\n            step += 1\n            for _ in range(len(q)):\n                b = q.popleft()\n                boards = findNei(b)\n                for b in boards:\n                    if b == target:\n                        return step\n                    t = tuple([tuple(row) for row in b])\n                    if t not in visited:\n                        visited.add(t)\n                        q.append(b)\n\n        return -1",
        "solution_js": "/**\n * @param {number[][]} board\n * @return {number}\n */\n\nclass BoardState {\n    constructor(board, currStep) {\n        this.board = this.copyBoard(board);\n        this.boardString = this.flatToString(board);\n        this.emptyIndex = this.findIndexOf0(board);\n        this.currStep = currStep;\n    }\n    findIndexOf0(board) {\n        for(let i = 0; i < board.length; i++) {\n            for (let j = 0; j < board[i].length; j++) {\n                if(board[i][j] === 0) return [i, j];\n            }\n        }\n        return null;\n    }\n    copyBoard(board) {\n        const newBoard = [];\n        board.forEach((row) => {\n             newBoard.push([...row]);\n        });\n        return newBoard;\n    }\n    flatToString(board) {\n        let str = '';\n        for(let i = 0; i < board.length; i++) {\n            for (let j = 0; j < board[i].length; j++) {\n                str += board[i][j];\n            }\n        }\n        return str;\n    }\n}\nvar slidingPuzzle = function(board) {\n    let queue = [new BoardState(board, 0)];\n    let set = new Set();\n    const x = board.length, y = board[0].length;\n    const switchMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]];\n    let slide = (i, j, newi, newj, currBoardState) => {\n        if (newi < 0 || newj < 0 || newi >= x || newj >= y) {\n            return null;\n        }\n        const newBoard = currBoardState.copyBoard(currBoardState.board);\n        const temp = newBoard[i][j];\n        newBoard[i][j] = newBoard[newi][newj];\n        newBoard[newi][newj] = temp;\n        const newBoardState = new BoardState(newBoard, currBoardState.currStep + 1);\n        return newBoardState\n    }\n    while(queue.length > 0) {\n        const currBoardState = queue.shift();\n        set.add(currBoardState.boardString);\n        if(currBoardState.boardString === '123450') {\n            return currBoardState.currStep;\n        }\n        const [i, j] = currBoardState.emptyIndex;\n        switchMoves.forEach((move) => {\n            const newBoardState = slide(i, j, i + move[0], j + move[1], currBoardState);\n            if (newBoardState && !set.has(newBoardState.boardString)) {\n                queue.push(newBoardState);\n            }\n        });\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}};\n    public int slidingPuzzle(int[][] board) {\n\n        String tar=\"123450\";\n\n        String src=\"\";\n\n        for(int i =0;i<board.length;i++){\n            for(int j=0;j<board[i].length;j++){\n                src+=board[i][j];\n            }\n        }\n\n       HashSet<String> visited=new HashSet<>();\n\n        visited.add(src);\n        int level=0;\n        ArrayDeque<String> q=new ArrayDeque<>();\n        q.add(src);\n        while(q.size()!=0){\n            int t=q.size();\n\n            while(t-->0){\n                String rem=q.remove();\n\n                if(rem.equals(tar)){\n                    return level;\n                }\n\n                int idx=-1;\n\n                for(int i=0;i<rem.length();i++){\n                    if(rem.charAt(i)=='0'){\n                        idx=i;\n                        break;\n                    }\n                }\n\n                for(int i =0;i<dir[idx].length;i++){\n                    String str=swapEle(rem,idx,dir[idx][i]);\n\n                    if(!visited.contains(str)){\n                        q.add(str);\n                        visited.add(str);\n                    }\n                }\n            }\n            level++;\n        }\n\n        return -1;\n    }\n\n    public String swapEle(String rem,int i,int j){\n        StringBuilder sb=new StringBuilder(rem);\n\n        sb.setCharAt(i,rem.charAt(j));\n        sb.setCharAt(j,rem.charAt(i));\n\n        return sb.toString();\n    }\n}",
        "solution_c": "class Node{\npublic:\nint row;\nint col;\nvector<vector<int>>state;\n    };\n\nclass Solution {\npublic:\n\nint slidingPuzzle(vector<vector<int>>& board) {\n\n    vector<vector<int>>target={{1,2,3},{4,5,0}};\n    queue<Node>q;\n    int n=2;\n    int m=3;\n    vector<vector<int>>dir={{1,0},{-1,0},{0,1},{0,-1}};\n\n    for(int i=0;i<board.size();i++)\n        for(int j=0;j<board[0].size();j++){\n            if(board[i][j]==0){\n                q.push({i,j,board});\n                break;\n            }\n        }\n\n    set<vector<vector<int>>>set;\n    set.insert(q.front().state);\n    int ladder=0;\n    while(!q.empty()){\n       int size=q.size();\n        for(int i=0;i<size;i++){\n            Node curr=q.front();\n            q.pop();\n            if(curr.state==target)\n                return ladder;\n\n            int row=curr.row;\n            int col=curr.col;\n            for(auto &x:dir){\n                int r=x[0]+row;\n                int c=x[1]+col;\n\n                if(r<n && r>=0 && c<m && c>=0 ){\n                    swap(curr.state[r][c],curr.state[row][col]) ;\n                    if(set.find(curr.state)==set.end()){\n                        set.insert(curr.state);\n                        q.push({r,c,curr.state});\n                    }\n                     swap(curr.state[r][c],curr.state[row][col]) ;\n\n                }\n\n            }\n\n        }\n        ladder++;\n\n    }\n    return -1;\n\n}\n};"
    },
    {
        "title": "Gray Code",
        "algo_input": "An n-bit gray code sequence is a sequence of 2n integers where:\n\n\n\tEvery integer is in the inclusive range [0, 2n - 1],\n\tThe first integer is 0,\n\tAn integer appears no more than once in the sequence,\n\tThe binary representation of every pair of adjacent integers differs by exactly one bit, and\n\tThe binary representation of the first and last integers differs by exactly one bit.\n\n\nGiven an integer n, return any valid n-bit gray code sequence.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: [0,1,3,2]\nExplanation:\nThe binary representation of [0,1,3,2] is [00,01,11,10].\n- 00 and 01 differ by one bit\n- 01 and 11 differ by one bit\n- 11 and 10 differ by one bit\n- 10 and 00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n- 00 and 10 differ by one bit\n- 10 and 11 differ by one bit\n- 11 and 01 differ by one bit\n- 01 and 00 differ by one bit\n\n\nExample 2:\n\nInput: n = 1\nOutput: [0,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 16\n\n",
        "solution_py": "import math\nclass Solution(object):\n    def grayCode(self, n):\n        \"\"\"\n        :type n: int\n        :rtype: List[int]\n        \"\"\"\n        allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)]\n        grayCodes = [0]\n        for diff in allowedDiffs:\n            grayCodes += [code + diff for code in reversed(grayCodes)]\n        return grayCodes",
        "solution_js": "/**\n * @param {number} n\n * @return {number[]}\n */\nvar grayCode = function(n) {\n    return binaryToInt(dfs(n, ['0', '1']))\n};\n\nconst dfs = (n, arr) => {\n    if (n === 1) return arr\n\n    const revArr = [...arr].reverse()\n\n    addOneBefore('0', arr)\n    addOneBefore('1', revArr)\n\n    return dfs(n - 1, [...arr, ...revArr])\n}\n\nconst addOneBefore = (e, arr) => {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = e + arr[i]\n    }\n}\n\nconst binaryToInt = (arr) => {\n    for (let i = 0; i < arr.length; i++){\n        arr[i] = parseInt(arr[i], 2)\n    }\n    return arr\n}",
        "solution_java": "class Solution {\n    public List<Integer> grayCode(int n) {\n      ArrayList list=new ArrayList();\n       for(int i=0;i<(1<<n);i++){\n         list.add(i^(i>>1));\n       }\n         return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> grayCode(int n) {\n        vector<int> dp = {0,1};\n        int cnt = 1;\n        for(int i = 2; i < n+1; i++) {\n            int mod = pow(2, cnt);\n            int index = dp.size()-1;\n            while(index >= 0) {\n                dp.push_back(dp[index] + mod);\n                index--;\n            }\n            cnt++;\n        }\n        return dp;\n    }\n};"
    },
    {
        "title": "Broken Calculator",
        "algo_input": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:\n\n\n\tmultiply the number on display by 2, or\n\tsubtract 1 from the number on display.\n\n\nGiven two integers startValue and target, return the minimum number of operations needed to display target on the calculator.\n\n&nbsp;\nExample 1:\n\nInput: startValue = 2, target = 3\nOutput: 2\nExplanation: Use double operation and then decrement operation {2 -&gt; 4 -&gt; 3}.\n\n\nExample 2:\n\nInput: startValue = 5, target = 8\nOutput: 2\nExplanation: Use decrement and then double {5 -&gt; 4 -&gt; 8}.\n\n\nExample 3:\n\nInput: startValue = 3, target = 10\nOutput: 3\nExplanation: Use double, decrement and double {3 -&gt; 6 -&gt; 5 -&gt; 10}.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= startValue, target &lt;= 109\n\n",
        "solution_py": "class Solution(object):\n    def brokenCalc(self, startValue, target):\n        \"\"\"\n        :type startValue: int\n        :type target: int\n        :rtype: int\n        \"\"\"\n        res = 0\n        while target > startValue:\n            res += 1\n            if target % 2:\n                target += 1\n            else:\n                target //= 2\n        return res + startValue - target",
        "solution_js": "/**\n * @param {number} startValue\n * @param {number} target\n * @return {number}\n */\nvar brokenCalc = function(startValue, target) {\n    let steps = 0;\n\n    while(target !== startValue){\n\n        if(startValue > target){\n            return steps + startValue - target;\n        }\n        if(target %2 === 0){\n            target /= 2;\n        }else {\n            target += 1;\n\n        }\n        steps++;\n    }\n    return steps\n};",
        "solution_java": "class Solution {\n    public int brokenCalc(int startValue, int target) {\n        if(startValue >= target) return startValue - target;\n        if(target % 2 == 0){\n            return 1 + brokenCalc(startValue, target / 2);\n        }\n        return 1 + brokenCalc(startValue, target + 1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int brokenCalc(int startValue, int target) {\n        int result=0;\n        while(target>startValue)\n        {\n            result++;\n            if(target%2==0)\n                target=target/2;\n            else\n                target+=1;\n        }\n        result=result+(startValue-target);\n        return result;\n    }\n};"
    },
    {
        "title": "Maximum Swap",
        "algo_input": "You are given an integer num. You can swap two digits at most once to get the maximum valued number.\n\nReturn the maximum valued number you can get.\n\n&nbsp;\nExample 1:\n\nInput: num = 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\n\n\nExample 2:\n\nInput: num = 9973\nOutput: 9973\nExplanation: No swap.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 108\n\n",
        "solution_py": "class Solution:\n    def maximumSwap(self, num: int) -> int:\n        digits = [int(x) for x in str(num)]\n        n = len(digits)\n        \n        for i in range(n):\n            maxx = digits[i]\n            indx = i\n            \n            for j in range(i+1,n):\n                if digits[j]>=maxx and digits[j]!=digits[i]:\n                    maxx = digits[j]\n                    indx = j\n                                        \n            if indx!=i:\n                digits[i],digits[indx] = digits[indx],digits[i]\n                    \n                #only one swap allowed\n                return \"\".join([str(x) for x in digits])\n                \n        #already sorted\n        return num",
        "solution_js": "var maximumSwap = function(num) {\n\tconst nums = `${num}`.split('');\n\n\tfor (let index = 0; index < nums.length - 1; index++) {\n\t\tconst current = nums[index];\n\t\tconst diff = nums.slice(index + 1);\n\t\tconst max = Math.max(...diff);\n\n\t\tif (current >= max) continue;\n\t\tconst swapIndex = index + diff.lastIndexOf(`${max}`) + 1;\n\t\t[nums[index], nums[swapIndex]] = [nums[swapIndex], nums[index]];\n\t\tbreak;\n\t}\n\treturn nums.join('');\n};",
        "solution_java": "class Solution {\n    public int maximumSwap(int num) {\n        char str[]=String.valueOf(num).toCharArray();\n        char arr[]=str.clone();\n        Arrays.sort(arr);\n        int i=0;\n        int j=str.length-1;\n        while(i<str.length && j>=0 && arr[j]==str[i]){i++;j--;}\n        int search=j;\n        if(i==str.length) return num;\n        j=str.length-1;\n        while(arr[search]!=str[j]){j--;}\n\n        char c=str[i];\n        str[i]=str[j];\n        str[j]=c;\n        return Integer.parseInt(new String(str));\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumSwap(int num) {\n        string st_n=to_string(num);\n        int maxNum=-1,maxIdx=-1;\n        int leftidx=-1,rightidx=-1;\n        for(int i=st_n.size()-1;i>=0;i--)\n        {\n            if(st_n[i]>maxNum)\n            {\n                maxNum=st_n[i];\n                maxIdx=i;\n                continue;\n            }\n\n            if(st_n[i]<maxNum)\n            {\n                leftidx=i;\n                rightidx=maxIdx;\n            }\n        }\n        if(leftidx==-1)\n            return num;\n\n        swap(st_n[leftidx],st_n[rightidx]);\n        return stoi(st_n);\n    }\n};"
    },
    {
        "title": "Odd Even Linked List",
        "algo_input": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.\n\nThe first node is considered odd, and the second node is even, and so on.\n\nNote that the relative order inside both the even and odd groups should remain as it was in the input.\n\nYou must solve the problem&nbsp;in O(1)&nbsp;extra space complexity and O(n) time complexity.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4,5]\nOutput: [1,3,5,2,4]\n\n\nExample 2:\n\nInput: head = [2,1,3,5,6,4,7]\nOutput: [2,3,6,7,1,5,4]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the linked list is in the range [0, 104].\n\t-106 &lt;= Node.val &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        if head is None:\n            return \n        odd, even_start, even = head, head.next, head.next\n        while odd is not None and even is not None:\n            odd.next = even.next\n            if odd.next is not None:\n                odd = odd.next\n                even.next = odd.next\n                even = even.next\n            else:\n                break\n        odd.next = even_start\n        return head",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar oddEvenList = function(head) {\n    if (!head || !head.next) return head;\n    let oddNode = head;\n    const evenHead = head.next;\n    let evenNode = head.next;\n    \n    while(evenNode?.next) {\n        oddNode.next = evenNode.next;\n        oddNode = oddNode.next;\n        evenNode.next = oddNode.next;\n        evenNode = evenNode.next;\n    }\n    \n    oddNode.next = evenHead;\n    \n    return head;\n};",
        "solution_java": "class Solution {\n    public ListNode oddEvenList(ListNode head) {\n        if(head == null) {\n            return head;\n        }\n        ListNode result = head, evenHalf = new ListNode(0), evenHalfPtr = evenHalf;\n        for(; head.next != null; head = head.next) {\n            evenHalfPtr = evenHalfPtr.next = head.next;\n            head.next = head.next.next;\n            evenHalfPtr.next = null;\n            if(head.next == null) {\n                break;\n            }\n        }\n        head.next = evenHalf.next;\n        return result;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode* oddEvenList(ListNode* head) {\n        if(head == NULL || head->next == NULL || head->next->next == NULL){\n            return head;\n        }\n        ListNode *first = head;\n        ListNode *second = head->next;\n        ListNode *last = head;\n        int count = 1;\n        while(last->next != NULL){\n            last = last->next;\n            count++;\n        }\n\n        int n = count/2;\n        while(n != 0){\n            first->next = second->next;\n            last->next = second;\n            second->next = NULL;\n            first = first->next;\n            last = second;\n            second = first->next;\n            n--;\n        }\n        return head;\n    }\n};"
    },
    {
        "title": "Richest Customer Wealth",
        "algo_input": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.\n\nA customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.\n\n&nbsp;\nExample 1:\n\nInput: accounts = [[1,2,3],[3,2,1]]\nOutput: 6\nExplanation:\n1st customer has wealth = 1 + 2 + 3 = 6\n2nd customer has wealth = 3 + 2 + 1 = 6\nBoth customers are considered the richest with a wealth of 6 each, so return 6.\n\n\nExample 2:\n\nInput: accounts = [[1,5],[7,3],[3,5]]\nOutput: 10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.\n\nExample 3:\n\nInput: accounts = [[2,8,7],[7,1,3],[1,9,5]]\nOutput: 17\n\n\n&nbsp;\nConstraints:\n\n\n\tm ==&nbsp;accounts.length\n\tn ==&nbsp;accounts[i].length\n\t1 &lt;= m, n &lt;= 50\n\t1 &lt;= accounts[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def maximumWealth(self, accounts: List[List[int]]) -> int:\n        return max(map(sum, accounts))",
        "solution_js": "var maximumWealth = function(accounts) {\n        var res = 0;\n        for(var i =0;i<accounts.length;i++){\n            var temp = 0;\n            for(var j = 0;j<accounts[i].length;j++){\n                temp+=accounts[i][j];\n            }\n            res = Math.max(res,temp);\n        }\n        return res;\n};",
        "solution_java": "class Solution {\n    public int maximumWealth(int[][] accounts) {\n        int res = 0;\n        for(int i =0;i<accounts.length;i++){\n            int temp = 0;\n            for(int j = 0;j<accounts[i].length;j++){\n                temp+=accounts[i][j];\n            }\n            res = Math.max(res,temp);\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maximumWealth(vector<vector<int>>& accounts) {\n           int maxWealth = 0;\n        for (auto account : accounts) {\n            int currentSum = 0;\n            for (int x : account) currentSum += x;\n            if (currentSum > maxWealth) maxWealth = currentSum;\n        }\n        return maxWealth;\n    }\n};"
    },
    {
        "title": "Longest Binary Subsequence Less Than or Equal to K",
        "algo_input": "You are given a binary string s and a positive integer k.\n\nReturn the length of the longest subsequence of s that makes up a binary number less than or equal to k.\n\nNote:\n\n\n\tThe subsequence can contain leading zeroes.\n\tThe empty string is considered to be equal to 0.\n\tA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"1001010\", k = 5\nOutput: 5\nExplanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.\n\n\nExample 2:\n\nInput: s = \"00101001\", k = 1\nOutput: 6\nExplanation: \"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts[i] is either '0' or '1'.\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def longestSubsequence(self, s: str, k: int) -> int:\n    \n        end, n  = len(s)-1, s.count(\"0\")    \n        while end >=0 and  int(s[end:], 2)<= k:\n            end-=1\n        return n+ s[end+1:].count(\"1\")\n        ",
        "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\n\nvar longestSubsequence = function(s, k) {\n    let count = 0;\n    let j = s.length - 1; // starting from the last digit\n    let i = 0; // binary number position\n    let acc = 0;\n\n    while(j >= 0){\n        let positionNumber = Number(s[j]) * Math.pow(2, i);\n        j--;\n        i++;\n        if(acc + positionNumber > k) continue;\n\n        acc += positionNumber;\n        count++;\n    }\n\n    return count;\n};",
        "solution_java": "class Solution {\n    public int longestSubsequence(String s, int k) {\n        int numOfZeros = 0;\n        int numOfOnes = 0;\n        \n        for(int i = 0; i < s.length(); i++){\n            char ch = s.charAt(i);\n            if(ch == '0'){\n                numOfZeros++;\n            }\n        }\n        int sum = 0;\n        for(int i = s.length() - 1; i >= 0; i--){\n            char ch = s.charAt(i);\n            if(ch == '1'){\n                double val = Math.pow(2, s.length() - i - 1);\n                sum += val;\n                if(sum <= k){\n                    numOfOnes++;\n                }\n            }\n        }\n        return numOfZeros + numOfOnes;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int ans = 0;\n    int f(int i,int size, int sum, string &s, vector<vector<int>>&dp){\n        if(i<0){\n            return 0;\n        }\n        if(dp[i][size] != -1){\n            return dp[i][size];\n        }\n        int no = f(i-1,size,sum,s,dp);\n        int yes = 0;\n        if((sum-(s[i]-'0')*pow(2,size)) >=0){\n            yes = 1+ f(i-1,size+1,(sum-(s[i]-'0')*pow(2,size)),s,dp);\n        }\n        return dp[i][size]=max(no,yes);\n    }\n    int longestSubsequence(string s, int k) {\n\n        int n = s.size();\n        vector<vector<int>>dp(n,vector<int>(n,-1));\n        return f(n-1,0,k,s,dp);\n\n    }\n};"
    },
    {
        "title": "Defanging an IP Address",
        "algo_input": "Given a valid (IPv4) IP address, return a defanged version of that IP address.\n\nA defanged&nbsp;IP address&nbsp;replaces every period \".\" with \"[.]\".\n\n&nbsp;\nExample 1:\nInput: address = \"1.1.1.1\"\nOutput: \"1[.]1[.]1[.]1\"\nExample 2:\nInput: address = \"255.100.50.0\"\nOutput: \"255[.]100[.]50[.]0\"\n\n&nbsp;\nConstraints:\n\n\n\tThe given address is a valid IPv4 address.\n",
        "solution_py": "class Solution:\n\tdef defangIPaddr(self, address: str) -> str:\n\t\treturn address.replace('.', '[.]')",
        "solution_js": "var defangIPaddr = function(address) {\n   return address.split(\"\").map((x)=>{\n        if(x=='.')\n            return \"[.]\"\n        else return x\n    }).join(\"\")\n};",
        "solution_java": "class Solution {\n    public String defangIPaddr(String address) {\n        return address.replace(\".\",\"[.]\");\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string defangIPaddr(string address) {\n     string res;\n        for(int i=0;i<address.length();i++){\n         if(address[i]=='.'){\n             res+=\"[.]\";\n\n         }\n        else{\n                res+=address[i];\n            }\n     }\n        return res;\n    }\n};"
    },
    {
        "title": "Determine if String Halves Are Alike",
        "algo_input": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.\n\nTwo strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.\n\nReturn true if a and b are alike. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"book\"\nOutput: true\nExplanation: a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\n\n\nExample 2:\n\nInput: s = \"textbook\"\nOutput: false\nExplanation: a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 1000\n\ts.length is even.\n\ts consists of uppercase and lowercase letters.\n\n",
        "solution_py": "vowels = \"aeiouAEIOU\"\n\nclass Solution:\n    def halvesAreAlike(self, S: str) -> bool:\n        mid, ans = len(S) // 2, 0\n        for i in range(mid):\n            if S[i] in vowels: ans += 1\n            if S[mid+i] in vowels: ans -=1\n        return ans == 0",
        "solution_js": "var halvesAreAlike = function(s) {\n    let isVowel = [\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"];\n    let count = 0;\n    for (let i = 0; i < s.length / 2; i++) {\n        if (isVowel.indexOf(s[i]) !== -1) {\n            count++;\n        }\n    }\n    for (let i = s.length / 2; i < s.length; i++) {\n        if (isVowel.indexOf(s[i]) !== -1) {\n            count--;\n        }\n    }\n    return count === 0;\n};",
        "solution_java": "class Solution {\n    public boolean halvesAreAlike(String s) {\n        //add vowels to the set\n        Set<Character> set = new HashSet<>();\n        set.add('a');\n        set.add('e');\n        set.add('i');\n        set.add('o');\n        set.add('u');\n        set.add('A');\n        set.add('E');\n        set.add('I');\n        set.add('O');\n        set.add('U');\n\n        //find the mid\n        int mid = s.length() / 2;\n        int count = 0;\n        //increment the count for left half, decrement count for the second half if its a vowel\n        for (int i = 0; i < s.length(); i++)\n            count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0;\n        //finally count should be 0 to match left and right half\n        return count == 0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool halvesAreAlike(string s) {\n        unordered_set<char> set = {'a', 'e', 'i', 'o', 'u','A','I','E','O','U'};\n        int i=0,j=s.size()/2,cnt=0;\n        while(j<s.size()){\n            if(set.find(s[i])!=set.end()) cnt++;\n            if(set.find(s[j])!=set.end()) cnt--;\n            i++;\n            j++;\n        }\n        return cnt==0;\n    }\n};"
    },
    {
        "title": "All Paths From Source to Target",
        "algo_input": "Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.\n\nThe graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).\n\n&nbsp;\nExample 1:\n\nInput: graph = [[1,2],[3],[3],[]]\nOutput: [[0,1,3],[0,2,3]]\nExplanation: There are two paths: 0 -&gt; 1 -&gt; 3 and 0 -&gt; 2 -&gt; 3.\n\n\nExample 2:\n\nInput: graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n\n\n&nbsp;\nConstraints:\n\n\n\tn == graph.length\n\t2 &lt;= n &lt;= 15\n\t0 &lt;= graph[i][j] &lt; n\n\tgraph[i][j] != i (i.e., there will be no self-loops).\n\tAll the elements of graph[i] are unique.\n\tThe input graph is guaranteed to be a DAG.\n\n",
        "solution_py": "class Solution:\n    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n        res = []\n        self.explore(graph, graph[0], [0], res)\n        return res\n    \n    def explore(self, graph, candidates, step, res):\n        if step[-1] == len(graph)-1:\n            res.append(list(step))\n        else:\n            for i in range(len(candidates)):\n                step.append(candidates[i])\n                self.explore(graph, graph[candidates[i]], step, res)\n                step.pop()",
        "solution_js": "/**\n * @param {number[][]} graph\n * @return {number[][]}\n */\nconst allPathsSourceTarget = function(graph) {\n    const n = graph.length;\n    const result = [];\n    const dfs = (node, path) => {\n        if (node === n-1) {\n            result.push([...path, node]); // Add the current path to the result if we have reached the target node\n            return;\n        }\n        for (const neighbor of graph[node]) {\n            dfs(neighbor, [...path, node]); // Recursively explore all neighbors of the current node\n        }\n    };\n    dfs(0, []); // Start the DFS from the source node\n    return result;\n};",
        "solution_java": "Approach : Using dfs+ backtracking we can solve it\t\n\t\n\tclass Solution {\n\t\tpublic List<List<Integer>> allPathsSourceTarget(int[][] graph) {\n\t\t\tList<List<Integer>> ans=new ArrayList<>();\n\t\t\tList<Integer> temp=new ArrayList<>();\n\t\t\t boolean []visit=new boolean [graph.length];\n\t\t\thelper(graph,0,graph.length-1,ans,temp,visit);\n\n\t\t\treturn ans;\n\t\t}\n\t\tpublic void helper(int[][] graph, int src,int dest,List<List<Integer>> ans,List<Integer> temp,boolean[]vis)\n\t\t{\n\n\t\t\tvis[src]=true;\n\t\t\ttemp.add(src);\n\t\t\tif(src==dest)\n\t\t\t{\n\t\t\t\tList<Integer> b =new ArrayList<>();\n\t\t\t\tfor(int h:temp){\n\t\t\t\t\tb.add(h);\n\t\t\t\t}\n\t\t\t\tans.add(b);\n\t\t\t}\n\n\t\t\tfor(int i:graph[src])\n\t\t\t{\n\t\t\t\tif(vis[i]!=true)\n\t\t\t\t{\n\t\t\t\t\thelper(graph,i,dest,ans,temp,vis);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tvis[src]=false;\n\t\t\ttemp.remove(temp.size()-1);\n\t\t}\n\t}",
        "solution_c": "class Solution {\npublic:\n    // setting a few class variables, so that we do not have to pass them down all the time in the recursive dfs calls\n    int target;\n    vector<vector<int>> res;\n    vector<int> tmp;\n    void dfs(vector<vector<int>>& graph, int currNode = 0) {\n\t    // updating tmp\n        tmp.push_back(currNode);\n\t\t// and either updating res with it if target is met\n        if (currNode == target) res.push_back(tmp);\n\t\t// or callling dfs again recursively\n        else for (int node: graph[currNode]) {\n            dfs(graph, node);\n        }\n        // backtracking with tmp\n\t\ttmp.pop_back();\n    }\n    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {\n        target = graph.size() - 1;\n        dfs(graph);\n        return res;\n    }\n};"
    },
    {
        "title": "Simplified Fractions",
        "algo_input": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\n\n\nExample 2:\n\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\n\n\nExample 3:\n\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def simplifiedFractions(self, n: int) -> List[str]:\n        \n        collect = {}\n        for b in range(2, n+1):\n            for a in range(1, b):\n                if a/b not in collect:\n                    collect[a/b] = f\"{a}/{b}\"  \n        return list(collect.values())",
        "solution_js": "var simplifiedFractions = function(n) {\n    const res = [];\n    const checkValid = (a, b) => {\n        if(a === 1) return 1;\n        let num = 2;\n        while(num <= a) {\n            if(b % num === 0 && a % num === 0) return num;\n            num++;\n        }\n        return 1;\n    }\n    let i = 1;\n    while(i / n < 1) {\n        let j = i + 1;\n        while(j <= n) {\n            if(checkValid(i, j) < 2) {\n                res.push(`${i}/${j}`); \n            }\n            j++;\n        }\n        i++;\n    }\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<String> simplifiedFractions(int n) {\n        List<String> list = new ArrayList<>() ;\n\n        for(int numerator = 1; numerator< n ; numerator++) {\n            for(int denominator = numerator+1; denominator<=n; denominator++) {\n                if(gcd(numerator,denominator) == 1) {\n                    list.add(numerator+\"/\"+denominator);\n// System.out.println(numerator+\"/\"+denominator);\n                }\n            }\n        }\n        return list ;\n    }\n\n    static int gcd(int a, int b)\n    {\n// euclidean algo\n\n        if(a==0) {\n            return b ;\n        }\n        return gcd(b%a,a);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool simplified(int n, int i){\n        while(i>0){\n            n-=i;\n            if(i>n)swap(n,i);\n        }\n        if(n>1) return false;\n        else return true;\n    }\n\n    vector<string> simplifiedFractions(int n) {\n        vector<string> ans;\n        while(n>1){\n            int i=1;\n            while(i<n){\n                if(simplified(n, i)){\n                    string fraction;\n                    int num=i;\n                    while(num>0){\n                        fraction.push_back(num%10+'0');\n                        num/=10;\n                    }\n                    fraction.push_back('/');\n                    num = n;\n                    while(num>0){\n                        fraction.push_back(num%10+'0');\n                        num/=10;\n                    }\n                    if(i>9) swap(fraction[0],fraction[1]);\n                    if(n>99) swap(fraction[fraction.size()-1],fraction[fraction.size()-3]);\n                    else if(n>9) swap(fraction[fraction.size()-1],fraction[fraction.size()-2]);\n                    ans.push_back(fraction);\n                }\n                i++;\n            }\n            n--;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Isomorphic Strings",
        "algo_input": "Given two strings s and t, determine if they are isomorphic.\n\nTwo strings s and t are isomorphic if the characters in s can be replaced to get t.\n\nAll occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.\n\n&nbsp;\nExample 1:\nInput: s = \"egg\", t = \"add\"\nOutput: true\nExample 2:\nInput: s = \"foo\", t = \"bar\"\nOutput: false\nExample 3:\nInput: s = \"paper\", t = \"title\"\nOutput: true\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 104\n\tt.length == s.length\n\ts and t consist of any valid ascii character.\n\n",
        "solution_py": "class Solution:\n    def isIsomorphic(self, s: str, t: str) -> bool:\n        dict1={}\n        m=\"\"\n\t\t#creating a dictionary by mapping each element from string S to string T\n        for i,j in zip(s,t):\n\t\t# this for the cases like \"badc\" and \"baba\" so we dont want two keys mapping to same value hence we can reject directly\n            if j in dict1.values() and i not in dict1.keys():\n                return False\n            dict1[i]=j          \n        \n\t\t#now take each letter from string s and using dictionary values replace it with that specific character\n        for k in s:\n            m=m+dict1[k]\n\t\t\t\n\t\t#now if newly formed string m == T is same then the strings are Isomorphic\n        if(m==t):\n            return True\n        else:\n            return False",
        "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isIsomorphic = function(s, t) {\n    const obj = {};\n    const setValues = new Set();\n    let isIso = true;\n\n    for(var indexI=0; indexI<s.length;indexI++) {\n       if(obj[s[indexI]] || setValues.has(t[indexI])) {\n            if (obj[s[indexI]] === t[indexI]) continue;\n\n            isIso= false;\n            break;\n       }\n       else {\n           obj[s[indexI]] = t[indexI];\n        setValues.add(t[indexI]);\n       }\n    }\n\n    return isIso;\n};",
        "solution_java": "class Solution {\n    public boolean isIsomorphic(String s, String t) {\n        \n        ArrayList<Integer>list1 = new ArrayList<>();\n        ArrayList<Integer>list2 = new ArrayList<>();\n        for(int i=0;i<s.length();i++){\n            list1.add(s.lastIndexOf(s.charAt(i)));\n            list2.add(t.lastIndexOf(t.charAt(i)));\n        }\n        \n        if(list1.equals(list2)){\n            return true;\n        }\n        else{\n            return false;\n        }\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isIsomorphic(string s, string t) {\n        if(s.size()!=t.size()) return false;\n        unordered_map<char,char>mp;\n        for(int i=0;i<s.size();i++){\n            if(mp.find(s[i])==mp.end()){\n                for(auto it:mp){\n                    if(it.second==t[i])return false;\n                }\n                mp[s[i]]=t[i];\n            }\n            else{\n                if(mp[s[i]]!=t[i]) return false;\n\n            }\n\n        }\n        return true;\n\n    }\n};"
    },
    {
        "title": "Maximum Distance Between a Pair of Values",
        "algo_input": "You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​.\n\nA pair of indices (i, j), where 0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; nums2.length, is valid if both i &lt;= j and nums1[i] &lt;= nums2[j]. The distance of the pair is j - i​​​​.\n\nReturn the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\n\nAn array arr is non-increasing if arr[i-1] &gt;= arr[i] for every 1 &lt;= i &lt; arr.length.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput: 2\nExplanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).\n\n\nExample 2:\n\nInput: nums1 = [2,2,2], nums2 = [10,10,1]\nOutput: 1\nExplanation: The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).\n\n\nExample 3:\n\nInput: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput: 2\nExplanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 105\n\t1 &lt;= nums1[i], nums2[j] &lt;= 105\n\tBoth nums1 and nums2 are non-increasing.\n\n",
        "solution_py": "class Solution:\n    def maxDistance(self, n1: List[int], n2: List[int]) -> int:\n        i = j = res = 0\n        while i < len(n1) and j < len(n2):\n            if n1[i] > n2[j]:\n                i += 1\n            else:\n                res = max(res, j - i)\n                j += 1\n        return res",
        "solution_js": "var maxDistance = function(nums1, nums2) {\n    let i = 0, j = 0;\n    \n    let ans = 0;\n    while (i < nums1.length && j < nums2.length) {\n        // maintain the i <= j invariant\n        j = Math.max(j, i);\n        \n        // we want to maximize j so move it forward whenever possible\n        while (nums1[i] <= nums2[j]) {\n            ans = Math.max(ans, j - i);\n            j++;\n        }\n        \n        // we want to minimize i so move it forward only to maintain invariants\n        i++;\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxDistance(int[] nums1, int[] nums2) {\n        int max = 0;\n        for (int i = 0; i < nums1.length; i++) {\n            int r = nums2.length - 1;\n            int l = i;\n            int m = i;\n            while (l <= r) {\n                m = l + (r - l) / 2;\n                if (nums1[i] > nums2[m]) {\n                    r = m - 1;\n                } else if (nums1[i] == nums2[m]) {\n                    l = m + 1;\n                } else {\n                    l = m + 1;\n                }\n            }\n            if (r < 0) {\n                continue;\n            }\n            max = Math.max(max, r - i);\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDistance(vector<int>& nums1, vector<int>& nums2) {\n\n        reverse(nums2.begin(),nums2.end());\n        int ans = 0;\n        for(int i=0;i<nums1.size();++i){\n            auto it = lower_bound(nums2.begin(),nums2.end(),nums1[i]) - nums2.begin(); //Finds first element greater than or equal to nums1[i]\n            int j = nums2.size() - 1 - it; //Index of the found element in the original array\n            if(i<=j) ans = max(ans,j-i); //Update distance\n        }\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Sell Diminishing-Valued Colored Balls",
        "algo_input": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.\n\nThe customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color&nbsp;you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).\n\nYou are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.\n\nReturn the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: inventory = [2,5], orders = 4\nOutput: 14\nExplanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.\n\n\nExample 2:\n\nInput: inventory = [3,5], orders = 6\nOutput: 19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= inventory.length &lt;= 105\n\t1 &lt;= inventory[i] &lt;= 109\n\t1 &lt;= orders &lt;= min(sum(inventory[i]), 109)\n\n",
        "solution_py": "class Solution:\n    def maxProfit(self, inventory: List[int], orders: int) -> int:\n        inventory.sort(reverse=True) \n        inventory += [0]\n        res = 0\n        k = 1\n        \n        for i in range(len(inventory)-1): \n            if inventory[i] > inventory[i+1]: \n                if k*(inventory[i]-inventory[i+1]) < orders:\n                    diff = inventory[i]-inventory[i+1]\n                    res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2\n                    orders -= k*diff\n                else: \n                    q, r = divmod(orders, k)\n                    res += k*(inventory[i]+(inventory[i]-q+1))*q//2\n                    res += r*(inventory[i]-q)\n                    return res%(10**9+7)\n            k += 1",
        "solution_js": "var maxProfit = function(A, k) {\n    //rangeSum Formula\n    let rangesum=(i,j)=>{\n        i=BigInt(i),j=BigInt(j)\n        return ((j*((j+1n))/2n)-(i*(i+1n)/2n))\n    }\n    A.unshift(0) //prepend the sentinel 0 \n    A.sort((a,b)=>a-b)\n    let n=A.length,result=0n,mod=BigInt(1e9+7),i=n-1\n    // can use all current levels\n    while((k>=(n-i)*(A[i]-A[i-1]))&&i>0){\n        if(A[i]!=A[i-1])\n            result=(result+(rangesum(A[i-1],A[i])*BigInt(n-i)))%mod,\n            k-=(n-i)*(A[i]-A[i-1])\n        i--\n    }\n    //can use some of the current levels\n    if(k>0&&k>=n-i){\n        let levels=Math.floor(k/(n-i)) //the levels i can use \n        result=(result+(BigInt(n-i)*rangesum(A[i]-levels,A[i])))%mod\n        k-=levels*(n-i)\n        A[i]-=levels\n    }\n    // can use some of the items OF the first level\n    if(k>0&&k<n-i)\n        result=(result+BigInt(k)*BigInt(A[i]))%mod\n    return Number(result)\n};",
        "solution_java": "class Solution {\n    private long mod = 1000000007L;\n    public int maxProfit(int[] inventory, int orders) {\n\t\t// we use pq to find the most balls\n        PriorityQueue<Long> pq = new PriorityQueue<>((x, y) -> Long.compare(y, x));\n        pq.offer(0L);\n\t\t\n        // we use map to count the balls\n        Map<Long, Long> map = new HashMap<>();\n        map.put(0L, 0L);\n        \n        for (int j : inventory) {\n            long i = (long)j;\n            if (map.containsKey(i)) {\n                map.put(i, map.get(i) + 1);\n            }\n            else {\n                pq.offer(i);\n                map.put(i, 1L);\n            }\n        }\n        \n        long res = 0;\n        while (orders > 0) {\n            long ball = pq.poll(), nextBall = pq.peek();\n            long times = map.get(ball);\n            long diff = Math.min(ball - nextBall, orders / times);\n            if (diff == 0) {\n                res = (res + orders * ball) % mod;\n                break;\n            }\n            long sum = (ball * 2 + 1 - diff) * diff / 2 * times;\n            res = (res + sum) % mod;\n            orders -= diff * times;\n            if (!map.containsKey(ball - diff)) {\n                map.put(ball - diff, map.get(ball));\n                pq.offer(ball - diff);\n            }\n            else {\n                map.put(ball - diff, map.get(ball - diff) + map.get(ball));\n            }\n            map.remove(ball);\n        }\n        return (int) res;\n    }\n}",
        "solution_c": "#define ll long long\nconst int MOD = 1e9+7; \n\nclass Solution {\npublic:\n    \n    ll summation(ll n) {\n        return (n*(n+1)/2);\n    }\n    \n    int maxProfit(vector<int>& inventory, int orders) {\n        ll n = inventory.size(), i = 0, ans = 0;\n        inventory.push_back(0);\n        sort(inventory.rbegin(), inventory.rend());\n        while(orders and i < n) {\n            if(inventory[i] != inventory[i+1]) {\n                ll width = i+1, h = inventory[i] - inventory[i+1];\n                ll available = width * h, gain = 0;\n                if(available <= orders) {\n                    orders -= available;\n\t\t\t\t\t// from each of the first i+1 inventories, we gain (inventory[i+1] + 1) + ... + inventory[i] value\n                    gain = (width * (summation(inventory[i]) - summation(inventory[i+1]))) % MOD; \n                } else {\n                    ll q = orders / width, r = orders % width;\n\t\t\t\t\t// q balls picked from each of the first i+1 inventories\n                    gain = (width * (summation(inventory[i]) - summation(inventory[i]-q))) % MOD;\n\t\t\t\t\t// 1 ball picked from r inventories providing value (inventory[i]-q)\n                    gain = (gain + r*(inventory[i]-q)) % MOD;\n                    orders = 0;\n                }\n                \n                ans = (ans + gain) % MOD; \n            }\n            \n            i++;\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Shortest Path in a Grid with Obstacles Elimination",
        "algo_input": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.\n\nReturn the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput: 6\nExplanation: \nThe shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -&gt; (0,1) -&gt; (0,2) -&gt; (1,2) -&gt; (2,2) -&gt; (3,2) -&gt; (4,2).\n\n\nExample 2:\n\nInput: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput: -1\nExplanation: We need to eliminate at least two obstacles to find such a walk.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 40\n\t1 &lt;= k &lt;= m * n\n\tgrid[i][j] is either 0 or 1.\n\tgrid[0][0] == grid[m - 1][n - 1] == 0\n\n",
        "solution_py": "class Solution:\n    def shortestPath(self, grid: List[List[int]], k: int) -> int:\n        Q = [[0, 0, k]] # m, n, remaining elimination quota \n        rows, cols = len(grid), len(grid[0])\n        V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited\n        \n        while Q: \n            frontier = []\n            for m, n, rem in Q: \n                if m == rows - 1 and n == cols - 1: \n                    return counter \n                for dm, dn in [[1, 0], [-1, 0], [0, 1], [0, -1]]: \n                    if 0 <= m+dm < rows and 0 <= n+dn < cols: # check inbound \n                        if grid[m+dm][n+dn] == 0: \n                            if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem: # if not visited or could be visited with fewer elimination \n                                frontier.append([m+dm, n+dn, rem])\n                                V[(m+dm, n+dn)] = rem\n                        elif rem > 0: # I see a wall and I can still eliminate\n                            if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem - 1: # if not visited or could be visited with fewer elimination \n                                frontier.append([m+dm, n+dn, rem-1])\n                                V[(m+dm, n+dn)] = rem - 1\n            Q = frontier \n            counter += 1\n                \n        return -1\n\t```",
        "solution_js": "var shortestPath = function(grid, k) {\n    const dir = [[-1, 0], [1, 0], [0, -1], [0, 1]];\n    const m = grid.length;\n    const n = grid[0].length;\n         \n    let q = [[0,0,k]];\n    const visited = new Set();\n    visited.add(`0:0:${k}`);\n    let cnt = 0;\n    while(q.length>0)\n    {\n        const size  = q.length;\n        for(let i = 0; i<size; i++)\n        {\n            let [x, y, ob] = q.shift();\n            if(x === m-1 && y === n-1) {\n                return cnt;\n            }\n            for(const d of dir)\n            {\n                const xx = d[0] + x;\n                const yy = d[1] + y;\n                if(xx>=0 && xx<m && yy>=0 && yy<n)\n                {\n                    const newK = grid[xx][yy] === 1 ? ob-1 : ob;\n                    if(newK >=0 && !visited.has(`${xx}:${yy}:${newK}`) )\n                    {\n                        q.push([xx, yy, newK]);\n                        visited.add(`${xx}:${yy}:${newK}`);\n                    }\n                }\n            }\n        }\n        cnt++;\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    int rowLen = 0;\n    int colLen = 0;\n    int MAXVAL = 0;\n    public int shortestPath(int[][] grid, int k) {\n        rowLen = grid.length;\n        colLen = grid[0].length;\n        MAXVAL = rowLen * colLen + 1;\n        int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k+1][4]);\n        return path == MAXVAL ? -1 : path;\n    }\n\n    /* Direction\n    0 - Up\n    1 - Down\n    2 - Left\n    3 - Right\n    */\n\n    // For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we consider the direction as well\n    int shortest(int[][] grid, int k, int row, int col, int direction, boolean[][] visited, Integer[][][][] dp){\n        // Reached end of the matrix\n        if(row == rowLen - 1 && col == colLen - 1 && k >= 0)\n            return 0;\n\n        // Couldn't find a valid path\n        if(k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen)\n            return MAXVAL;\n\n        if(dp[row][col][k][direction] != null)\n            return dp[row][col][k][direction];\n\n        // 4 options to choose a direction\n        // Go right\n        int op1 = MAXVAL;\n        if(col + 1 < colLen && !visited[row][col+1]) {\n            visited[row][col+1] = true;\n            if(grid[row][col+1] == 0)\n                op1 = shortest(grid, k, row, col+1, 3, visited, dp) + 1;\n            else\n                op1 = shortest(grid, k-1, row, col+1, 3, visited, dp) + 1;\n            visited[row][col+1] = false;\n        }\n\n        // Go left\n        int op2 = MAXVAL;\n        if(col - 1 >= 0 && !visited[row][col-1]) {\n            visited[row][col-1] = true;\n            if(grid[row][col-1] == 0)\n                op2 = shortest(grid, k, row, col-1, 2, visited, dp) + 1;\n            else\n                op2 = shortest(grid, k-1, row, col-1, 2, visited, dp) + 1;\n            visited[row][col-1] = false;\n        }\n\n        // Go up\n        int op3 = MAXVAL;\n        if(row - 1 >= 0 && !visited[row-1][col]) {\n            visited[row-1][col] = true;\n            if(grid[row-1][col] == 0)\n                op3 = shortest(grid, k, row-1, col, 0, visited, dp) + 1;\n            else\n                op3 = shortest(grid, k-1, row-1, col, 0, visited, dp) + 1;\n            visited[row-1][col] = false;\n        }\n\n        // Go down\n        int op4 = MAXVAL;\n        if(row + 1 < rowLen && !visited[row+1][col]) {\n            visited[row+1][col] = true;\n            if(grid[row+1][col] == 0)\n                op4 = shortest(grid, k, row+1, col, 1, visited, dp) + 1;\n            else\n                op4 = shortest(grid, k-1, row+1, col, 1, visited, dp) + 1;\n            visited[row+1][col] = false;\n        }\n\n        dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4));\n        return dp[row][col][k][direction];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> directions{{-1,0},{1,0},{0,1},{0,-1}};\n    int shortestPath(vector<vector<int>>& grid, int k) {\n        int m = grid.size(),n = grid[0].size(),ans=0;\n        queue<vector<int>> q;\n        bool visited[m][n][k+1];\n        memset(visited,false,sizeof(visited));\n        q.push({0,0,k});\n        visited[0][0][k]=true;\n        \n        while(!q.empty()) {\n            int size = q.size();\n            while(size--) {\n                auto p = q.front();\n                q.pop();\n                \n                if(p[0]==m-1 && p[1]==n-1) return ans;\n                for(auto x : directions) {\n                    int i= p[0]+x[0];\n                    int j= p[1]+x[1];\n                    int obstacle = p[2];\n                    \n                    if(i>=0 && i<m && j>=0 && j<n) {\n                      if(grid[i][j]==0 && !visited[i][j][obstacle])  {\n                          q.push({i,j,obstacle});\n                          visited[i][j][obstacle] =true;\n                      } else if(grid[i][j]==1 && obstacle>0 && !visited[i][j][obstacle-1]) {\n                          q.push({i,j,obstacle-1});\n                          visited[i][j][obstacle-1]=true;\n                      }\n                    } \n                }\n            }\n            ans++;\n        }\n        return -1;\n    }\n};"
    },
    {
        "title": "Minimum Number of Operations to Reinitialize a Permutation",
        "algo_input": "You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​.\n\nIn one operation, you will create a new array arr, and for each i:\n\n\n\tIf i % 2 == 0, then arr[i] = perm[i / 2].\n\tIf i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].\n\n\nYou will then assign arr​​​​ to perm.\n\nReturn the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 1\nExplanation: perm = [0,1] initially.\nAfter the 1st operation, perm = [0,1]\nSo it takes only 1 operation.\n\n\nExample 2:\n\nInput: n = 4\nOutput: 2\nExplanation: perm = [0,1,2,3] initially.\nAfter the 1st operation, perm = [0,2,1,3]\nAfter the 2nd operation, perm = [0,1,2,3]\nSo it takes only 2 operations.\n\n\nExample 3:\n\nInput: n = 6\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 1000\n\tn​​​​​​ is even.\n\n",
        "solution_py": "class Solution:\n    def reinitializePermutation(self, n: int) -> int:\n        ans = 0\n        perm = list(range(n))\n        while True: \n            ans += 1\n            perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]\n            if all(perm[i] == i for i in range(n)): return ans",
        "solution_js": " * @param {number} n\n * @return {number}\n */\nvar reinitializePermutation = function(n) {\n  if (n < 2) return 0;\n  let prem = [];\n  let count = 0;\n  for (var i = 0; i < n; i++) {\n    prem[i] = i;\n  }\n  let newArr = [];\n  newArr = helper(prem, newArr);\n\n  const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b);\n\n  if (equals(prem, newArr)) {\n    count++;\n    return count;\n  } else {\n    while (!equals(prem, newArr)) {\n      count++;\n      let temp = newArr;\n      newArr = [];\n      newArr = helper(temp, newArr);\n    }\n  }\n  return count + 1;\n};\n\nvar helper = function (prem, arr) {\n  let n = prem.length;\n  for (var i = 0; i < n; i++) {\n    if (i % 2 == 0) {\n      arr[i] = prem[i / 2];\n    } else {\n      arr[i] = prem[n / 2 + (i - 1) / 2];\n    }\n  }\n  return arr;\n};",
        "solution_java": "class Solution {\n    public int reinitializePermutation(int n) {\n        int ans = 1;\n        int num = 2;\n        if(n == 2) return 1;\n        while(true){\n            if(num % (n-1) == 1)break; \n            else {\n                ans++;\n                num = (num * 2) % (n-1);\n            }\n        }\n        return ans;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> change(vector<int>arr,vector<int>v){\n        int n=v.size();\n         for(int i=0;i<n;i++){\n            if(i%2==0){\n                arr[i]=v[i/2];\n            }\n            else{\n                arr[i]=v[(n/2) + ((i-1)/2) ];\n            }\n        }\n        return arr;\n    }\n    int reinitializePermutation(int n) {\n        vector<int>v(n);\n        for(int i=0;i<n;i++){\n            v[i]=i;\n        }\n        vector<int>arr(n);\n\n        arr=change(arr,v);\n        if(arr==v){return 1;}\n\n        int cnt=1;\n\n        while(arr!=v){\n            arr=change(arr,arr);\n            cnt++;\n            if(arr==v){return cnt;}\n\n        }\n        return cnt;\n    }\n};"
    },
    {
        "title": "Sum of Subarray Ranges",
        "algo_input": "You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.\n\nReturn the sum of all subarray ranges of nums.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.\n\nExample 2:\n\nInput: nums = [1,3,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.\n\n\nExample 3:\n\nInput: nums = [4,-2,-3,4,1]\nOutput: 59\nExplanation: The sum of all subarray ranges of nums is 59.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t-109 &lt;= nums[i] &lt;= 109\n\n\n&nbsp;\nFollow-up: Could you find a solution with O(n) time complexity?\n",
        "solution_py": "class Solution:\n    def subArrayRanges(self, nums: List[int]) -> int:\n        n = len(nums)\n        \n        # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n        # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n        # so totalsum = maxsum - minsum\n        # we calculate minsum and maxsum in two different loops\n        minsum = maxsum = 0\n        \n        # first calculate sum{ Min(subarray) } over all subarrays\n        # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1\n        # where f(i) is number of subarrays where nums[i] is the minimum value\n        # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i]\n        # we can claculate these indices in linear time using a monotonically increasing stack.\n        stack = []\n        for next_smaller in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically increasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n            while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]):\n                i = stack.pop()\n                prev_smaller = stack[-1] if stack else -1\n                minsum += nums[i] * (next_smaller - i) * (i - prev_smaller)\n            stack.append(next_smaller)\n            \n        # then calculate sum{ Max(subarray) } over all subarrays\n        # sum{ Max(subarray) } = sum(f'(i) * nums[i]) ; i=0..n-1\n        # where f'(i) is number of subarrays where nums[i] is the maximum value\n        # f'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i]\n        # this time we use a monotonically decreasing stack.\n        stack = []\n        for next_larger in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically decreasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n            while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]):\n                i = stack.pop()\n                prev_larger = stack[-1] if stack else -1\n                maxsum += nums[i] * (next_larger - i) * (i - prev_larger)\n            stack.append(next_larger)\n        \n        return maxsum - minsum",
        "solution_js": "// O(n^3) time | O(1) space\nvar subArrayRanges = function(nums) {\n    let res = 0\n    for (let i = 1; i < nums.length; i++) {\n        for (let j = 0; j < i; j++) {\n            let smallest = nums[i], biggest = nums[i]\n            for (let k = j; k < i; k++) {\n                smallest = Math.min(smallest, nums[k])\n                biggest = Math.max(biggest, nums[k])\n            }\n            res += biggest - smallest\n        }\n    }\n    return res\n};",
        "solution_java": "class Solution {\n    class Node{\n        long val, displace;\n        Node(long val, long displace){\n            this.val = val;\n            this.displace = displace;\n        }\n    }\n    public long subArrayRanges(int[] nums) {\n        \n        //lesser than current element\n        Stack<Node> stack = new Stack<>();\n        //from left\n        long [] lesserLeft = new long[nums.length];\n        for (int i = 0; i< nums.length; i++){\n            long count = 1;\n            while(stack.size()>0 && stack.peek().val<=nums[i]){\n                count+=stack.pop().displace;\n            }\n            stack.add(new Node(nums[i], count));\n            lesserLeft[i] = count;\n        }\n        stack.clear();\n        //from right\n        long[] lesserRight = new long[nums.length];\n        for (int i = nums.length-1; i>=0; i--){\n            long count = 1;\n            while(stack.size()>0 && stack.peek().val<nums[i]){\n                count+=stack.pop().displace;\n            }\n            stack.add(new Node(nums[i], count));\n            lesserRight[i] = count;\n        }\n        \n        \n        //greater than current element\n        stack.clear();\n        //from left\n        long [] greaterLeft = new long[nums.length];\n        for (int i = 0; i< nums.length; i++){\n            long count = 1;\n            while(stack.size()>0 && stack.peek().val>=nums[i]){\n                count+=stack.pop().displace;\n            }\n            stack.add(new Node(nums[i], count));\n            greaterLeft[i] = count;\n        }\n        stack.clear();\n        //from right\n        long[] greaterRight = new long[nums.length];\n        for (int i = nums.length-1; i>=0; i--){\n            long count = 1;\n            while(stack.size()>0 && stack.peek().val>nums[i]){\n                count+=stack.pop().displace;\n            }\n            stack.add(new Node(nums[i], count));\n            greaterRight[i] = count;\n        }        \n        \n        long ans = 0;\n        //Now we subtract the count of minimum occurrences from the count of maximum occurrences\n        \n        for (int i = 0; i< nums.length; i++){\n            ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i];\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    long long subArrayRanges(vector<int>& nums) {\n        int n=nums.size();\n        long long res=0;\n        for(int i=0;i<n-1;i++){\n            int maxi=nums[i], mini=nums[i];\n            for(int j=i+1;j<n;j++){\n                if(nums[j]>maxi)maxi=nums[j];\n                else if(nums[j]<mini)mini=nums[j];\n                res+=maxi-mini;\n            }\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Bag of Tokens",
        "algo_input": "You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed).\n\nYour goal is to maximize your total score by potentially playing each token in one of two ways:\n\n\n\tIf your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score.\n\tIf your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score.\n\n\nEach token may be played at most once and in any order. You do not have to play all the tokens.\n\nReturn the largest possible score you can achieve after playing any number of tokens.\n\n&nbsp;\nExample 1:\n\nInput: tokens = [100], power = 50\nOutput: 0\nExplanation: Playing the only token in the bag is impossible because you either have too little power or too little score.\n\n\nExample 2:\n\nInput: tokens = [100,200], power = 150\nOutput: 1\nExplanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1st token since you cannot play it face up to add to your score.\n\n\nExample 3:\n\nInput: tokens = [100,200,300,400], power = 200\nOutput: 2\nExplanation: Play the tokens in this order to get a score of 2:\n1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= tokens.length &lt;= 1000\n\t0 &lt;= tokens[i],&nbsp;power &lt; 104\n\n",
        "solution_py": "class Solution:\n    def bagOfTokensScore(self, tokens, power):\n        tokens.sort()\n        n = len(tokens)\n        i, j = 0, n\n        while i < j:\n            if tokens[i] <= power:\n                power -= tokens[i]\n                i += 1\n            elif i - (n - j) and j > i + 1:\n                j -= 1\n                power += tokens[j]\n            else: break\n        return i - (n - j)",
        "solution_js": "var bagOfTokensScore = function(tokens, power) {\n    const n = tokens.length;\n    \n    tokens.sort((a, b) => a - b);\n    \n    let maxScore = 0;\n    let currScore = 0;\n    \n    let left = 0;\n    let right = n - 1;\n    \n    while (left <= right) {\n        const leftPower = tokens[left];\n        const rightPower = tokens[right];\n        \n        if (power >= leftPower) {\n            power -= leftPower;\n            currScore++;\n\n            maxScore = Math.max(currScore, maxScore);\n            left++;\n        }\n        else if (currScore > 0) {\n            power += rightPower;\n            currScore--;\n            right--; \n        }\n        else {\n            return maxScore;\n        }\n    }\n    \n    return maxScore;\n};",
        "solution_java": "class Solution {\n    public int bagOfTokensScore(int[] tokens, int power) {        \n        //initially score is 0, that's why in these conditions, return 0.        \n        if(tokens.length == 0 || power < tokens[0])\n\t\t\treturn 0;        \n        Arrays.sort(tokens); //sort the array\n        \n        int i = 0;\n        int r = tokens.length - 1;\n        int score = 0;\n        int answer = 0;\n        \n        while(i<=r){            \n            if(power >= tokens[i]){\n                power -= tokens[i++];                \n                answer = Math.max(answer, ++score); //play all tokens, but store the max score in answer.    \n            }\n            else if (score > 0){\n                power += tokens[r--]; //take power from greatest element\n                score--; //decrease by 1.\n            }            \n            //when you can't do any of the steps (face up, face down)\n            else\n                return answer;\n        }        \n        return answer;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int bagOfTokensScore(vector<int>& tokens, int power) {\n        sort(tokens.begin(),tokens.end());\n        int start=0,end=tokens.size()-1,score=0,ans=0;\n        while(start<=end){\n            if(power>=tokens[start]){\n                ans=max(ans,++score);\n                power-=tokens[start++];\n            } else if(score>0){\n                score--;\n                power+=tokens[end--];\n            } else {\n                return 0;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Greatest Sum Divisible by Three",
        "algo_input": "Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,6,5,1,8]\nOutput: 18\nExplanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\n\nExample 2:\n\nInput: nums = [4]\nOutput: 0\nExplanation: Since 4 is not divisible by 3, do not pick any number.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,4]\nOutput: 12\nExplanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 4 * 10^4\n\t1 &lt;= nums[i] &lt;= 10^4\n\n",
        "solution_py": "class Solution:\n    def maxSumDivThree(self, nums: List[int]) -> int:\n        dp = [0, float('-inf'), float('-inf')]\n        for x in nums:\n            dp_cp = dp[:]\n            for left in range(3):\n                right = (left + x) % 3\n                dp[right] = max(dp_cp[right], dp_cp[left] + x)\n\n        return dp[0]",
        "solution_js": "var maxSumDivThree = function(nums) {\n    // there are 3 options for how the sum fit's into 3 via mod % 3\n    // track those 3 options via indices in the dp array\n    // dp[0] = %3 === 0\n    // dp[1] = %3 === 1\n    // dp[2] = %3 === 2\n    let dp = new Array(3).fill(0);\n    for (let num of nums) {\n        for (let i of dp.slice(0)) {\n            let sum = i + num;\n            let mod = sum % 3;\n            // on each pass, set the value of dp[mod] to the Math.max val\n            dp[mod] = Math.max(dp[mod], sum);\n        }\n    }\n    return dp[0];\n};",
        "solution_java": "class Solution {\n\n    public int maxSumDivThree(int[] nums) {\n        int r0 = 0;\n        int r1 = 0;\n        int r2 = 0;\n        for (int i = 0; i < nums.length; i++) {\n            int nr0 = r0;\n            int nr1 = r1;\n            int nr2 = r2;\n            int a = r0 + nums[i];\n            int b = r1 + nums[i];\n            int c = r2 + nums[i];\n            if (a % 3 == 0) {\n                nr0 = Math.max(nr0, a);\n            } else if (a % 3 == 1) {\n                nr1 = Math.max(nr1, a);\n            } else if (a % 3 == 2) {\n                nr2 = Math.max(nr2, a);\n            }\n\n            if (b % 3 == 0) {\n                nr0 = Math.max(nr0, b);\n            } else if (b % 3 == 1) {\n                nr1 = Math.max(nr1, b);\n            } else if (b % 3 == 2) {\n                nr2 = Math.max(nr2, b);\n            }\n\n            if (c % 3 == 0) {\n                nr0 = Math.max(nr0, c);\n            } else if (c % 3 == 1) {\n                nr1 = Math.max(nr1, c);\n            } else if (c % 3 == 2) {\n                nr2 = Math.max(nr2, c);\n            }\n            r0=nr0;\n            r1=nr1;\n            r2=nr2;\n        }\n\n        return r0;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxSumDivThree(vector<int>& nums) {\n        vector<int> twos = {(int)1e4+1, (int)1e4+1}, ones = {(int)1e4+1, (int)1e4+1};\n        int res = 0;\n        for(int i: nums) {\n            if(i%3 == 2) {\n                if(i <= twos[0]) {\n                    twos[1] = twos[0], twos[0] = i;\n                }\n                else if(i < twos[1]) twos[1] = i;\n            }\n            else if(i%3 == 1) {\n                if(i <= ones[0]) {\n                    ones[1] = ones[0], ones[0] = i;\n                }\n                else if(i < ones[1]) ones[1] = i;\n            }\n            res += i;\n        }\n        if(res%3 == 2)\n            return max(res - twos[0], res - ones[0] - ones[1]);\n        else if(res%3 == 1)\n            return max(res - ones[0], res - twos[0] - twos[1]);\n        return res;\n    }\n};"
    },
    {
        "title": "Boats to Save People",
        "algo_input": "You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.\n\nReturn the minimum number of boats to carry every given person.\n\n&nbsp;\nExample 1:\n\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\n\nExample 2:\n\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\n\nExample 3:\n\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= people.length &lt;= 5 * 104\n\t1 &lt;= people[i] &lt;= limit &lt;= 3 * 104\n\n",
        "solution_py": "class Solution:\n    def numRescueBoats(self, people: List[int], limit: int) -> int:\n        people.sort()\n        lo = 0\n        hi = len(people)-1\n        boats = 0\n        while lo <= hi:\n            if people[lo] + people[hi] <= limit:\n                lo += 1\n                hi -= 1\n            else:\n                hi -= 1\n            boats += 1\n        return boats",
        "solution_js": "/**\n * @param {number[]} people\n * @param {number} limit\n * @return {number}\n */\nvar numRescueBoats = function(people, limit) {\n    people = people.sort((a,b) => a - b)\n\n    let left = 0\n    let right = people.length - 1\n    let res = 0\n    \n    while (left <= right) {\n       if (people[left] + people[right] <= limit) {\n           res++\n           right--\n           left++\n       } else if (people[right] <= limit) {\n           res++ \n           right--\n       }\n    }\n    \n    return res\n};",
        "solution_java": "class Solution {\n    public int numRescueBoats(int[] people, int limit) {\n        int boatCount = 0;\n        Arrays.sort(people);\n\n        int left = 0;\n        int right = people.length - 1;\n\n        while(left <= right){\n            int sum = people[left] + people[right];\n            if(sum <= limit){\n                boatCount++;\n                left++;\n                right--;\n            }\n            else{\n                boatCount++;\n                right--;\n            }\n        }\n        return boatCount;\n    }\n}",
        "solution_c": "\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n    int numRescueBoats(vector<int>& people, int limit) {\n       \n        // sort vector\n        sort(people.begin(),people.end());\n        \n        int i = 0, j = people.size() - 1,cnt = 0;\n        \n        while(i <= j)\n        {   \n            // lightest person + heaviest person sum <= limit\n            // they can go together\n            if(people[i] + people[j] <= limit)\n            {\n                ++i;\n                --j;\n            }\n            // if sum is over the limit,\n            // heaviest will go alone.\n            else\n                --j;\n            \n            ++cnt;  // number of boats\n        }\n        \n        return cnt;\n        \n    }\n\t// for github repository link go to my profile.\n};"
    },
    {
        "title": "Maximum Product of Two Elements in an Array",
        "algo_input": "Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).\n&nbsp;\nExample 1:\n\nInput: nums = [3,4,5,2]\nOutput: 12 \nExplanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \n\n\nExample 2:\n\nInput: nums = [1,5,4,5]\nOutput: 16\nExplanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\n\n\nExample 3:\n\nInput: nums = [3,7]\nOutput: 12\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 500\n\t1 &lt;= nums[i] &lt;= 10^3\n\n",
        "solution_py": "class Solution:\n    def maxProduct(self, nums: List[int]) -> int:\n        # mx1 - max element, mx2 - second max element\n        mx1 = nums[0] if nums[0] > nums[1] else nums[1]\n        mx2 = nums[1] if nums[0] > nums[1] else nums[0]\n        for num in nums[2:]:\n            if num > mx1:\n                mx1, mx2 = num, mx1\n            elif num > mx2:\n                mx2 = num\n\n        return (mx1 - 1) * (mx2 - 1)",
        "solution_js": "var maxProduct = function(nums) {\n    let val = [];\n    for(let i=0; i<nums.length; i++){\n        for(let j=i+1; j<nums.length; j++){\n            val.push((nums[i]-1)*(nums[j]-1))\n        }\n    }\n    return Math.max(...val)\n};",
        "solution_java": "class Solution {\n    public int maxProduct(int[] nums) {\n        int max = Integer.MIN_VALUE;\n        int maxi = -1;\n        for (int i = 0; i < nums.length; ++i) {\n            if (nums[i] > max) {\n                max = nums[i];\n                maxi = i;\n            }\n        }\n        nums[maxi] = Integer.MIN_VALUE;\n        int nextmax = Integer.MIN_VALUE;\n        for (int i = 0; i < nums.length; ++i) {\n            if (nums[i] > nextmax) nextmax = nums[i];\n        }\n        return max*nextmax-max-nextmax+1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxProduct(vector<int>& nums) {\n        int n = nums.size();      \n         sort(nums.begin(), nums.end());                \n       return (nums[n -1]-1)* (nums[n-2]-1);\n    }\n};"
    },
    {
        "title": "Last Moment Before All Ants Fall Out of a Plank",
        "algo_input": "We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.\n\nWhen two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.\n\nWhen an ant reaches one end of the plank at a time t, it falls out of the plank immediately.\n\nGiven an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, left = [4,3], right = [0,1]\nOutput: 4\nExplanation: In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).\n\n\nExample 2:\n\nInput: n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput: 7\nExplanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.\n\n\nExample 3:\n\nInput: n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput: 7\nExplanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= left.length &lt;= n + 1\n\t0 &lt;= left[i] &lt;= n\n\t0 &lt;= right.length &lt;= n + 1\n\t0 &lt;= right[i] &lt;= n\n\t1 &lt;= left.length + right.length &lt;= n + 1\n\tAll values of left and right are unique, and each value can appear only in one of the two arrays.\n\n",
        "solution_py": "class Solution:\n    def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n        # make sure left and right are not empty without changing the answer\n        left.append(0)\n        right.append(n)\n\n        return max(max(left), n - min(right))",
        "solution_js": "var getLastMoment = function(n, left, right) {\n    const maxLeft = Math.max(...left);\n    const minRight = Math.min(...right);\n\n    return Math.max(n - minRight, maxLeft);\n};",
        "solution_java": "class Solution {\n    public int getLastMoment(int n, int[] left, int[] right) {\n        int max = 0;\n        for (int i = 0; i < left.length; i++) {\n            if (left[i] > max)\n                max = left[i];\n        }\n        for (int i = 0; i < right.length; i++) {\n            if (n - right[i] > max)\n                max = n - right[i];\n        }\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int getLastMoment(int n, vector<int>& left, vector<int>& right) {\n        int mx=0;\n        for(auto&i:left)mx=max(mx,i);\n        for(auto&i:right)mx=max(mx,n-i);\n        return mx;\n    }\n};"
    },
    {
        "title": "Smallest String Starting From Leaf",
        "algo_input": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.\n\nReturn the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\n\nAs a reminder, any shorter prefix of a string is lexicographically smaller.\n\n\n\tFor example, \"ab\" is lexicographically smaller than \"aba\".\n\n\nA leaf of a node is a node that has no children.\n\n&nbsp;\nExample 1:\n\nInput: root = [0,1,2,3,4,3,4]\nOutput: \"dba\"\n\n\nExample 2:\n\nInput: root = [25,1,3,1,3,0,2]\nOutput: \"adz\"\n\n\nExample 3:\n\nInput: root = [2,2,1,null,1,0,null,0]\nOutput: \"abc\"\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 8500].\n\t0 &lt;= Node.val &lt;= 25\n\n",
        "solution_py": "class Solution:\n    res = 'z' * 13           # init max result, tree depth,  12< log2(8000) < 13\n    \n    def smallestFromLeaf(self, root: TreeNode) -> str:\n        \n        def helper(node: TreeNode, prev):\n            prev = chr(97 + node.val) + prev\n            \n            if not node.left and not node.right:\n                self.res = min(self.res, prev)\n                return\n            \n            if node.left:\n                helper(node.left, prev)\n            if node.right:\n                helper(node.right, prev)\n        \n        helper(root, \"\")\n        return self.res",
        "solution_js": "var smallestFromLeaf = function(root) {\n    \n    if(root === null) return '';\n    \n    let queue = [[root, ''+giveCharacter(root.val)]];\n    let leafLevelFound = false;\n    let possibleSmallString = [];\n    \n    while(queue.length > 0){\n        \n        let currentLevelLength = queue.length;\n        \n        \n        for(let i=0; i<currentLevelLength; i++){\n            \n            let [currentNode, currentPath] = queue.shift();\n            \n            if(currentNode.left === null && currentNode.right ===null){\n                // as one of the test case is failing with this approacch - saying legth/depth of the path doesnt matter\n                // even TOTAL (ASCII)SUM of letters also not matter - it should be dictionary first path\n                // hence, no need of this logic and have to continue until all path discovered\n                // So, instead removing - just never doing TRUE - hence it will continue exploring and putting all paths\n                leafLevelFound = false; \n                possibleSmallString.push(currentPath); //.split(\"\").reverse().join(\"\")\n            }\n            \n            if(!leafLevelFound){\n                if(currentNode.left !== null) queue.push([currentNode.left,giveCharacter(currentNode.left.val)+currentPath]);\n                if(currentNode.right !== null) queue.push([currentNode.right,giveCharacter(currentNode.right.val)+currentPath]);\n            }\n            \n        }\n        \n        if(leafLevelFound) break; \n    }\n    \n    // console.log(possibleSmallString);\n    possibleSmallString.sort();\n    // console.log(possibleSmallString);\n    return possibleSmallString[0];\n    \n};\n\nfunction giveCharacter(num){\n    return String.fromCharCode(num+97);\n}",
        "solution_java": "class Solution {\n    String result = null;\n    public String smallestFromLeaf(TreeNode root) {\n        build(root, new StringBuilder());\n        return result;\n    }\n\n    public void build(TreeNode root, StringBuilder str) {\n        if (root == null) return;\n\n        StringBuilder sb = new StringBuilder(str).insert(0, String.valueOf(intToChar(root.val)));\n\n        if (root.left == null && root.right == null) { // we are on a leaf node\n            result = result == null || sb.toString().compareTo(result) < 0 ? sb.toString() : result;\n            return;\n        }\n        build(root.left, sb); // build left child\n        build(root.right, sb); // build right child\n    }\n\n    // turns an int (0-25) into a Character ex: 0 -> a, 1 -> b, 2 -> c\n    public Character intToChar(int i) {\n        return (char) (i + 'a');\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    string res;\n    void solve(TreeNode* root,string cur){\n        if(!root) return;\n        cur.push_back((char)('a'+root->val));//converting integer to corresponding characer\n        if(!root->left and !root->right){\n\t\t\t//reversing the string since it is computed from root to leaf, but we need viceversa\n            reverse(cur.begin(),cur.end());\n            if(res==\"\" or cur<res) res=cur;//updating the result based on lexicographical order\n            return;\n        }\n        solve(root->left,cur);\n        solve(root->right,cur);\n        return;\n    }\n    string smallestFromLeaf(TreeNode* root) {\n        if(!root) return \"\"; \n        solve(root,\"\");\n        return res;\n    }\n};"
    },
    {
        "title": "Find in Mountain Array",
        "algo_input": "(This problem is an interactive problem.)\n\nYou may recall that an array arr is a mountain array if and only if:\n\n\n\tarr.length &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\nGiven a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.\n\nYou cannot access the mountain array directly. You may only access the array using a MountainArray interface:\n\n\n\tMountainArray.get(k) returns the element of the array at index k (0-indexed).\n\tMountainArray.length() returns the length of the array.\n\n\nSubmissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.\n\n&nbsp;\nExample 1:\n\nInput: array = [1,2,3,4,5,3,1], target = 3\nOutput: 2\nExplanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\n\nExample 2:\n\nInput: array = [0,1,2,4,2,1], target = 3\nOutput: -1\nExplanation: 3 does not exist in the array, so we return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= mountain_arr.length() &lt;= 104\n\t0 &lt;= target &lt;= 109\n\t0 &lt;= mountain_arr.get(index) &lt;= 109\n\n",
        "solution_py": "# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class MountainArray:\n#    def get(self, index: int) -> int:\n#    def length(self) -> int:\n\nclass Solution:\n    def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:\n        min_index = -1\n        peak = self.findpeak(mountain_arr)\n        \n        min_index = self.binary_search(0, peak, mountain_arr, target, 1)\n        if min_index == -1:\n            min_index = self.binary_search(peak+1, mountain_arr.length() - 1, mountain_arr, target, -1)\n        return min_index\n\n    def findpeak(self, mountain_arr):\n        start = 0\n        end = mountain_arr.length() - 1\n        while start < end:\n            mid = start + int((end - start)/2)\n            if mountain_arr.get(mid) < mountain_arr.get(mid + 1):\n                start = mid + 1\n            else:\n                end = mid\n        \n        return start\n    \n    def binary_search(self, start, end, mountain_arr, target, asc):\n        while start <= end:\n            mid = start + int((end - start)/2)\n            mountain_arr_get_mid = mountain_arr.get(mid)\n            if target == mountain_arr_get_mid:\n                return mid\n            if asc == 1:\n                if target < mountain_arr_get_mid:\n                    end = mid - 1\n                elif target > mountain_arr_get_mid:\n                    start = mid + 1\n            else:\n                if target < mountain_arr_get_mid:\n                    start = mid + 1\n                elif target > mountain_arr_get_mid:\n                    end = mid - 1\n            \n        return -1",
        "solution_js": "/**\n * // This is the MountainArray's API interface.\n * // You should not implement it, or speculate about its implementation\n * function MountainArray() {\n *     @param {number} index\n *     @return {number}\n *     this.get = function(index) {\n *         ...\n *     };\n *\n *     @return {number}\n *     this.length = function() {\n *         ...\n *     };\n * };\n */\n\nvar binarySearch = function(left, right, condition) {\n    while (left < right) {\n        var mid = left + Math.floor((right - left) / 2);\n        if (condition(mid)) {\n            right = mid;\n        } else {\n            left = mid + 1;\n        }\n    }\n    return left;\n}\n\n/**\n * @param {number} target\n * @param {MountainArray} mountainArr\n * @return {number}\n */\nvar findInMountainArray = function(target, mountainArr) {\n    var n = mountainArr.length();\n    var maxNumIdx = binarySearch(1, n - 2, function(idx) {\n        return mountainArr.get(idx) > mountainArr.get(idx + 1);\n    });\n    var leftIdx = binarySearch(0, maxNumIdx, function(idx) {\n        return mountainArr.get(idx) >= target;\n    });\n    if (mountainArr.get(leftIdx) === target) {\n        return leftIdx;\n    }\n    var rightIdx = binarySearch(maxNumIdx, n - 1, function(idx) {\n        return mountainArr.get(idx) <= target;\n    });\n    if (mountainArr.get(rightIdx) === target) {\n        return rightIdx;\n    }\n    return -1;\n};",
        "solution_java": "class Solution {\n    public int findInMountainArray(int target, MountainArray mountainArr) {\n        int peak = findPeak(mountainArr);\n        \n        int left =binary(0,peak,mountainArr,target,true);\n            if(left!=-1){\n                return left;\n            }\n        int right= binary(peak+1,mountainArr.length()-1,mountainArr, target,false);\n        return right;  \n    }\n    \n    static int findPeak(MountainArray mountainArr){\n        int start=0;\n        int end =mountainArr.length()-1;\n        \n        while(start<end){\n            int mid=start+((end-start)/2);\n            \n            if(mountainArr.get(mid)<mountainArr.get(mid+1)){\n                start=mid+1;\n            }else{\n                end=mid;\n            }\n        }\n        return start;\n    }\n    \n    static int binary(int low, int high, MountainArray arr,int target, boolean left){\n            while(low<=high){\n                int mid=low+((high-low)/2);\n                if(target<arr.get(mid)){\n                    if(left){\n                        high=mid-1;\n                    }else{\n                         low=mid+1;\n                    }   \n                }else if(target>arr.get(mid)){\n                    if(left){\n                        low=mid+1;\n                    }else{\n                       high=mid-1; \n                    }    \n                }else{\n                    return mid;\n                }\n            } \n        return -1;\n    }\n}",
        "solution_c": "/**\n * // This is the MountainArray's API interface.\n * // You should not implement it, or speculate about its implementation\n * class MountainArray {\n * public:\n * int get(int index);\n * int length();\n * };\n */\n\nclass Solution {\npublic:\n\n    //----------------------- find peak ---------------------------------------\n\n    int find_max(MountainArray &mountainArr,int start,int end)\n    { int n= mountainArr.length();\n        while(start<=end)\n        { int mid= start+(end-start)/2;\n           int next=(mid+1)%n;\n          int prev=(mid+n-1)%n;\n\n         int mid_val = mountainArr.get(mid);\n         int pre_val = mountainArr.get(prev);\n         int next_val = mountainArr.get(next);\n\n           if(mid_val > next_val and mid_val>pre_val)\n               return mid;\n\n           else if(mid_val<next_val and mid_val > pre_val)\n                start=mid+1;\n\n           else if(mid_val>next_val and mid_val<pre_val)\n                end=mid-1;\n\n        }\n        return -1;\n\n    }\n\n   //--------------------------binary search-------------------------------------------\n\n   int binary_search(MountainArray &mountainArr,int start,int end,int target)\n   {\n       while(start<=end)\n       {\n           int mid= start + (end-start)/2;\n             int mid_val=mountainArr.get(mid);\n\n           if(mid_val==target)\n               return mid;\n          else if(target < mid_val)\n           {\n               end=mid-1;\n           }\n           else\n               start=mid+1;\n       }\n       return -1;\n   }\n\n    //----------------------binary search in reverse sorted------------------------------\n\n       int binary_search_rev(MountainArray &mountainArr,int start,int end,int target)\n   {\n       while(start<=end)\n       {\n           int mid= start + (end-start)/2;\n           int mid_val=mountainArr.get(mid);\n           if(mid_val==target)\n               return mid;\n          else if(target > mid_val)\n           {\n               end=mid-1;\n           }\n           else\n               start=mid+1;\n       }\n       return -1;\n   }\n\n  //------------------------------returns minimum index of target--------------------------------------\n\n    int evaluate_ans(int a,int b)\n    {\n        if(a==-1 and b==-1 )\n            return -1;\n        else if(a!= -1 and b!= -1)\n            return min(a,b);\n        else if(a==-1 and b!=-1)\n            return b;\n        else\n            return a;\n\n    }\n\n    int findInMountainArray(int target, MountainArray &mountainArr) {\n\n        int start=0;\n        int n= mountainArr.length()-1;\n        int max_in = find_max(mountainArr,start ,n);\n\n        int a= binary_search(mountainArr,start,max_in,target);\n        int b= binary_search_rev(mountainArr,max_in + 1,n,target);\n\n        return evaluate_ans(a,b);\n    }\n};"
    },
    {
        "title": "Count Nodes With the Highest Score",
        "algo_input": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.\n\nEach node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.\n\nReturn the number of nodes that have the highest score.\n\n&nbsp;\nExample 1:\n\nInput: parents = [-1,2,0,2,0]\nOutput: 3\nExplanation:\n- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.\n\n\nExample 2:\n\nInput: parents = [-1,2,0]\nOutput: 2\nExplanation:\n- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == parents.length\n\t2 &lt;= n &lt;= 105\n\tparents[0] == -1\n\t0 &lt;= parents[i] &lt;= n - 1 for i != 0\n\tparents represents a valid binary tree.\n\n",
        "solution_py": "class Solution:\n    def countHighestScoreNodes(self, parents: List[int]) -> int:\n        graph = collections.defaultdict(list)\n        for node, parent in enumerate(parents):  # build graph\n            graph[parent].append(node)\n        n = len(parents)                         # total number of nodes\n        d = collections.Counter()\n        def count_nodes(node):                   # number of children node + self\n            p, s = 1, 0                          # p: product, s: sum\n            for child in graph[node]:            # for each child (only 2 at maximum)\n                res = count_nodes(child)         # get its nodes count\n                p *= res                         # take the product\n                s += res                         # take the sum\n            p *= max(1, n - 1 - s)               # times up-branch (number of nodes other than left, right children ans itself)\n            d[p] += 1                            # count the product\n            return s + 1                         # return number of children node + 1 (self)\n        count_nodes(0)                           # starting from root (0)\n        return d[max(d.keys())]                  # return max count",
        "solution_js": "var countHighestScoreNodes = function(parents) {\n    const n = parents.length;\n    const adj = [];\n    \n    for (let i = 0; i < n; ++i) {\n        adj[i] = [];\n    } \n    \n    for (let i = 1; i < n; ++i) {\n        const parent = parents[i];\n        adj[parent].push(i);\n    }\n    \n    let maxProd = 0;\n    let maxCount = 0;\n    \n    dfs(0);\n    \n    return maxCount;\n    \n    function dfs(node) {\n        let rem = n - 1;\n\n        let sum = 0;\n        let prod = 1;\n\n        for (const child of adj[node]) {\n            const count = dfs(child);\n            \n            sum += count;\n            prod *= count;\n            rem -= count;\n        }\n\n        if (rem > 0) prod *= rem;\n\n        if (prod > maxProd) {\n            maxProd = prod;\n            maxCount = 1;\n        }\n        else if (prod === maxProd) {\n            ++maxCount;\n        }\n\n        return sum + 1;\n    }\n};",
        "solution_java": "class Solution {\n    long max = 0, res = 0;\n    public int countHighestScoreNodes(int[] parents) {\n        Map<Integer, List<Integer>> hm = new HashMap();\n        for(int i = 0; i < parents.length; i++) {   // build the tree\n            hm.computeIfAbsent(parents[i], x ->new ArrayList<>()).add(i);\n        }\n        dfs(0, parents.length, hm); // traverse the tree to get the result\n        return (int)res;\n    }\n    int dfs(int s, int n, Map<Integer, List<Integer>> hm) {\n        int sum = 1;\n        long mult = 1L;\n        for(int child : hm.getOrDefault(s, new ArrayList<>())) {\n            int count = dfs(child, n, hm); // subtree node count\n            sum += count;\n            mult *= count; // multiply the result by children size\n        }     \n        mult *= (s == 0 ? 1L : n - sum); // multiply the result by remain size except self and children size(the nodes through parent)\n        if(mult > max) {\n            max = mult;\n            res = 1;\n        } else if (mult == max) {\n            res++;\n        }\n        return sum; // return the node count of the tree rooted at s\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n     \n    // Steps : \n    // 1 - For each node, you need to find the sizes of the subtrees rooted in each of its children.\n    \n    // 2 - How to determine the number of nodes in the rest of the tree? \n\t// Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree?\n    \n    // 3 - Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score. \n    \n\t// calculating size of each subtree by standing at every node  '0' to 'n-1'\n    int dfs(int src,vector<vector<int>>& g,vector<int>& size)\n    {\n         int ans = 1;// for curent node\n         for(auto child : g[src]){\n             ans += dfs(child,g,size);\n         }\n         return size[src] = ans; \n     }\n    \n    // This code can also be work for generalized tree not only for Binary tree\n    int countHighestScoreNodes(vector<int>& parents) \n    {    \n        int n=parents.size();\n        vector<int>size(n,0);  // size[i] indicates size of subtree(rooted at i node) + 1\n        vector<vector<int>>g(n);  // storing left and right child of a node\n        for(int i=1;i<n;i++){\n            g[parents[i]].push_back(i); // 'There is no parent for 0th node'\n        }\n        \n        dfs(0,g,size); //calculating size of each subtree(rooted at ith node)\n\n        long long int maxCount = 0; // To avoid overflow  because perform product below you should take \"long long int\"\n        long long int maxScore = 0;\n        for(int i=0;i<n;i++) // Nodes from '0' to 'n-1'\n        {\n            // calculate score of each node after removal their 'edge' or 'node itself'.\n            long long int product = 1;\n            product = max(product, (long long int)(n - size[i])); // calculating leftover nodes excluding child nodes \n            for(auto x : g[i])\n            {\n                product = product*size[x];\n            }\n            \n            if(product > maxScore){\n                maxScore = product;\n                maxCount = 1;\n            }\n            else if(product == maxScore){\n                maxCount++; // store count of nodes which have maximum score equal to \"maxScore\"\n            }\n        }\n            \n        return maxCount;\n    }\n};"
    },
    {
        "title": "Recover a Tree From Preorder Traversal",
        "algo_input": "We run a&nbsp;preorder&nbsp;depth-first search (DFS) on the root of a binary tree.\n\nAt each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.&nbsp; If the depth of a node is D, the depth of its immediate child is D + 1.&nbsp; The depth of the root node is 0.\n\nIf a node has only one child, that child is guaranteed to be the left child.\n\nGiven the output traversal of this traversal, recover the tree and return its root.\n\n&nbsp;\nExample 1:\n\nInput: traversal = \"1-2--3--4-5--6--7\"\nOutput: [1,2,5,3,4,6,7]\n\n\nExample 2:\n\nInput: traversal = \"1-2--3---4-5--6---7\"\nOutput: [1,2,5,3,null,6,null,4,null,7]\n\n\nExample 3:\n\nInput: traversal = \"1-401--349---90--88\"\nOutput: [1,401,null,349,88,90]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the original tree is in the range [1, 1000].\n\t1 &lt;= Node.val &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n        i = 0\n        dummy_head = TreeNode()\n        depth = 0\n        while i < len(traversal):\n            if traversal[i].isdigit():\n                value, i = get_value(traversal, i)\n                insert_node(dummy_head, depth, value)\n\n            else:\n                depth, i = get_depth(traversal, i)\n\n        return dummy_head.left\n\n# Returns the next value from the string traversal, and returns the position following the last digit of the current value.\ndef get_value(traversal, i):\n    value = 0\n    while i < len(traversal) and traversal[i].isdigit():\n        value *= 10\n        value += int(traversal[i])\n        i += 1\n\n    return value, i\n\n# Insertes a node of the given `value` at the given `depth` of the subtree whose root is the given `root`.\ndef insert_node(root, depth, value):\n    for _ in range(depth):\n        if root.right:\n            root = root.right\n        else:\n            root = root.left\n\n    new_node = TreeNode(value)\n    if root.left:\n        root.right = new_node\n    else:\n        root.left = new_node\n\n# Gets the next depth from the string traversal, and returns the position following the last dash of the current depth.\ndef get_depth(traversal, i):\n    depth = 0\n    while i < len(traversal) and traversal[i] == \"-\":\n        depth += 1\n        i += 1\n\n    return depth, i",
        "solution_js": "var recoverFromPreorder = function(traversal) {\n    \n    let n = traversal.length;\n    \n    // Every layer in dfs handles the depth+1 of '-' only.\n    // ex: \n    //   depth=0 -> find '-'  as splitter\n    //   depth=1 -> find '--' as splitter\n    //   depth=2 -> find '---' as splitter\n    let dfs = (str,depth)=>{\n        if(str.indexOf(\"-\") === -1) return new TreeNode(str);\n\t\t\n\t\t// 1. We split by the depth+1 number of '-'\n        // Using regex to split is much easier. -> str.split(/(?<=\\d)-(?=\\d)/g)\n\t\t// where (?<=\\d)  means positive lookbehind , ex: \"1- ...\", then we'll split '-' excluding 1.\n\t\t// Similarly , (?=\\d) means positive lookahead , ex: \"-5 ...\",  then we'll split '-' excluding 5.\n\t\t\n        let re = new RegExp(`(?<=\\\\d)${\"-\".repeat(depth+1)}(?=\\\\d)`,'g');\n        let [val,leftStr,rightStr] = str.split(re);\n        // ex: 1-2--3--4-5--6--7 --> ['1','2--3--4','5--6--7']\n        \n\t\t// 2. After splitting,  we'll get [val,leftStr,rightStr]\n\t\t// Then we could handle left / right node in the next dfs layer intuitively.\n        let node = new TreeNode(val);\n        if(leftStr)  node.left  = dfs(leftStr,depth+1);\n        if(rightStr) node.right = dfs(rightStr,depth+1);\n        \n        return node;\n    };\n    \n    return dfs(traversal,0);\n    \n};",
        "solution_java": "class Solution {\n    public TreeNode recoverFromPreorder(String traversal) {\n        if(!traversal.contains(\"-\"))\n            return new TreeNode(Integer.parseInt(traversal));\n        String number = \"\";\n        int i = 0;\n        while(traversal.charAt(i)!='-'){\n            number+=traversal.charAt(i);\n            i++;\n        }\n        //System.out.print(\"root = \" + number + \" \" + i + \"     \");\n        TreeNode root = new TreeNode(Integer.parseInt(number));\n        StringBuilder str = new StringBuilder();\n        int bk = 0;\n        for(int j = i; i < traversal.length(); i++){\n            if(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-' && traversal.charAt(i+1) != '-')\n                bk = str.toString().length();\n            else if(!(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-'))\n                str.append(traversal.charAt(i));\n        }\n        String divide = str.toString();\n        \n        TreeNode left = (bk==0)?recoverFromPreorder(divide):recoverFromPreorder(divide.substring(0,bk));\n        TreeNode right = (bk==0)?null:recoverFromPreorder(divide.substring(bk,divide.length()));\n        root.left = left;\n        root.right = right;\n            \n        \n        return root;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    // Returns the index of '-' if present otherwise returns the string length\n    int findIndex(int ind, string &traversal){\n        int req = traversal.size();\n        for(int i=ind; i<traversal.size(); i++){\n            if(traversal[i] == '-'){\n                req = i;\n                break;\n            }\n        }\n        return req;\n    }\n\n    TreeNode* recoverFromPreorder(string traversal) {\n        // Pushing the node along with its depth into the stack\n        int depth = 0;\n        stack<pair<TreeNode*,int>> st;\n\n        // Finding the root node\n        int ind = findIndex(0, traversal);\n        string str = traversal.substr(0, ind);\n        TreeNode *root = new TreeNode(stoi(str));\n\n        // Pushing the root node along with its depth\n        st.push({root, 0});\n\n        // Starting from 'ind' as it has the next '-' character\n        int i = ind;\n\n        while(i<traversal.size()){\n            // Increment the depth\n            if(traversal[i] == '-'){\n                depth++;\n                i++;\n                continue;\n            }\n\n            // Find the complete number as no.of digits can be > 1\n            int ind = findIndex(i, traversal);\n            string str = traversal.substr(i, ind-i);\n            TreeNode *node = new TreeNode(stoi(str));\n\n            // Finding its appropriate parent, whose depth is one less than current depth\n            while(!st.empty() && st.top().second != depth-1){\n                st.pop();\n            }\n\n            // There is already left child for the parent\n            if(st.top().first->left){\n                st.top().first->right = node;\n            }\n            else{\n                st.top().first->left = node;\n            }\n\n            // Pushing that node and its depth into stack\n            st.push({node, depth});\n            depth = 0;\n            i = ind;\n        }\n\n        return root;\n    }\n};"
    },
    {
        "title": "Path with Maximum Gold",
        "algo_input": "In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.\n\nReturn the maximum amount of gold you can collect under the conditions:\n\n\n\tEvery time you are located in a cell you will collect all the gold in that cell.\n\tFrom your position, you can walk one step to the left, right, up, or down.\n\tYou can't visit the same cell more than once.\n\tNever visit a cell with 0 gold.\n\tYou can start and stop collecting gold from any position in the grid that has some gold.\n\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput: 24\nExplanation:\n[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -&gt; 8 -&gt; 7.\n\n\nExample 2:\n\nInput: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput: 28\nExplanation:\n[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 15\n\t0 &lt;= grid[i][j] &lt;= 100\n\tThere are at most 25 cells containing gold.\n\n",
        "solution_py": "class Solution:\n    def getMaximumGold(self, grid):\n        answer = [0]\n\n        def visit(visited, i, j, gold_sum):\n            val = grid[i][j]\n            if val == 0 or (i,j) in visited:\n                answer[0] = max(answer[0], gold_sum)\n                return\n\n            gold_sum_new = gold_sum + val\n            visited_new = visited.union({(i,j)})\n\n            if i > 0:\n                visit(visited_new, i-1, j, gold_sum_new)\n\n            if j < len(grid[i]) - 1:\n                visit(visited_new, i, j+1, gold_sum_new)\n\n            if i < len(grid) - 1:\n                visit(visited_new, i+1, j, gold_sum_new)\n            if j > 0:\n                visit(visited_new, i, j-1, gold_sum_new)\n        #choosing the starting points\n        for i in range(len(grid)):\n            for j in range(len(grid[i])):\n                if grid[i][j] != 0:\n                    count = 0\n\n                    try:\n                        if grid[i-1][j] != 0:\n                            count += 1\n                    except:\n                        pass\n                    try:\n                        if grid[i][j+1] != 0:\n                            count += 1\n                    except:\n                        pass\n                    try:\n                        if grid[i+1][j] != 0:\n                            count += 1\n                    except:\n                        pass\n                    try:\n                        if grid[i][j-1] != 0:\n                            count += 1\n                    except:\n                        pass\n\n                    if count < 3:\n                        visit(set(),i,j,0)\n\n        return answer[0]",
        "solution_js": "var getMaximumGold = function(grid) {\n    let max = 0;\n    \n\t// This is our internal dfs function that will search all possible directions from a cell\n    const mine = (x, y, n) => {\n\t    // We can't mine any gold if the position is out of the grid, or the cell doesnt have any gold\n        if (x < 0 || y < 0 || x > grid.length - 1 || y > grid[x].length - 1 || grid[x][y] == 0) return 0;\n\t\t\n\t\t// Save the temp value so we can mark the cell as visited\n        let temp = grid[x][y];\n        grid[x][y] = 0;\n        \n\t\t// Try mining left, right, up, and down from the current position, \n\t\t// bringing along the gold total that was found in the current cell\n        mine(x + 1, y, n + temp);\n        mine(x - 1, y, n + temp);\n        mine(x, y + 1, n + temp);\n        mine(x, y - 1, n + temp);\n        \n\t\t// After we've tried all directions reset cell to have its original value,\n\t\t// so it can be mined from a different starting point\n        grid[x][y] = temp;\n        \n\t\t// Update the max based on the mining done up until the current cell\n        max = Math.max(max, n + temp);\n    }\n\t\n\t// We need to run this dfs function through every potential starting point\n    for (let i = 0; i < grid.length; i++) {\n        for (let j = 0; j < grid[i].length; j++) {\n            mine(i, j, 0);\n        }\n    }\n    return max;\n    \n};",
        "solution_java": "class Solution {\n    int r = 0;\n    int c = 0;\n    int max = 0;\n    public int getMaximumGold(int[][] grid) {\n        r = grid.length;\n        c = grid[0].length;\n        for(int i = 0; i < r; i++) {\n            for(int j = 0; j < c; j++) {\n                if(grid[i][j] != 0) {\n                    dfs(grid, i, j, 0);\n                }\n            }\n        }\n        return max;\n    }\n    \n    private void dfs(int[][] grid, int i, int j, int cur) {\n        if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] == 0) {\n            max = Math.max(max, cur);\n            return;\n        }\n        int val = grid[i][j];\n        grid[i][j] = 0;\n        dfs(grid, i + 1, j, cur + val);\n        dfs(grid, i - 1, j, cur + val);\n        dfs(grid, i, j + 1, cur + val);\n        dfs(grid, i, j - 1, cur + val);\n        grid[i][j] = val;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxgold=0;\n    int m,n;\n    void gold(int i,int j,vector<vector<int>>& grid,vector<vector<int>>& vis,int count){\n// Down\n        if(i+1<m && !vis[i+1][j] && grid[i+1][j]){\n            vis[i][j]=1;\n            gold(i+1,j,grid,vis,count+grid[i+1][j]);\n            vis[i][j]=0;\n        }\n// Left\n        if(j-1>=0 && !vis[i][j-1] && grid[i][j-1]){\n            vis[i][j]=1;\n            gold(i,j-1,grid,vis,count+grid[i][j-1]);\n            vis[i][j]=0;\n        }\n// Right\n        if(j+1<n && !vis[i][j+1] && grid[i][j+1]){\n            vis[i][j]=1;\n            gold(i,j+1,grid,vis,count+grid[i][j+1]);\n            vis[i][j]=0;\n        }\n// Up\n        if(i-1>=0 && !vis[i-1][j] && grid[i-1][j]){\n            vis[i][j]=1;\n            gold(i-1,j,grid,vis,count+grid[i-1][j]);\n            vis[i][j]=0;\n        }\n        maxgold=max(maxgold,count);\n    }\n\n    int getMaximumGold(vector<vector<int>>& grid) {\n        m=grid.size();\n        n=grid[0].size();\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                if(grid[i][j]){\n                    vector<vector<int>>vis(m,vector<int>(n,0));\n                    gold(i,j,grid,vis,grid[i][j]);\n                }\n            }\n        }\n        return maxgold;\n    }\n};"
    },
    {
        "title": "Count of Smaller Numbers After Self",
        "algo_input": "Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,2,6,1]\nOutput: [2,1,1,0]\nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\n\n\nExample 2:\n\nInput: nums = [-1]\nOutput: [0]\n\n\nExample 3:\n\nInput: nums = [-1,-1]\nOutput: [0,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def countSmaller(self, nums: List[int]) -> List[int]:\n        # build the binary indexed tree\n        num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0\n        tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1\n\n        result = [0] * len(nums)\n\n        # iterate from right to left\n        for result_index in range(len(nums) - 1, -1, -1):\n            n = nums[result_index]\n            # add 10**4 to n to account for negative numbers\n            i = n + 10 ** 4\n\n            # convert to 1-based index for the tree\n            i += 1\n            # perform range sum query of buckets [-inf, n-1], where n is current number\n            # because we want n - 1 for range sum query of [-inf, n-1], not n, subtract 1 from i:\n            i -= 1\n\n            val = 0\n            while i != 0:\n                val += tree[i]\n                # get parent node by subtracting least significant set bit\n                i -= i & -i\n\n            result[result_index] = val\n\n            # update the binary indexed tree with new bucket\n            i = n + 10 ** 4\n            i += 1\n            while i < len(tree):\n                tree[i] += 1\n                # get next node to update by adding the least significant set bit\n                i += i & -i\n\n        return result",
        "solution_js": "var countSmaller = function(nums) {\n    if(nums===null || nums.length == 0) return []\n    \n    let N = nums.length\n    const result = new Array(N).fill(0)\n    const numsWithIdx = new Array(N).fill(0)\n    \n    for(let i = 0; i < nums.length; i++) {\n        const curr = nums[i]\n        \n        numsWithIdx[i] = {val:curr, originalIdx: i}\n    }\n\n    divideAndConqueuer(0, nums.length - 1)\n    \n    const resultList = []\n    result.forEach(el => resultList.push(el))\n    \n    return resultList\n\n    function divideAndConqueuer(left, right) {\n        if(left < right) {\n            const mid = Math.floor(left + (right - left)/2)\n            divideAndConqueuer(left, mid)\n            divideAndConqueuer(mid+1, right)\n            merge(left, mid, right)\n        }\n    }\n\n    function merge(left, mid, right) {\n        const leftLen = mid - left + 1\n        const rightLen = right - mid\n        \n        let rightSmallers = 0\n\n        const leftAux = new Array(leftLen).fill(0)\n        const rightAux = new Array(rightLen).fill(0)\n\n\n        for(let i = 0; i < leftLen; i++) {\n            leftAux[i] = numsWithIdx[left+i]\n        }\n\n\n        for(let i = 0; i < rightLen; i++) {\n            rightAux[i] = numsWithIdx[mid+1+i]\n        }\n\n\n        let leftPointer = 0\n        let rightPointer = 0\n        let insertAtPointer = left\n\n        while(leftPointer < leftLen && rightPointer < rightLen) {\n            if(leftAux[leftPointer].val <= rightAux[rightPointer].val) {\n                \n                result[leftAux[leftPointer].originalIdx] += rightSmallers  \n                numsWithIdx[insertAtPointer++] = leftAux[leftPointer++]\n                \n            } else {\n                numsWithIdx[insertAtPointer++] = rightAux[rightPointer++]                \n                rightSmallers++\n            }\n        }\n\n\n        while(rightPointer < rightLen) {\n                numsWithIdx[insertAtPointer++] = rightAux[rightPointer++]                            \n        }\n        \n        while(leftPointer < leftLen) {\n                result[leftAux[leftPointer].originalIdx] += rightSmallers  \n                numsWithIdx[insertAtPointer++] = leftAux[leftPointer++]            \n        }\n\n    }\n};",
        "solution_java": "class Solution {    \n    public List<Integer> countSmaller(int[] nums) {\n        int min = 20001;\n        int max = -1;\n        for (int num : nums) {\n            min = Math.min(min, num);\n            max = Math.max(max, num);\n        }\n        \n        min--;\n        int[] count = new int[max-min+1];\n        Integer[] result = new Integer[nums.length];\n        for (int i = nums.length-1; i >=0; i--) {\n            int k = nums[i]-min-1;\n            int c = 0;\n            do {\n                c += count[k];\n                k -= (-k&k);\n            } while (k > 0);\n            result[i] = c;\n            \n            k = nums[i]-min;\n            while (k < count.length) {\n                count[k]++;\n                k += (-k&k);\n            }\n        }\n        \n        return Arrays.asList(result);\n    }\n}",
        "solution_c": "typedef struct _SmallerValueCount {\n    _SmallerValueCount(const int &value, const int &originalIndex) :\n        mValue(value), mOriginalIndex(originalIndex) {}\n    \n    int mValue = 0;\n    int mOriginalIndex = 0;\n} SmallerValueCount;\n\nclass Solution {\npublic:\n    vector<int> countSmaller(vector<int>& nums) {\n        vector<SmallerValueCount> convertedNums;\n        convertedNums.reserve(nums.size());\n\n        for (int i = 0; i < nums.size(); ++i)\n            convertedNums.emplace_back(SmallerValueCount(nums[i], i));\n\n        vector<int> smallerCounts(convertedNums.size(), 0);\n        merge_sort(convertedNums, smallerCounts, 0, nums.size() - 1);\n\n        return smallerCounts;\n    }\n\n    void merge_sort(vector<SmallerValueCount> &nums, vector<int> &smallerCounts, const int &left, const int &right) {\n        if (left >= right)\n            return;\n        const auto mid = (left + right) / 2;\n        merge_sort(nums, smallerCounts, left, mid);\n        merge_sort(nums, smallerCounts, mid+1, right);\n        merge(nums, smallerCounts, left, mid, right);\n    }\n\n    void merge(vector<SmallerValueCount> &nums, vector<int> &smallerCounts, const int &left, const int &mid, const int &right)\n    {\n        vector<SmallerValueCount> buffer;\n        buffer.reserve(right - left + 1);\n\n        int i = left, j = mid + 1;\n        int smallerCount = 0;\n        while (i <= mid && j <= right)\n            if (nums[i].mValue > nums[j].mValue)\n            {\n                ++smallerCount;\n                buffer.push_back(nums[j]);\n                ++j;\n            }\n            else\n            {\n                smallerCounts[nums[i].mOriginalIndex] += smallerCount;\n                buffer.push_back(nums[i]);\n                ++i;\n            }\n\n        while (i <= mid)\n        {\n            smallerCounts[nums[i].mOriginalIndex] += smallerCount;\n            buffer.push_back(nums[i]);\n            ++i;\n        }\n\n        while (j <= right)\n        {\n            buffer.push_back(nums[j]);\n            ++j;\n        }\n\n        std::move(std::begin(buffer), std::end(buffer), std::next(std::begin(nums), left));\n    }\n\n};"
    },
    {
        "title": "01 Matrix",
        "algo_input": "Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.\n\nThe distance between two adjacent cells is 1.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput: [[0,0,0],[0,1,0],[0,0,0]]\n\n\nExample 2:\n\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput: [[0,0,0],[0,1,0],[1,2,1]]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 104\n\t1 &lt;= m * n &lt;= 104\n\tmat[i][j] is either 0 or 1.\n\tThere is at least one 0 in mat.\n\n",
        "solution_py": "class Solution:\n    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n        if not mat or not mat[0]:\n            return []\n\n        m, n = len(mat), len(mat[0])\n        queue = deque()\n        MAX_VALUE = m * n\n        \n        # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n        for i in range(m):\n            for j in range(n):\n                if mat[i][j] == 0:\n                    queue.append((i, j))\n                else:\n                    mat[i][j] = MAX_VALUE\n        \n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n        \n        while queue:\n            row, col = queue.popleft()\n            for dr, dc in directions:\n                r, c = row + dr, col + dc\n                if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n                    queue.append((r, c))\n                    mat[r][c] = mat[row][col] + 1\n        \n        return mat",
        "solution_js": "/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nvar updateMatrix = function(mat) {\n  const rows = mat.length,\n        cols = mat[0].length;\n  \n  if (!rows) return mat;\n  \n  const queue = new Queue();\n  const dist = Array.from({length: rows}, () => new Array(cols).fill(Infinity));\n  \n  for (let i = 0; i < rows; i++) {\n    for (let j = 0; j < cols; j++) {\n      if (!mat[i][j]) {\n        dist[i][j] = 0;\n        queue.enqueue([i, j]);\n      }\n    }\n  }\n  \n  const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];\n  \n  while (!queue.isEmpty()) {\n    const [ row, col ] = queue.dequeue();\n    for (let i = 0; i < 4; i++) {\n      const nRow = row + dirs[i][0],\n            nCol = col + dirs[i][1];\n      \n      if (nRow < 0 || nCol < 0 || nRow >= rows || nCol >= cols) continue;\n      \n      if (dist[nRow][nCol] > dist[row][col] + 1) {\n        dist[nRow][nCol] = dist[row][col] + 1;\n        queue.enqueue([nRow, nCol]);\n      }\n    }\n  }\n  \n  return dist;\n};",
        "solution_java": "class Solution {\n//  BFS\n// We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it.\n    boolean visited[][];\n    \n    // Could also convert the indexes to a single number by mat[0].length * i + j.\n    class Pair{\n        int x;\n        int y;\n        Pair(int x, int y){\n            this.x = x;\n            this.y = y;\n        }\n    }\n    public int[][] updateMatrix(int[][] mat) {\n        int level = 0;\n        visited = new boolean[mat.length][mat[0].length];\n        Queue<Pair> q = new ArrayDeque<>();\n        // Addition of all pairs in mat that have 0.\n        for(int i = 0; i < mat.length; i++){\n            for(int j = 0; j < mat[0].length; j++){\n                if(mat[i][j] == 0){\n                    visited[i][j] = true;\n                    q.add(new Pair(i, j));\n                }\n            }\n        }\n        while(q.size()>0){\n            int size = q.size();\n            while(size-- > 0){\n                Pair p = q.remove();\n                mat[p.x][p.y] = level;\n                if(p.x > 0 && visited[p.x - 1][p.y] == false){\n                    visited[p.x-1][p.y] = true;\n                    q.add(new Pair(p.x-1, p.y));\n                }\n                if(p.x < mat.length - 1 && visited[p.x + 1][p.y] == false){\n                    visited[p.x+1][p.y] = true;\n                    q.add(new Pair(p.x+1, p.y));\n                    \n                }\n                if(p.y > 0 && visited[p.x][p.y-1] == false){\n                    visited[p.x][p.y-1] = true;\n                    q.add(new Pair(p.x, p.y-1));\n                    \n                }\n                if(p.y < mat[0].length-1 && visited[p.x][p.y + 1] == false){\n                    visited[p.x][p.y+1] = true;\n                    q.add(new Pair(p.x, p.y + 1));\n                }\n            }\n            level++;\n        }\n        return mat;\n    }\n}",
        "solution_c": "class Solution {\n   bool isValid(vector<vector<int>>& grid,int r,int c,int nr,int nc,int m,int n){\n        if(nr>=0 && nc>=0 && nr<m && nc<n && grid[nr][nc]==-1){\n            if(grid[r][c]==0)\n                grid[nr][nc]=1;\n            else\n                grid[nr][nc]=grid[r][c]+1;\n            return 1;\n        }\n        return 0;\n    }\npublic:\n    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n        queue<pair<int,int>> q;\n        int m = mat.size();\n        int n = mat[0].size();\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                if(mat[i][j]==0)\n                    q.push({i,j});\n                else\n                    mat[i][j]=-1;\n            }\n        }\n        while(!q.empty()){\n            auto per = q.front();\n            int r = per.first;\n            int c = per.second;\n            // if()\n            q.pop();\n            if(isValid(mat,r,c,r-1,c,m,n)){\n                q.push({r-1,c});\n            }\n            if(isValid(mat,r,c,r+1,c,m,n)){\n                q.push({r+1,c});\n            }\n            if(isValid(mat,r,c,r,c-1,m,n)){\n                q.push({r,c-1});\n            }\n            if(isValid(mat,r,c,r,c+1,m,n)){\n                q.push({r,c+1});\n            }\n\n        }\n        return mat;\n    }\n};"
    },
    {
        "title": "Determine Whether Matrix Can Be Obtained By Rotation",
        "algo_input": "Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.\n\n\nExample 2:\n\nInput: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput: false\nExplanation: It is impossible to make mat equal to target by rotating mat.\n\n\nExample 3:\n\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == mat.length == target.length\n\tn == mat[i].length == target[i].length\n\t1 &lt;= n &lt;= 10\n\tmat[i][j] and target[i][j] are either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n        \n        # if already equal\n        if target == mat:\n            return True\n        # there are 4 different rotation with 90 deg. \n        # We need to check at most 3 more rotation.\n        for i in range(3):\n            # transpose the matrix by swap row and col values.\n            for j in range(len(mat)):\n                for k in range(j+1, len(mat)):\n                    mat[j][k], mat[k][j] = mat[k][j], mat[j][k]\n                # Reflect the row by reverse it.\n                mat[j] = mat[j][::-1]\n            # now the matrix is roteted; check if they're alike.\n            if target == mat:\n                return True\n        return False",
        "solution_js": "var findRotation = function(mat, target) {\n    let width = mat[0].length;\n    let height = mat.length;\n    \n    let normal = true;\n    let rightOneTime = true;\n    let rightTwoTimes = true;\n    let rightThreeTimes = true;\n    for (let i = 0; i < height; i++)  {\n        for (let j = 0; j < width; j++) {\n            // don't rotate mat\n            if (mat[i][j] !== target[i][j]) {\n                normal = false;\n            }\n            // rotate mat right 1 time\n            if (mat[i][j] !== target[j][width - 1 - i]) {\n                rightOneTime = false;\n            }\n            // rotate mat right 2 times\n            if (mat[i][j] !== target[height - 1 - i][width - 1 - j]) {\n                rightTwoTimes = false;\n            }\n            // rotate mat right 3 times\n            if (mat[i][j] !== target[height - 1 - j][i]) {\n                rightThreeTimes = false;\n            }\n        }\n    }\n    return normal || rightOneTime || rightTwoTimes || rightThreeTimes;\n};",
        "solution_java": "class Solution {\n    public boolean findRotation(int[][] mat, int[][] target) {\n        if (mat == target) return true;\n        int n = mat.length;\n        int[] res[] = new int[n][n];\n        for (int i = 0; i < n; i++) { //clockwise 90\n            for (int j = 0; j < n; j++) {\n                res[i][j] = mat[n - 1 - j][i];\n            }\n        }\n\n        int[] res2[] = new int[n][n];\n        for (int i = 0; i < n; i++) { //clockwise 180\n            for (int j = 0; j < n; j++) {\n                res2[i][j] = res[n - 1 - j][i];\n            }\n        }\n\n        int[] res3[] = new int[n][n];\n        for (int i = 0; i < n; i++) { //clockwise 270\n            for (int j = 0; j < n; j++) {\n                res3[i][j] = res2[n - 1 - j][i];\n            }\n        }\n\n        //compare to 90,180,270 and itself\n        if(Arrays.deepEquals(target, res) || Arrays.deepEquals(target, res2) || Arrays.deepEquals(target, res3) || Arrays.deepEquals(target, mat) ){\n            return true;\n        }\n        return false;\n    }\n}\n\n// Arrays.deepEquals() use for matrix",
        "solution_c": "class Solution {\npublic:\n    bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) {\n        int n = mat.size();\n        if(mat == target) { // rotation by 0 degree.\n            return true;\n        }\n\n        int deg = 3; // more rotations with 90, 180, 270 degree's.\n\n        while(deg --) {\n            for(int i = 0; i < n; i ++) {\n                for(int j = i; j < n; j ++) {\n                    swap(mat[i][j], mat[j][i]); // transpose of matrix.\n                }\n            }\n            for(int i = 0; i < n; i ++) {\n                reverse(mat[i].begin(),mat[i].end()); // reverse each row.\n            }\n            if(mat == target) {\n                return true;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Map of Highest Peak",
        "algo_input": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells.\n\n\n\tIf isWater[i][j] == 0, cell (i, j) is a land cell.\n\tIf isWater[i][j] == 1, cell (i, j) is a water cell.\n\n\nYou must assign each cell a height in a way that follows these rules:\n\n\n\tThe height of each cell must be non-negative.\n\tIf the cell is a water cell, its height must be 0.\n\tAny two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n\n\nFind an assignment of heights such that the maximum height in the matrix is maximized.\n\nReturn an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.\n\n&nbsp;\nExample 1:\n\n\n\nInput: isWater = [[0,1],[0,0]]\nOutput: [[1,0],[2,1]]\nExplanation: The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.\n\n\nExample 2:\n\n\n\nInput: isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput: [[1,1,0],[0,1,1],[1,2,2]]\nExplanation: A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == isWater.length\n\tn == isWater[i].length\n\t1 &lt;= m, n &lt;= 1000\n\tisWater[i][j] is 0 or 1.\n\tThere is at least one water cell.\n\n",
        "solution_py": "class Solution:\n    def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n        arr = collections.deque()\n        m, n = len(isWater), len(isWater[0])\n        for i in range(m):\n            for j in range(n):\n                if isWater[i][j] == 1:\n                    arr.append((0, i, j))\n                    \n        ans = [[-1] * n for _ in range(m)]\n        while arr:\n            val, x, y = arr.popleft() \n            if ans[x][y] != -1: continue\n            ans[x][y] = val\n            for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n                xx, yy = x+dx, y+dy\n                if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1:\n                    arr.append((val+1, xx, yy))\n        return ans",
        "solution_js": "var highestPeak = function(isWater) {\n    const RN = isWater.length, CN = isWater[0].length;\n    const output = [...Array(RN)].map(() => Array(CN).fill(-1));\n    const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n    let queue = []\n\n    for(let r = 0; r < RN; r++) {\n        for(let c = 0; c < CN; c++) {\n            if(isWater[r][c]) {\n                queue.push([r, c]);\n                output[r][c] = 0;\n            }\n        }\n    }\n\n    while(queue.length) {\n        const next = []\n\n        for(let [r, c] of queue) {\n            for(let [dr, dc] of dir) {\n                dr += r;\n                dc += c;\n                if(dr < 0 || dc < 0 || dr >= RN || dc >= CN || output[dr][dc] !== -1) continue;\n                output[dr][dc] = output[r][c] + 1;\n                next.push([dr, dc]);\n            }\n        }\n        queue = next;\n    }\n    return output;\n};",
        "solution_java": "class Solution {\n    \n    static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};\n    int rows;\n    int cols;\n    int[][] isWater;\n\n    \n    public int[][] highestPeak(int[][] isWater) {\n        this.isWater = isWater;\n        rows = isWater.length;\n        cols = isWater[0].length;\n        \n\n        int[][] heightCells = new int[rows][cols];\n        \n        //store the coordinate of water cell\n        Queue<int[]> queue = new LinkedList();\n        \n        for(int r = 0; r < rows; r++){\n            for(int c = 0; c < cols; c++){\n                if(isWater[r][c] == 1){\n                    \n                    //mark as water\n                    heightCells[r][c] = 0;\n                    \n                    //add water coordinate\n                    queue.add(new int[]{r, c});\n                } else{\n                    //mark default value for land\n                    heightCells[r][c] = -1;  \n                }\n            }\n        }\n\n        \n        /*\n        * Approach\n        * 1. start from every water source, \n             update their neighbor height\n        * 2. add each neighbours which was not processed earlier\n          3. do it every cell is processed\n        */\n        bfs(queue, heightCells);\n        \n        \n        return heightCells;\n    }\n    \n    private void bfs(Queue<int[]> queue, int[][] heightCells){\n        \n        while(!queue.isEmpty()){\n            int[] cell = queue.remove();\n \n            //increment height of neighbor cell in all 4 direction \n            //e.g, left, right, up, down\n            for(int[] dir : DIRECTION){\n                \n                int newRow = cell[0] + dir[0];\n                int newCol = cell[1] + dir[1]; \n                \n                //check new coordinate of cell inside the grid or not\n                if(!isInsideGrid(newRow, newCol)) continue;\n                \n                //check already handled\n                if(heightCells[newRow][newCol] != -1) continue;\n\n                //increament, \n                heightCells[newRow][newCol] =  heightCells[cell[0]][cell[1]] + 1;\n                \n                //to handle the neighbour of this new cell\n                queue.add(new int[]{newRow, newCol});\n            }\n        \n        }\n    }\n    \n    private boolean isInsideGrid(int row, int col){\n        return row >= 0 && row < rows && col >= 0 && col < cols;\n    } \n}",
        "solution_c": "class Solution {\npublic:\n\n    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {\n        int r = isWater.size();\n        int c = isWater[0].size();\n        queue <pair<int,int>> curr;\n\n        for (int i = 0; i < r; i++) {\n            for (int j = 0; j < c; j++) {\n                //set the land cell to -1 (not visited)\n                if (isWater[i][j] == 0) {\n                    isWater[i][j] = -1;\n                }\n                //set the water cell to zero and to queue\n                else {\n                    isWater[i][j] = 0;\n                    curr.push({i, j});\n                }\n            }\n        }\n\n        int hill = 0;\n        while (!curr.empty()) {\n            int len = curr.size();\n\n            for (int k = 0; k < len; k++) {\n\n                //for each cell check its 4 boundary cells\n                //if it is not visited, increase its hill by 1\n                pair <int, int> fnt = curr.front(); curr.pop();\n                int i = fnt.first, j = fnt.second;\n\n                //top cell\n                if (i > 0 && isWater[i - 1][j] == -1) {\n                    isWater[i - 1][j] = hill + 1;\n                    curr.push({i-1, j});\n                }\n                //bottom cell\n                if ((i < r - 1) && (isWater[i + 1][j] == -1)) {\n                    isWater[i + 1][j] = hill + 1;\n                    curr.push({i+1, j});\n                }\n                //left cell\n                if (j > 0 && (isWater[i][j - 1] == -1)) {\n                    isWater[i][j - 1] = hill + 1;\n                    curr.push({i, j-1});\n                }\n                //right cell\n                if ((j < c - 1) && (isWater[i][j + 1] == -1)) {\n                    isWater[i][j + 1] = hill + 1;\n                    curr.push({i, j+1});\n                }\n            }\n\n            //after 1 complete round increase the height of the hill\n            hill += 1;\n        }\n\n        return isWater;\n    }\n};"
    },
    {
        "title": "Path Crossing",
        "algo_input": "Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.\n\nReturn true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: path = \"NES\"\nOutput: false \nExplanation: Notice that the path doesn't cross any point more than once.\n\n\nExample 2:\n\nInput: path = \"NESWW\"\nOutput: true\nExplanation: Notice that the path visits the origin twice.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= path.length &lt;= 104\n\tpath[i] is either 'N', 'S', 'E', or 'W'.\n\n",
        "solution_py": "class Solution:\n    def isPathCrossing(self, path: str) -> bool:\n        c = set()\n        x,y = 0,0\n        c.add((x,y))\n        for i in path:\n            if i == 'N':\n                y+=1\n            elif i == 'E':\n                x+=1\n            elif i == 'W':\n                x-=1\n            else:\n                y-=1\n            if (x,y) in c:\n                return True\n            else:\n                c.add((x,y))\n        return False",
        "solution_js": "var isPathCrossing = function(path) {\n    let set = new Set();\n    let curr = [0, 0]\n    \n    let start = `${curr[0]}, ${curr[1]}`\n    set.add(start)\n    \n    for (let el of path) {\n        if (el === 'N') curr[1]++;\n        else if (el === 'S') curr[1]--;\n        else if (el === 'E') curr[0]++;\n        else curr[0]--;\n        \n        let key = `${curr[0]}, ${curr[1]}`\n        if (set.has(key)) return true;\n        set.add(key)\n    }\n    \n    return false;\n};",
        "solution_java": "// Path crossing\n// Leetcode\n\nclass Solution {\n    public boolean isPathCrossing(String path) {\n        Set<String> visited = new HashSet<>();\n        int x = 0, y = 0;\n        visited.add(x + \",\" + y);\n        for (char c : path.toCharArray()) {\n            if (c == 'N') y++;\n            else if (c == 'S') y--;\n            else if (c == 'E') x++;\n            else x--;\n            if (visited.contains(x + \",\" + y)) return true;\n            visited.add(x + \",\" + y);\n        }\n        return false;       \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool isPathCrossing(string path) {\n\n        set<pair<int, int>>st;\n\n        int x=0,y=0;\n\n        st.insert({0, 0});\n\n        for(int i=0;i<path.length();i++){\n\n            if(path[i]=='N'){\n                x++;\n            }\n\n            else if(path[i]=='S'){\n                x--;\n            }\n\n            else if(path[i]=='E'){\n                y++;\n            }\n\n            else{\n                y--;\n            }\n\n            //if pair find at any point, return true\n            if(st.find({x,y}) != st.end()){\n                return 1;\n            }\n            //insert the pair\n            st.insert({x, y});\n        }\n        return 0;\n    }\n};"
    },
    {
        "title": "Valid Arrangement of Pairs",
        "algo_input": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 &lt;= i &lt; pairs.length, we have endi-1 == starti.\n\nReturn any valid arrangement of pairs.\n\nNote: The inputs will be generated such that there exists a valid arrangement of pairs.\n\n&nbsp;\nExample 1:\n\nInput: pairs = [[5,1],[4,5],[11,9],[9,4]]\nOutput: [[11,9],[9,4],[4,5],[5,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 9 == 9 = start1 \nend1 = 4 == 4 = start2\nend2 = 5 == 5 = start3\n\n\nExample 2:\n\nInput: pairs = [[1,3],[3,2],[2,1]]\nOutput: [[1,3],[3,2],[2,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 3 == 3 = start1\nend1 = 2 == 2 = start2\nThe arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.\n\n\nExample 3:\n\nInput: pairs = [[1,2],[1,3],[2,1]]\nOutput: [[1,2],[2,1],[1,3]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 2 == 2 = start1\nend1 = 1 == 1 = start2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pairs.length &lt;= 105\n\tpairs[i].length == 2\n\t0 &lt;= starti, endi &lt;= 109\n\tstarti != endi\n\tNo two pairs are exactly the same.\n\tThere exists a valid arrangement of pairs.\n\n",
        "solution_py": "#Hierholzer Algorithm\nfrom collections import defaultdict\nclass Solution:\n    def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n        G = defaultdict(list)\n        din = defaultdict(int)\n        dout = defaultdict(int)\n        for v, w in pairs:\n            G[v].append(w)\n            dout[v] += 1\n            din[w] += 1\n        start = pairs[0][0]\n        for v in G:\n            if din[v]+1 == dout[v]:\n                start = v\n        route = []\n        def dfs(v):\n            while G[v]:\n                w = G[v].pop()\n                dfs(w)\n            route.append(v)\n        dfs(start)\n        route.reverse()\n        return [[route[i],route[i+1]] for i in range(len(route)-1)]",
        "solution_js": "var validArrangement = function(pairs) {\n  let graph = {};\n  let degrees = {}; // outdegree: positive, indegree: negative\n  for (var [x, y] of pairs) {\n    if (!graph[x]) graph[x] = [];\n    graph[x].push(y);\n    if (degrees[x] === undefined) degrees[x] = 0;\n    if (degrees[y] === undefined) degrees[y] = 0;\n    degrees[x]++;\n    degrees[y]--;\n  }\n  let start = pairs[0][0];\n  for (var [x] of pairs) {\n    if (degrees[x] === 1) start = x; // one extra outdegree\n  }\n  let ans = [];\n  dfs(start);\n\n  function dfs(node) {\n    while ((graph[node] || []).length) {\n      let neighbor = graph[node].pop();\n      dfs(neighbor);\n      ans.push([node, neighbor]);\n    }\n  }\n  return ans.reverse();\n};",
        "solution_java": "class Solution {\n    public int[][] validArrangement(int[][] pairs) {\n        int n = pairs.length;\n        \n        int[][] ans = new int[n][2];\n        for (int[] a : ans) {\n            a[0] = -1;\n            a[1] = -1;\n        }\n        \n        Map<Integer, Integer> outdegree = new HashMap<>();\n        Map<Integer, Deque<Integer>> out = new HashMap<>();\n        \n        for (int[] pair : pairs) {\n            outdegree.put(pair[0], outdegree.getOrDefault(pair[0], 0) + 1);\n            outdegree.put(pair[1], outdegree.getOrDefault(pair[1], 0) - 1);\n            \n            out.computeIfAbsent(pair[0], k -> new ArrayDeque<>());\n            out.computeIfAbsent(pair[1], k -> new ArrayDeque<>());\n            \n            out.get(pair[0]).addLast(pair[1]);\n        }\n        \n        for (Map.Entry<Integer, Integer> entry : outdegree.entrySet()) {\n            if (entry.getValue() == 1) ans[0][0] = entry.getKey();\n            if (entry.getValue() == -1) ans[n - 1][1] = entry.getKey();\n        }\n        \n        if (ans[0][0] == -1) {\n            ans[0][0] = pairs[0][0];\n            ans[n - 1][1] = pairs[0][0];\n        }\n        \n        int i = 0;\n        int j = n - 1;\n        while (i < j) {\n            int from = ans[i][0];\n            \n            Deque<Integer> toList = out.get(from);\n            \n            if (toList.size() == 0) {\n                ans[j][0] = ans[--i][0];\n                ans[--j][1] = ans[j + 1][0];\n            } else {\n                ans[i++][1] = toList.removeLast();\n                ans[i][0] = ans[i - 1][1];\n            }\n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {\n        int m = pairs.size();\n        // Eulerian Path\n        unordered_map<int, stack<int>> adj;\n        unordered_map<int, int> in;\n        unordered_map<int, int> out;\n        // reserve spaces for unordered_map may help in runtime.\n        adj.reserve(m);\n        in.reserve(m);\n        out.reserve(m);\n        for (int i = 0; i < m; i++) {\n            int u = pairs[i][0], v = pairs[i][1];\n            in[v]++;\n            out[u]++;\n            adj[u].push(v);\n        }\n        // find the starting node\n        int start = -1;\n        for (auto& p : adj) {\n            int i = p.first;\n            if (out[i] - in[i] == 1) start = i;\n        }\n        if (start == -1) {\n            // Eulerian Circuit -> start at any node\n            start = adj.begin()->first;\n        }\n        vector<vector<int>> ans;\n        euler(adj, ans, start);\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\nprivate:\n    void euler(unordered_map<int, stack<int>>& adj, vector<vector<int>>& ans, int curr) {\n        auto& stk = adj[curr];\n        while (!stk.empty()) {\n            int nei = stk.top();\n            stk.pop();\n            euler(adj, ans, nei);\n            // postorder\n            ans.push_back({curr, nei});\n        }\n    }\n};"
    },
    {
        "title": "Car Fleet",
        "algo_input": "There are n cars going to the same destination along a one-lane road. The destination is target miles away.\n\nYou are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).\n\nA car can never pass another car ahead of it, but it can catch up to it&nbsp;and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).\n\nA car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.\n\nIf a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.\n\nReturn the number of car fleets that will arrive at the destination.\n\n&nbsp;\nExample 1:\n\nInput: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\nOutput: 3\nExplanation:\nThe cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\nThe car starting at 0 does not catch up to any other car, so it is a fleet by itself.\nThe cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\nNote that no other cars meet these fleets before the destination, so the answer is 3.\n\n\nExample 2:\n\nInput: target = 10, position = [3], speed = [3]\nOutput: 1\nExplanation: There is only one car, hence there is only one fleet.\n\n\nExample 3:\n\nInput: target = 100, position = [0,2,4], speed = [4,2,1]\nOutput: 1\nExplanation:\nThe cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\nThen, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == position.length == speed.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt; target &lt;= 106\n\t0 &lt;= position[i] &lt; target\n\tAll the values of position are unique.\n\t0 &lt; speed[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n        def computeArrivalTime(curr_pos, curr_speed):\n            nonlocal target\n            return (target - curr_pos) / curr_speed\n            # avoid integer division, as a car may arrive at 5.2s and another at 5.6s\n\n        cars = list(zip(position, speed))\n        cars.sort(key=lambda x: x[0], reverse=True)\n        arrival_bound = None # time upper bound\n        fleet = 0\n        for pos, sp in cars:\n            curr_arrival = computeArrivalTime(pos, sp)\n            if not arrival_bound or curr_arrival > arrival_bound:\n                arrival_bound = curr_arrival\n                fleet += 1\n        return fleet\n    # time O(n logn): sort = (nlogn); loop = (n)\n    # space O(n): depend on sort",
        "solution_js": "var carFleet = function(target, position, speed) {\n    for (let i = 0 ; i < position.length ; i ++) {\n        position[i] = [target - position[i], speed[i]]\n    }\n    position.sort((a, b) => { return a[0] - b[0] })\n    let count = 1, prev = position[0][0] / position[0][1]\n    for (let i = 1 ; i < position.length ; i ++) {\n\t\t// if the time taken is longer then it will cause another fleet\n        if (position[i][0] / position[i][1] > prev) {\n            count ++\n            prev = position[i][0] / position[i][1]\n        }\n    }\n    \n    return count\n};",
        "solution_java": "class Solution {\n    class pair implements Comparable<pair>{\n        int pos;\n        double time;\n        pair(int pos,double time){\n            this.pos=pos;\n            this.time=time;\n        }\n        public int compareTo(pair o){\n            return o.pos-this.pos;\n        }\n    }\n    public int carFleet(int target, int[] position, int[] speed) {\n        double []arr=new double[position.length];\n        for(int i=0;i<position.length;i++){\n            arr[i]=(target-position[i])*1.0/speed[i];\n        }\n        PriorityQueue<pair>pq=new PriorityQueue<>();\n        for(int i=0;i<position.length;i++){\n            pq.add(new pair(position[i],arr[i]));\n        }\n        double updatetime=0;\n        int fleet=0;\n        while(pq.size()>0){\n            pair rem=pq.remove();\n            if(updatetime<rem.time){\n               fleet++;\n               updatetime=rem.time;\n            }\n        }\n        return fleet;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int carFleet(int target, vector<int>& position, vector<int>& speed) {\n        \n        int n = position.size();\n        vector<pair<int,int>> cars;\n        \n        for(int i=0; i<n; i++)cars.push_back({position[i], speed[i]});\n        \n        sort(cars.begin(),cars.end());\n        \n        int start=0;\n        int mid=0;\n        int fleet = n;\n        \n        double times[n];\n        \n        for(int i=n-1; i>=0; i--){\n            times[i] =((double) (target-cars[i].first)/cars[i].second);\n            if(i<n-1)times[i] = max(times[i],times[i+1]);\n        }\n        \n        while(mid<n){            \n            double timeA = times[start];\n            double timeB = times[mid];\n            //cout<<timeA<<\" \"<<timeB<<endl;\n            if(mid-start+1 == 2){\n                if(timeA<=timeB)fleet--;\n                start++;\n            }\n            mid++;\n        }\n        \n        return fleet;\n        \n    }\n};"
    },
    {
        "title": "Maximum Value after Insertion",
        "algo_input": "You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.\n\nYou want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign.\n\n\n\tFor example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.\n\tIf n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.\n\n\nReturn a string representing the maximum value of n​​​​​​ after the insertion.\n\n&nbsp;\nExample 1:\n\nInput: n = \"99\", x = 9\nOutput: \"999\"\nExplanation: The result is the same regardless of where you insert 9.\n\n\nExample 2:\n\nInput: n = \"-13\", x = 2\nOutput: \"-123\"\nExplanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n.length &lt;= 105\n\t1 &lt;= x &lt;= 9\n\tThe digits in n​​​ are in the range [1, 9].\n\tn is a valid representation of an integer.\n\tIn the case of a negative n,​​​​​​ it will begin with '-'.\n\n",
        "solution_py": "class Solution:\n    def maxValue(self, n: str, x: int) -> str:\n        if int(n)>0:\n            ans = \"\"\n            flag = False\n            for i in range(len(n)):\n                if int(n[i])>=x:\n                    ans += n[i]\n                else:\n                    a = n[:i]\n                    b = n[i:]\n                    ans = a+str(x)+b\n                \n                    flag = True\n                    break\n            if not flag:\n                ans += str(x)\n        else:\n            n = n[1:]\n            ans = \"\"\n            flag = False\n            for i in range(len(n)):\n                if int(n[i])<=x:\n                    ans += n[i]\n                else:\n                    a = n[:i]\n                    b = n[i:]\n                    ans = a+str(x)+b\n            \n                    flag = True\n                    break\n            if not flag:\n                ans += str(x)\n            ans = \"-\"+ans\n        \n        return ans\n                    ",
        "solution_js": "var maxValue = function(n, x) {\n    let i;\n\n    // if the number if positive, find the first\n    // number that is less than x\n    if (n[0] !== '-') {\n        for (i = 0; i < n.length; i++) {\n            if (Number(n[i]) < x) break;\n        }        \n    \n    // if the number is negative, find the first\n    // number that is greater than x\n    } else {\n        for (i = 1; i < n.length; i++) {\n            if (Number(n[i]) > x) break;\n        }\n    }\n    \n    // return the string with x inserted at the found index\n    return n.slice(0, i) + x + n.slice(i)\n};\n\n\n///////////////// short hand ////////////////////\n\n\nvar maxValue = function(n, x) {\n    let i;\n    if (n[0] !== '-') {\n        for (i = 0; i < n.length; i++) {\n            if (Number(n[i]) < x) break;\n        }        \n    } else {\n        for (i = 1; i < n.length; i++) {\n            if (Number(n[i]) > x) break;\n        }\n    }\n    return n.slice(0, i) + x + n.slice(i)\n};",
        "solution_java": "class Solution {\n    public String maxValue(String n, int x) {\n        StringBuilder res= new StringBuilder();\n        int i=0, j=0;\n        if(n.charAt(0)=='-'){\n            res.append(n.charAt(0));\n            for(j=1; j<n.length(); j++){\n               char ch= n.charAt(j);\n               int val= ch-'0';\n               if(val<= x){  \n                  res.append(ch);\n               }else{\n                   res.append(x);\n                   res.append(ch);\n                   res.append(n.substring(j+1));\n                   break;\n               }\n           }\n            if(j==n.length()){\n                res.append(x);\n            }\n        }\n        else{\n            for(i=0; i<n.length(); i++){\n               char ch= n.charAt(i);\n               int val= ch-'0';\n                \n               if(val>= x){  \n                  res.append(ch);\n               }else{\n                   res.append(x);\n                   res.append(ch);\n                   res.append(n.substring(i+1));\n                   break;\n               }\n           }\n            if(i==n.length()){\n                res.append(x);\n            }\n        }\n        return res.toString();\n    }\n}",
        "solution_c": "class Solution { \n\npublic:\nstring maxValue(string s, int x) {\n    int p=0,flag=0;\n    char ch='0'+x;  //change int to char\n    string str;\n\t\n    if(s[0]=='-')\n    {   //for negative numbers\n\t     for(int i=1;i<s.size();i++)\n        {\n          if(ch<s[i] && !flag){\n            str+=ch;\n            str+=s[i];\n            flag=1; \n          }\n          else \n           str+=s[i];\n        }\n        if(!flag) str+=ch;\n        return '-'+str;\n    }\n    \n\t// if number is positive\n    for(int i=0;i<s.size();i++)\n    {\n       if(ch>s[i] && !flag){\n         str+=ch;\n         str+=s[i];\n         flag=1;\n       }\n       else \n        str+=s[i];\n    }    \n    if(!flag) str+=ch;\n    return str;\n  }\n};"
    },
    {
        "title": "Camelcase Matching",
        "algo_input": "Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.\n\nA query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.\n\n&nbsp;\nExample 1:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput: [true,false,true,true,false]\nExplanation: \"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".\n\n\nExample 2:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput: [true,false,true,false,false]\nExplanation: \"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".\n\n\nExample 3:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput: [false,true,false,false,false]\nExplanation: \"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pattern.length, queries.length &lt;= 100\n\t1 &lt;= queries[i].length &lt;= 100\n\tqueries[i] and pattern consist of English letters.\n\n",
        "solution_py": "class Solution:\n    def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n        res, N = [], len(pattern)\n\t\t\n        for query in queries:\n\t\t\n            if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N:\n                res.append(False)\n            \n            else:\n                res.append(True)\n\t\t\t\t\n        return res\n                \n        \n\t\t\n    def LCS(self, A, B):\n        N, M = len(A), len(B)\n        d = [[0 for _ in range(M+1)] for _ in range(N+1)]\n\n        for i in range(1, N+1):\n            for j in range(1, M+1):\n\t\t\t\n                if A[i - 1] == B[j - 1]:\n                    d[i][j] = 1 + d[i-1][j-1]\n\n                else:\n                    d[i][j] = max(d[i-1][j], d[i][j-1])\n        return d[-1][-1]\n\n\n    \n    def upLetter(self, w):\n        count = 0\n        for c in w:\n            if c.isupper():\n                count += 1\n        return count",
        "solution_js": "var camelMatch = function(queries, pattern) {\n    function camelMatch(q, p){\n        let qlist=[]\n        let plist=[]\n        for(let a of q) if(a<='Z') qlist.push(a);\n        for(let a of p) if(a<='Z') plist.push(a);\n        return plist.join('') === qlist.join('')\n    }\n    function seqMatch(q, p){\n        if(!camelMatch(p,q)) return false\n        let pi=0\n        for(let qi=0; qi<q.length; qi++){\n            if(pi<p.length && p[pi]===q[qi]) pi++\n        }\n        return pi===p.length\n    }\n\n    return queries.map(q=>seqMatch(q, pattern))\n}",
        "solution_java": "class Solution {\n    public List<Boolean> camelMatch(String[] queries, String pattern) {\n      List<Boolean> list = new ArrayList<>();\n\n      for (var q : queries) {\n         int index = 0;\n         boolean flag = true;\n         for (var c : q.toCharArray()) {\n            if(index < pattern.length() && c == pattern.charAt(index)){\n               index++;\n               continue;\n            }\n            if(c >= 'A' && c <= 'Z'){\n               if(index >= pattern.length() || c != pattern.charAt(index)){\n                  flag = false;\n                  break;\n               }\n            }\n         }\n         flag = flag && index == pattern.length();\n         list.add(flag);\n      }\n      return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<bool> camelMatch(vector<string>& queries, string pattern) {\n        \n        vector<bool> res(queries.size());\n        \n        for (int i = 0; i < queries.size(); i++)\n        {\n            int patRef = 0;\n            bool isCamel = true;\n            \n            for (const char& ltr : queries[i])\n            {\n                if (patRef == pattern.size())\n                {\n                    if (isupper(ltr))\n                    {\n                        isCamel = false;\n                        break;\n                    }\n                }\n                else\n                {\n                    if (isupper(ltr) and isupper(pattern[patRef]) and ltr != pattern[patRef])\n                    {\n                        isCamel = false;\n                        break;\n                    }\n                    else if (islower(ltr) and islower(pattern[patRef]) and ltr == pattern[patRef])\n                        patRef++;\n                    else if (ltr == pattern[patRef])\n                        patRef++;\n                }\n            }\n            \n            if (patRef == pattern.size() and isCamel)\n                res[i] = true;\n        }\n                             \n        return res;\n    }\n};"
    },
    {
        "title": "Decode the Message",
        "algo_input": "You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:\n\n\n\tUse the first appearance of all 26 lowercase English letters in key as the order of the substitution table.\n\tAlign the substitution table with the regular English alphabet.\n\tEach letter in message is then substituted using the table.\n\tSpaces ' ' are transformed to themselves.\n\n\n\n\tFor example, given key = \"happy boy\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -&gt; 'a', 'a' -&gt; 'b', 'p' -&gt; 'c', 'y' -&gt; 'd', 'b' -&gt; 'e', 'o' -&gt; 'f').\n\n\nReturn the decoded message.\n\n&nbsp;\nExample 1:\n\nInput: key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\nOutput: \"this is a secret\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"the quick brown fox jumps over the lazy dog\".\n\n\nExample 2:\n\nInput: key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\nOutput: \"the five boxing wizards jump quickly\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".\n\n\n&nbsp;\nConstraints:\n\n\n\t26 &lt;= key.length &lt;= 2000\n\tkey consists of lowercase English letters and ' '.\n\tkey contains every letter in the English alphabet ('a' to 'z') at least once.\n\t1 &lt;= message.length &lt;= 2000\n\tmessage consists of lowercase English letters and ' '.\n\n",
        "solution_py": "class Solution:\n    def decodeMessage(self, key: str, message: str) -> str:\n        alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n        i=0\n        d={}\n        for j in key:\n            if j!=\" \" and j not in d:\n                d[j]=alpha[i]\n                i+=1\n            if len(d)==26:\n                break\n        res=\"\"\n        d[\" \"]=\" \"\n        for i in message:\n            res+=d[i]\n        return res",
        "solution_js": "var decodeMessage = function(key, message) {\n  let result = ''\n  key = Array.from(new Set(key.split(' ').join('')))\n  const hash = new Map()\n  const alpha = 'abcdefghijklmnopqrstuvwxyz'\n  \n  for (let i = 0; i < alpha.length; i++) {\n    hash.set(key[i], alpha[i])\n  }\n\n  for (let chr of message) {\n    result += hash.get(chr) || ' '\n  }\n    \n  return result\n};",
        "solution_java": "class Solution {\n    public String decodeMessage(String key, String message) {\n        StringBuilder ans = new StringBuilder();//Using String Builder to append the string\n        key = key.replaceAll(\" \", \"\");\n        //Removing the spaces\n        HashMap<Character,Character> letters = new HashMap<>();\n        //Mapping the key into a hashmap.\n        char original = 'a';\n        for (int i = 0; i < key.length() ; i++) {\n            if (!letters.containsKey(key.charAt(i))){\n                letters.put(key.charAt(i),original++);\n            }\n        }\n        //After the first pass all the letters of the key will be mapped with their respective original letters.\n        for (int i = 0; i < message.length(); i++) {\n            if (letters.containsKey(message.charAt(i))){\n                //Now replacing the letters of the message with appropriate letter according to the key\n                ans.append(letters.get(message.charAt(i)));\n            }else{\n                ans.append(message.charAt(i));\n                //This is for characters other than the letters in the key example a space \" \"\n                //They will not be replaced by any letters hence original letter is appended into the StringBuilder\n            }\n        }\n        return ans.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string decodeMessage(string key, string message) {\n        vector <char> alpha {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};\n        int i=0;\n\n        map<char,char> d;\n\n        for(int j=0;j<26;j++){\n            d[alpha[j]]='0';\n        }\n\n        for(int j=0; j<key.size(); j++){\n\n            if(key[j]!=' ' && d[key[j]]=='0'){\n                d[key[j]]=alpha[i];\n                i++;\n            }\n            if (i==26) break;\n        }\n        d[' '] = ' ';\n\n        string res=\"\";\n        for(int i=0; i<message.size(); i++){\n            res += d[message[i]];\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Detect Pattern of Length M Repeated K or More Times",
        "algo_input": "Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.\n\nA pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.\n\nReturn true if there exists a pattern of length m that is repeated k or more times, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,4,4,4,4], m = 1, k = 3\nOutput: true\nExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.\n\n\nExample 2:\n\nInput: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\nOutput: true\nExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.\n\n\nExample 3:\n\nInput: arr = [1,2,1,2,1,3], m = 2, k = 3\nOutput: false\nExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 100\n\t1 &lt;= arr[i] &lt;= 100\n\t1 &lt;= m &lt;= 100\n\t2 &lt;= k &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n        if len(arr) < k*m:\n            return False\n        \n        n = len(arr)\n        pattern = arr[0:m]\n        repeats = 1\n        for i in range(m, n - m + 1, m):\n            if arr[i:i+m] != pattern:\n                break\n            \n            repeats += 1\n            if repeats >= k:\n                return True\n            \n        return self.containsPattern(arr[1:], m, k)",
        "solution_js": "var containsPattern = function(arr, m, k) {\n\tconst origin = arr.join(',');\n\n\treturn arr.some((_, index, array) => {\n\t\tconst check = arr.slice(index, m + index).join(',') + ',';\n\n\t\tindex + k * m > arr.length && array.splice(index);\n\t\tconst target = check.repeat(k).slice(0, -1);\n\t\tif (~origin.indexOf(target)) return true\n\t});\n};",
        "solution_java": "// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n    public boolean containsPattern(int[] arr, int m, int k) {\n        int count = 0;\n        for (int i = 0; i < arr.length - m; i++) {\n            if (arr[i] == arr[i + m]) {\n                count++;\n            } else {\n                count = 0;\n            }\n            if (count == m * (k-1)) {\n                return true;\n            }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool containsPattern(vector<int>& arr, int m, int k) {\n        unordered_map<string, vector<int>> ump;\n        string num = \"\";\n        for(int i = 0; i < arr.size(); ++i)\n            num += to_string(arr[i]);\n        for(int i = 0; i <= num.length() - m; ++i){\n            string str = num.substr(i, m);\n            ump[str].push_back(i);\n        }\n        for(auto it = ump.begin(); it != ump.end(); ++it){\n            if(it->second.size() >= k){\n                bool flag = true;\n                for(int i = 1; i < it->second.size(); ++i){\n                    if(it->second[i] - it->second[i - 1] < m)\n                        flag = false;\n                }\n                if(flag == true)\n                    return true;\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "The k Strongest Values in an Array",
        "algo_input": "Given an array of integers arr and an integer k.\n\nA value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| &gt; |arr[j] - m| where m is the median of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] &gt; arr[j].\n\nReturn a list of the strongest k values in the array. return the answer in any arbitrary order.\n\nMedian is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).\n\n\n\tFor arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.\n\tFor arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.\n\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 &gt; 1.\n\n\nExample 2:\n\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\n\n\nExample 3:\n\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t-105 &lt;= arr[i] &lt;= 105\n\t1 &lt;= k &lt;= arr.length\n\n",
        "solution_py": "class Solution:\n    def getStrongest(self, arr: List[int], k: int) -> List[int]:\n        n = len(arr)\n        medInd = (n-1)//2\n        arr = sorted(arr)\n        med = arr[medInd]\n        \n        start, end = 0, n-1\n        ans = []\n        while start <= end and len(ans) < k:\n            if abs(med - arr[end]) < abs(med - arr[start]):\n                ans.append(arr[start])\n                start += 1\n            else:# abs(med - arr[end]) >= abs(med - arr[start]):\n                # <= because end is always bigger in a sorted array\n                ans.append(arr[end])\n                end -= 1\n        \n        return ans",
        "solution_js": "var getStrongest = function(arr, k) {\n    // sort array so we can easily find median\n    const sorted = arr.sort((a,b) => a-b)\n    // get index of median\n    const medianIndex = Math.floor(((sorted.length-1)/2))\n    // get median\n    const median = sorted[medianIndex]\n\n    // custom sort function following the parameters given us in the description\n    const compareFunction = (a, b) => {\n        if (Math.abs(a-median) > Math.abs(b-median)) {\n            return 1\n        }\n        else if (Math.abs(a-median) === Math.abs(b-median) && a > b) {\n            return 1\n        } else {\n            return -1\n        }\n    }\n\n    // sort array using our custom sort function\n    const strongest = arr.sort(compareFunction).reverse().slice(0,k);\n\n    return strongest;\n};",
        "solution_java": "class Solution {\n    public int[] getStrongest(int[] arr, int k) {\n        int[] result = new int[k];\n        int n = arr.length, left = 0, right = n - 1, idx = 0;\n        Arrays.sort(arr);\n        int median = arr[(n - 1) / 2];\n        while (left <= right) {\n            int diff_l = Math.abs(arr[left] - median);\n            int diff_r = Math.abs(arr[right] - median);\n\n            if (diff_r > diff_l)\n                result[idx++] = arr[right--];\n            else if (diff_l > diff_r)\n                result[idx++] = arr[left++];\n            else if (arr[right] > arr[left])\n                result[idx++] = arr[right--];\n            else\n                result[idx++] = arr[left++];\n            if (idx == k)\n                break;\n        }\n        return result;\n    }\n}",
        "solution_c": "class Solution \n{\npublic:\n    vector<int> getStrongest(vector<int>& arr, int k) \n    {\n        int n=arr.size();\n        sort(arr.begin(),arr.end());\n        int m=arr[(n-1)/2];\n        priority_queue<pair<int,int>> pq;\n        for(auto it: arr)\n        {\n            pq.push({abs(it-m),it});\n        }\n        vector<int> ans;\n        while(k-- && !pq.empty())\n        {\n            ans.push_back(pq.top().second);\n            pq.pop();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Maximum Product Subarray",
        "algo_input": "Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.\n\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n\nA subarray is a contiguous subsequence of the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,3,-2,4]\nOutput: 6\nExplanation: [2,3] has the largest product 6.\n\n\nExample 2:\n\nInput: nums = [-2,0,-1]\nOutput: 0\nExplanation: The result cannot be 2, because [-2,-1] is not a subarray.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t-10 &lt;= nums[i] &lt;= 10\n\tThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n\n",
        "solution_py": "class Solution:\n    def maxProduct(self, nums: List[int]) -> int:\n        prod=1\n        maxprod=-100000000\n        for i in range(len(nums)): # traverse from L-R so that we get max \n            prod*=nums[i]\n            maxprod=max(maxprod,prod)\n            if prod==0:\n                prod=1\n\n        prod=1\n        for i in range(len(nums)-1,-1,-1): #if 0 or -ve present at starting then find from back\n            prod*=nums[i]\n            maxprod=max(maxprod,prod)\n            if prod==0:\n                prod=1\n\n        return maxprod",
        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxProduct = function(nums) {\n    const n = nums.length - 1;\n    let ans = nums[0];\n    let l = 1, r = 1;\n\n    for (let i = 0; i < nums.length; i++) {\n        l = (l ? l : 1) * nums[i];\n        r = (r ? r : 1) * nums[n - i];\n        ans = Math.max(ans, Math.max(l, r));\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int maxProduct(int[] nums) {\n        int ans = Integer.MIN_VALUE;\n        int m = 1;\n        for(int i=0; i< nums.length; i++){\n            m*=nums[i];\n            ans = Math.max(m, ans);\n            if(m == 0) m=1;\n        }\n        int n = 1;\n        for(int i=nums.length-1; i>=0; i--){\n            n*=nums[i];\n            ans = Math.max(n, ans);\n            if(n == 0) n=1;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxProduct(vector<int>& nums) {\n        int n = nums.size();\n        int negPro = 1;\n        int posPro = 1;\n        int CHECK_ZERO = 0;\n        int res = INT_MIN;\n        for(int i = 0; i < n; i++)\n        {\n            if(nums[i] == 0)\n            {\n                posPro = 1;\n                negPro = 1;\n                CHECK_ZERO = 1;\n            }\n            int numPos = posPro * nums[i];\n            int numNeg = negPro * nums[i];\n            posPro = max(numPos, max(numNeg, nums[i]));\n            negPro = min(numPos, min(numNeg, nums[i]));\n            res = max(posPro,res);\n        }\n        return (CHECK_ZERO ? max(0,res) : res);\n    }\n};"
    },
    {
        "title": "Subarray Sums Divisible by K",
        "algo_input": "Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.\n\nA subarray is a contiguous part of an array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,5,0,-2,-3,1], k = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\n\nExample 2:\n\nInput: nums = [5], k = 9\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-104 &lt;= nums[i] &lt;= 104\n\t2 &lt;= k &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def subarraysDivByK(self, nums, k):\n        n = len(nums)\n        prefix_mod = 0\n        result = 0\n\n        # There are k mod groups 0...k-1.\n        mod_groups = [0] * k\n        mod_groups[0] = 1\n\n        for num in nums:\n            # Take modulo twice to avoid negative remainders.\n            prefix_mod = (prefix_mod + num % k + k) % k\n            # Add the count of subarrays that have the same remainder as the current\n            # one to cancel out the remainders.\n            result += mod_groups[prefix_mod]\n            mod_groups[prefix_mod] += 1\n\n        return result",
        "solution_js": "var subarraysDivByK = function(nums, k) {\n    let count = 0;\n    let map = new Map();\n    map.set(0, 1)\n    let sum = 0;\n    for(let i=0; i<nums.length; i++){\n        sum += nums[i];\n        let rem = sum%k;\n        if(rem<0) rem += k;\n        if(map.has(rem)){\n            count += map.get(rem)\n            map.set(rem, map.get(rem)+1)\n        }else{\n            map.set(rem, 1)\n        }\n    }\n    return count\n};",
        "solution_java": "class Solution {\n    public int subarraysDivByK(int[] nums, int k) {\n        HashMap<Integer,Integer> map = new HashMap<>();\n        int count = 0;\n        int sum = 0;\n        for(int i=0;i<nums.length;i++){\n            sum +=nums[i];\n            int rem =sum%k;\n            if(rem <0){\n                rem = rem+k; // -4%3 == -1 and 2 both bec -4 = 3(-1) +(-1) = 3(-2) + 2\n            }\n            \n            if(rem==0){\n                count++;\n            }\n            if(map.containsKey(rem)){\n                count+=map.get(rem);\n            }\n            \n            map.put(rem,map.getOrDefault(rem,0)+1);\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int subarraysDivByK(vector<int>& nums, int k) {\n        // take an ans variable\n        int ans = 0;\n        // initialize a map of int, int and insert {0,1} as 0 occurs first time for sum\n        unordered_map<int, int> mapp;\n        mapp.insert({0,1});\n        // initialize presum = 0 and remainder rem = 0 which will be used in further calculations\n        int presum = 0;\n\n        int rem = 0;\n\n        // Logic\n        /*\n            1. We will traverse the entire given array/vector.\n            2. While traversing we will add the element in our presum, i.e presum += nums[i] .\n            3. Now we will do the % of presum and k and store it in rem that we have created.\n            4. We need to take care of negative value of rem. If it is < 0, then we will add k to the remainder to make it positive.\n            5. Now we will check if rem already exist in the map. If it exist then we will add it's frequency to ans variable\n             and then increment rem's value in map, i.e. mapp[rem]++, else we will add it in the map.\n            6. At last we will return ans.\n        */\n\n        for(int i=0; i<nums.size(); i++)\n        {\n            presum += nums[i];\n            rem = presum % k;\n            if(rem < 0)\n                rem += k;\n\n            if(mapp.find(rem) != mapp.end())\n            {\n                ans += mapp[rem];\n                mapp[rem]++;\n            }\n            else\n            {\n                mapp.insert({rem,1});\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Knight Probability in Chessboard",
        "algo_input": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).\n\nA chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.\n\nEach time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.\n\nThe knight continues moving until it has made exactly k moves or has moved off the chessboard.\n\nReturn the probability that the knight remains on the board after it has stopped moving.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, k = 2, row = 0, column = 0\nOutput: 0.06250\nExplanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.\n\n\nExample 2:\n\nInput: n = 1, k = 0, row = 0, column = 0\nOutput: 1.00000\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 25\n\t0 &lt;= k &lt;= 100\n\t0 &lt;= row, column &lt;= n\n\n",
        "solution_py": "class Solution:\n    def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n        \n        x_dir = [2, 1, -1, -2, -2, -1, 1, 2]\n        y_dir = [1, 2, 2, 1, -1, -2, -2, -1]\n        \n        cache = {}\n        \n        def kMoves(i, j, moves):\n            if i >= n or j >= n or i < 0 or j < 0:\n                return 0\n            \n            if moves == k:\n                return 1\n            \n            if (i, j, moves) in cache:\n                return cache[(i, j, moves)]\n            \n            totMoves = 0\n            for ind in range(8):\n                totMoves += kMoves(i+x_dir[ind], j+y_dir[ind], moves+1)*(1/8)\n            \n            cache[(i, j, moves)] = totMoves\n            return totMoves\n        \n        return kMoves(row, column, 0)",
        "solution_js": "var knightProbability = function(n, k, row, column) {\n    if (k === 0) return 1;\n    const dirs = [[-2, -1], [-1, -2], [1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1]];\n    const dp = Array(k + 1)\n        .fill('')\n        .map(_ => Array(n).fill('').map(_ => Array(n).fill(0)));\n\n    const isOut = (pos) => pos < 0 || pos > n - 1;\n    const move = (x = row, y = column, step = k) => {\n        if (step === 0) return 1;\n        const moves = dp[step][x][y];\n        if (moves !== 0) return moves;\n\n        for (const [mvoeX, moveY] of dirs) {\n            const nextX = x + mvoeX;\n            const nextY = y + moveY;\n            if (isOut(nextX) || isOut(nextY)) continue;\n\n            dp[step][x][y] += move(nextX, nextY, step - 1);\n        }\n        return dp[step][x][y];\n    };\n\n    move();\n    return dp[k][row][column] / 8 ** k;\n};",
        "solution_java": "class Solution {\n    public double knightProbability(int n, int k, int row, int column) {\n        double [][]curr=new double[n][n];\n        double [][]next=new double[n][n];\n        \n        curr[row][column]=1;\n        \n        int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};\n        for(int p=1;p<=k;p++){\n            for(int i=0;i<n;i++){\n                for(int j=0;j<n;j++){\n                    if(curr[i][j]!=0){\n                        \n                        for(int d=0;d<8;d++){\n                            int ni=i+dir[d][0];\n                            int nj=j+dir[d][1];\n                            \n                            if(ni<0 || nj<0 || ni>=n || nj>=n){\n                                continue;\n                            }\n                            \n                            next[ni][nj]+=curr[i][j]/8.0;\n                        }\n                    }\n                }\n            }\n            \n            curr=next;\n            next=new double[n][n];\n        }\n        \n        double sum=0.0;\n        \n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                sum+=curr[i][j];\n            }\n        }\n        \n        return sum;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    // declare a dp\n    \n    double dp[30][30][105];\n    \n    // x and y co-ordinates of 8 directions\n   \n    vector<int> dx = {-2, -2, -1, 1, 2, 2, 1, -1};\n    \n    vector<int> dy = {-1, 1, 2, 2, 1, -1, -2, -2};\n    \n    double dfs(int i, int j, int n, int moves)\n    {\n        // base case if we have reached out of grid\n        \n        if(i < 0 || i >= n || j < 0 || j >= n)\n            return 0;\n        \n        // if no moves are remaining\n        \n        if(moves <= 0)\n            return 1;\n        \n        // if already calculated\n        \n        if(dp[i][j][moves] != 0)\n            return dp[i][j][moves];\n        \n        // find total possible ways of staying on chess board\n        \n        double ans = 0;\n        \n        for(int k = 0; k < 8; k++)\n        {\n            int new_row = i + dx[k];\n            \n            int new_col = j + dy[k];\n            \n            ans += dfs(new_row, new_col, n, moves - 1);\n        }\n        \n        // for each cell there are 8 possible moves, so probablity will be no. of successfull moves / 8\n        \n        // store the result and return\n        \n        return dp[i][j][moves] = ans / 8.0;\n    }\n    \n    double knightProbability(int n, int k, int row, int column) {\n        \n        // initialize the dp with 0\n        \n        memset(dp, 0, sizeof(dp));\n       \n        return dfs(row, column, n, k);\n    }\n};"
    },
    {
        "title": "Rearrange Spaces Between Words",
        "algo_input": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.\n\nRearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.\n\nReturn the string after rearranging the spaces.\n\n&nbsp;\nExample 1:\n\nInput: text = \"  this   is  a sentence \"\nOutput: \"this   is   a   sentence\"\nExplanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\n\n\nExample 2:\n\nInput: text = \" practice   makes   perfect\"\nOutput: \"practice   makes   perfect \"\nExplanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 100\n\ttext consists of lowercase English letters and ' '.\n\ttext contains at least one word.\n\n",
        "solution_py": "class Solution(object):\n    def reorderSpaces(self, text):\n        word_list = text.split()\n        words, spaces = len(word_list), text.count(\" \")\n        \n        if words > 1:\n            q, r = spaces//(words-1), spaces%(words-1)\n            return (\" \" * q).join(word_list) + \" \" * r\n        else:\n            return \"\".join(word_list) + \" \" * spaces",
        "solution_js": "var reorderSpaces = function(text) {\n    let arr = text.split(\" \");\n    let totalSpace = arr.length-1;\n    arr = arr.filter(w => w !== '');\n    let spaceBetween = arr.length > 1 ?\n                    Math.floor(totalSpace / (arr.length-1)) : 0;\n    let spaceLeftOver = arr.length > 1 ?\n                    totalSpace % (arr.length-1) : totalSpace;\n    return (arr.join(\" \".repeat(spaceBetween)) + \" \".repeat(spaceLeftOver));\n    // Time Complexity: O(n)\n    // Space Complexity: O(n)\n};",
        "solution_java": "class Solution {\n    public String reorderSpaces(String text) {\n        int spaces = 0;\n\n        //count the spacex\n        for(char c: text.toCharArray()){\n            if(c==' ')\n                spaces++;\n        }\n\n        //form word array\n        String[] words = text.trim().split(\"\\\\s+\");\n        int nWords = words.length;\n\n        StringBuilder sb = new StringBuilder();\n        int spacesToApply=0,extraSpaces=0;\n\n        //if there is only 1 word, then all spaces will be at the end\n        if(nWords == 1){\n            extraSpaces=spaces;\n        }\n\n        //if there are multiple words, find the spaces to apply between words and also any extra space\n        else{\n            spacesToApply = spaces / (nWords-1);\n            extraSpaces = spaces % (nWords-1);\n        }\n\n        //append every word and then apply spaces\n        for(int i=0;i<words.length-1;i++){\n            sb.append(words[i]);\n\n            for(int j=0;j<spacesToApply;j++)\n                sb.append(\" \");\n        }\n\n        //now append last word separately, bcz we dont want to apply spaces after last word\n        sb.append(words[nWords-1]);\n\n        //if there are any extra spaces that cannot be distributed among words, add them here\n        for(int j=0;j<extraSpaces;j++)\n                sb.append(\" \");\n\n        return sb.toString();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string reorderSpaces(string text) {\n       int ct=0;\n\n       // Collection of words\n        vector<string> v;\n        for (int i=0; i<text.size(); i++){\n\n            // Calculate the numbert of spaces\n            while(i<text.size() && text[i] == ' '){\n                ct++;\n                i++;\n            }\n\n            // Extract the words and collect them\n            string tp=\"\";\n            while(i<text.size() && text[i] != ' '){\n                tp+=text[i];\n                i++;\n            }\n            i--;\n\n            // Adding word to the collection\n            if(tp.size()) v.push_back(tp);\n        }\n\n        text = \"\";\n\n        // Combining the words with equal number of white spaces\n        for(int i=0; i<v.size()-1; i++){\n            text += v[i];\n            int j=ct/(v.size()-1);\n            while(j--) text += ' ';\n        }\n\n        text += v[v.size()-1];\n\n        // Adding remaining extra spaces at the end\n        int j=(v.size() > 1)?ct % (v.size()-1):ct;\n        while(j--) text += ' ';\n\n        return text;\n    }\n};"
    },
    {
        "title": "Valid Square",
        "algo_input": "Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.\n\nThe coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.\n\nA valid square has four equal sides with positive length and four equal angles (90-degree angles).\n\n&nbsp;\nExample 1:\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput: true\n\n\nExample 2:\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\nOutput: false\n\n\nExample 3:\n\nInput: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\tp1.length == p2.length == p3.length == p4.length == 2\n\t-104 &lt;= xi, yi &lt;= 104\n\n",
        "solution_py": "class Solution:\n    def validSquare(self, p1, p2, p3, p4):\n\n        def cal(A, B):\n            return abs(A[0] - B[0]) + abs(A[1] - B[1])\n\n        d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)]\n        d.sort()\n\n        return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5]",
        "solution_js": "var validSquare = function(p1, p2, p3, p4) {\n    const distance = (a, b) => {\n        const [aX, aY] = a;\n        const [bX, bY] = b;\n        return (aX - bX) ** 2 + (aY - bY) ** 2;\n    };\n\n    const set = new Set([\n        distance(p1, p2),\n        distance(p1, p3),\n        distance(p1, p4),\n        distance(p2, p3),\n        distance(p2, p4),\n        distance(p3, p4),\n    ]);\n\n    return !set.has(0) && set.size === 2;\n};",
        "solution_java": "class Solution {\n    // This method returns true if the given 4 points form a square, false otherwise\n    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n        // We use a set to store the distances between the points\n        Set<Integer> set = new HashSet();\n        // Calculate the distances between all pairs of points and add them to the set\n        set.add(distanceSquare(p1,p2));\n        set.add(distanceSquare(p1,p3));\n        set.add(distanceSquare(p1,p4));\n        set.add(distanceSquare(p2,p3));\n        set.add(distanceSquare(p2,p4));\n        set.add(distanceSquare(p3,p4));\n        // A square must have 4 equal sides, so the set must contain 2 different values (the lengths of the sides and the diagonals)\n        // The set should not contain 0, as that would mean that two points have the same coordinates\n        return !set.contains(0) && set.size() == 2;\n    }\n    // This method calculates the distance between two points and returns its square\n    private int distanceSquare(int[] a, int[] b){\n        // We use the Pythagorean theorem to calculate the distance between the points\n        return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {\n        vector<vector<int>> p{p1, p2, p3, p4};\n        unsigned short ans{0};\n        double scal;\n        vector<double> bar(2);\n        /* compute the barycenter */ \n        bar[0] = (p1[0] + p2[0] + p3[0] + p4[0]) / 4.;\n        bar[1] = (p1[1] + p2[1] + p3[1] + p4[1]) / 4.;\n        const double length = pow(p1[0]-bar[0],2) + pow(p1[1] - bar[1],2);\n        for (size_t i=0; i<4; i++) {if ((pow(p[i][0]-bar[0], 2) + pow(p[i][1] - bar[1], 2)) != length) return false; \n            for (size_t j=i+1; j<4;j++){\n                scal = (bar[0] - p[i][0])*(bar[0] - p[j][0]) + (bar[1] - p[i][1])*(bar[1]- p[j][1]);\n                ans += (scal==0.)?1:0;}}\n        return  ans==4;\n    }\n};"
    },
    {
        "title": "Minimum Deletions to Make Array Beautiful",
        "algo_input": "You are given a 0-indexed integer array nums. The array nums is beautiful if:\n\n\n\tnums.length is even.\n\tnums[i] != nums[i + 1] for all i % 2 == 0.\n\n\nNote that an empty array is considered beautiful.\n\nYou can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.\n\nReturn the minimum number of elements to delete from nums to make it beautiful.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,2,3,5]\nOutput: 1\nExplanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.\n\n\nExample 2:\n\nInput: nums = [1,1,2,2,3,3]\nOutput: 2\nExplanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def minDeletion(self, nums: List[int]) -> int:\n        # Greedy !\n        # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n        # at the begining, we consider the num on the even index\n        # when we delete a num, we need consider the num on the odd index\n        # then repeat this process\n        # at the end we check the requirement 1: nums.length is even or not\n        \n        n = len(nums)\n        count = 0\n        # flag is true then check the even index\n        # flag is false then check the odd index\n        flag = True\n        \n        for i in range(n):\n            # check the even index\n            if flag:\n                if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]:\n                    count += 1\n                    flag = False\n            # check the odd index\n            elif not flag:\n                if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]:\n                    count += 1\n                    flag = True\n        \n        curLength = n - count\n        \n        return count if curLength % 2 == 0 else count + 1",
        "solution_js": "var minDeletion = function(nums) {\n    const n = nums.length;\n    const res = [];\n\n    for (let i = 0; i < n; ++i) {\n        const num = nums[i];\n\n        if (res.length % 2 === 0 || res.at(-1) != num) {\n            res.push(num);\n        }\n    }\n\n    if (res.length % 2 === 1) res.pop();\n\n    return n - res.length;\n};",
        "solution_java": "class Solution {\n    public int minDeletion(int[] nums) {\n\n        int deletion = 0, n = nums.length;\n\n        for (int i=0; i<n-1; ) {\n            int newIndex = i-deletion;\n            if ((newIndex % 2 == 0) && nums[i] == nums[i+1]) deletion++;\n            else i++;\n        }\n        return ((n-deletion) % 2 == 0) ? deletion : deletion+1;\n    }\n}",
        "solution_c": "INTUITION\n1. since we have to find the minimum deletions, we dont have to \n\tactually delete the elements , we just have to count those elements.\n2. Now if we delete the element and shift all the elements towards left , it will\n\tcause time limit exceeded.\n3. To handle above case we can  observe one thing that, if we delete some element\n\tat a certain position then the indices of all the elements towards the right \n\twill get inverted means the odd index will become even and the even will become odd.\n4. In the end checking if the vector size if even or odd, if it is even simply return or else if it \n\tis odd then decrement result by 1 since we have to remove one element to have the vector size even.\nclass Solution {\npublic:\n    int minDeletion(vector<int>& nums) {\n        int res=0,n=nums.size(),i;\n        int flag=1;\n            for(i=0;i<nums.size()-1;i++){\n                    if(i%2==0 and nums[i]==nums[i+1]  and flag){\n                        res++;\n                        flag=0;\n                    }\n                    else if(i%2==1 and nums[i]==nums[i+1] and flag==0){\n                        res++;\n                        flag=1;\n                    }\n                }\n        int x=n-res;\n        if(x%2==0){\n            return res;\n        }\n        return res+1;\n    }\n};"
    },
    {
        "title": "Continuous Subarray Sum",
        "algo_input": "Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.\n\nAn integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.\n\n&nbsp;\nExample 1:\n\nInput: nums = [23,2,4,6,7], k = 6\nOutput: true\nExplanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\n\n\nExample 2:\n\nInput: nums = [23,2,6,4,7], k = 6\nOutput: true\nExplanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.\n\n\nExample 3:\n\nInput: nums = [23,2,6,4,7], k = 13\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 109\n\t0 &lt;= sum(nums[i]) &lt;= 231 - 1\n\t1 &lt;= k &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n        psum = {0:-1}\n        currentSum = 0\n        for i in range(len(nums)):\n            currentSum += nums[i]\n            remainder = currentSum % k\n            if remainder not in psum:\n                psum[remainder] = i\n            else:\n                if i - psum[remainder] > 1:\n                    return True\n        return False",
        "solution_js": "var checkSubarraySum = function(nums, k) {\n\tconst hash = new Map([[0, -1]]);\n\tlet sum = 0;\n\n\tfor (let index = 0; index < nums.length; index++) {\n\t\tsum += nums[index];\n\t\tconst r = sum % k;\n\n\t\tif (hash.has(r)) {\n\t\t\tif (index - hash.get(r) > 1) return true;\n\t\t}\n\t\telse hash.set(r, index);\n\t}\n\treturn false;\n};",
        "solution_java": "class Solution {\n    public boolean checkSubarraySum(int[] nums, int k) {\n        boolean t[]=new boolean[nums.length+1];\n        Arrays.fill(t,false);\n       return help(nums.length,nums,k,0,0,t);\n    }\n    public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){\n        if(size>=2&&sum%k==0){\n            return true;\n        }\n        if(i==0){\n            return false;\n        }\n        if(t[i-1]!=false){\n            return t[i-1];\n        }\n        if(size>0){\n         return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t);\n        }\n        return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t)||help(i-1,nums,k,sum,size,t);\n    }\n}\n---------------------------------------------------------------------------------------------\nclass Solution {\n    public boolean checkSubarraySum(int[] nums, int k) {\n      int sum=0;\n      HashMap<Integer,Integer>h=new HashMap<>();\n      h.put(0,-1);\n      for(int i=0;i<nums.length;i++){\n          sum+=nums[i];\n          sum=k==0?sum:sum%k;\n          if(h.containsKey(sum)&& i-h.get(sum)>=2){\n              return true;\n          }\n          h.put(sum,h.getOrDefault(sum,i));\n      }  \n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool checkSubarraySum(vector<int>& nums, int k) {\n        unordered_set<int> s;\n        int sum = 0;\n        int pre = 0;\n        for(int i = 0; i < nums.size(); i++)\n        {\n            sum += nums[i];\n            int remainder = sum%k;\n            if (s.find(remainder) != s.end())\n            {\n                return true;\n            }\n            s.insert(pre);\n            pre = remainder;\n        }\n        return false;\n    }"
    },
    {
        "title": "Reconstruct Itinerary",
        "algo_input": "You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.\n\nAll of the tickets belong to a man who departs from \"JFK\", thus, the itinerary must begin with \"JFK\". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.\n\n\n\tFor example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"].\n\n\nYou may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.\n\n&nbsp;\nExample 1:\n\nInput: tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nOutput: [\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]\n\n\nExample 2:\n\nInput: tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nOutput: [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\nExplanation: Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= tickets.length &lt;= 300\n\ttickets[i].length == 2\n\tfromi.length == 3\n\ttoi.length == 3\n\tfromi and toi consist of uppercase English letters.\n\tfromi != toi\n\n",
        "solution_py": "class Solution:        \n    def findTicketsAdjList(self, tickets):\n        ticket = {}\n        for src,dest in tickets:\n            if src in ticket:\n                ticket[src].append(dest)\n            else:\n                ticket[src] = [dest]\n\n        for src,dest in ticket.items():\n            if len(dest)>1:\n                ticket[src] = sorted(ticket[src], reverse=True)\n                \n        return ticket\n    \n    def reconstructItinerary(self, source, tickets, itinerary):\n        if source in tickets:\n            while tickets[source]:        \n                destination = tickets[source].pop()\n                self.reconstructItinerary(destination, tickets, itinerary)\n        itinerary.append(source)\n        return itinerary\n                        \n    def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n        if len(tickets)==1:\n            if \"JFK\" not in tickets[0]:\n                return []\n            \n        ticketsAdj = self.findTicketsAdjList(tickets)\n        if \"JFK\" not in ticketsAdj:\n            return []\n        itinerary = []\n        itinerary = self.reconstructItinerary(\"JFK\", ticketsAdj, itinerary)\n        \n        return itinerary[::-1]\n        ",
        "solution_js": "function dfs(edges,s=`JFK`,ans=[`JFK`]){  //run dfs, starting node being `JFK`\n    if(!edges[s] || edges[s].length==0){  //if currenctly reached node has its adjacent list empty\n        let isAllTravelled=1;\n        Object.values(edges).forEach(ele=> {if(ele.length>0) isAllTravelled=0}) // check if every edge has been travelled i.e all adjacentLists should be empty\n         if(!isAllTravelled) return false;   //returns false when there are more edges to travel , but from current node we cannot move anywhere else \n        else return  ans; // return true if from current node we cannot move anywhere else and all the edges have been travelled as well\n    }\n    \n    let myAL= edges[s].sort();  // sort the Adjacency List  of current node lexicographically\n    for(let i=0;i<myAL.length;i++){ // start by taking the lexicographically smallest node and run dfs\n        ans.push(myAL[i]);  // add current node into answer array\n        edges[s]= [...edges[s].slice(0,edges[s].indexOf(myAL[i])),...edges[s].slice(edges[s].indexOf(myAL[i])+1)]; // remove the currently edges travelled from adjacency List \n        let xx= dfs(edges,myAL[i],ans); //here runs the dfs\n        if(!xx){ // if dfs result of current node could not travel all edges from current node\n            ans.pop(); // pop out current accounted node from answer\n            edges[s].push(myAL[i]);  //put back the edge into adjacency list assmuing we should not visit this edge at this point as it doesnt leads to answer from here currenlt\n        }\n        else return xx ; // if dfs result of current node could travel all edges from current node return the answer array\n    } \n}\nvar findItinerary = function(tickets) {\n    let edges={}; //our adjacency list\n    tickets.forEach(ticket=>{\n       if(!edges[ticket[0]]){\n            edges[ticket[0]]=[];\n        }\n        edges[ticket[0]].push(ticket[1]);\n    })\n   \n    let ans= dfs(edges); // run dfs \n    return ans;\n};",
        "solution_java": "class Solution {\n    LinkedList<String> res = new LinkedList<>();\n\n    public List<String> findItinerary(List<List<String>> tickets) {\n        HashMap<String,PriorityQueue<String>> map= new HashMap<>();\n        for(int i=0;i<tickets.size();i++){\n            String a=tickets.get(i).get(0);\n            String b=tickets.get(i).get(1);\n            if(!map.containsKey(a)){\n                PriorityQueue<String> temp = new PriorityQueue();\n                map.put(a,temp);\n            }\n            map.get(a).add(b);\n        }\n\n        dfs(\"JFK\",map);\n        return res;\n\n    }\n    private void dfs(String departure,HashMap<String,PriorityQueue<String>> map){\n        PriorityQueue<String> arrivals= map.get(departure);\n        while(arrivals!=null &&!arrivals.isEmpty()){\n            dfs(arrivals.poll(),map);\n        }\n        res.addFirst(departure);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> findItinerary(vector<vector<string>>& tickets) {\n        unordered_map<string, multiset<string>> myMap;\n        stack<string> myStack;\n        vector<string> ans;\n        for (int i=0; i<tickets.size(); ++i) {\n            myMap[tickets[i][0]].insert(tickets[i][1]);\n        }\n        myStack.push({\"JFK\"});\n        while (!myStack.empty()) {\n            string top = myStack.top();\n            if (!myMap[top].empty()) {\n                myStack.push(*myMap[top].begin());\n                myMap[top].erase(myMap[top].begin());\n            } else {\n                ans.insert(ans.begin(), top);\n                myStack.pop();\n            }\n        }\n        return ans;\n    }\n};\n// Time : O(E)\n// Space : O(V + E)"
    },
    {
        "title": "Data Stream as Disjoint Intervals",
        "algo_input": "Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.\n\nImplement the SummaryRanges class:\n\n\n\tSummaryRanges() Initializes the object with an empty stream.\n\tvoid addNum(int val) Adds the integer val to the stream.\n\tint[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]\nOutput\n[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n\nExplanation\nSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1);      // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3);      // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7);      // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2);      // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= val &lt;= 104\n\tAt most 3 * 104 calls will be made to addNum and getIntervals.\n\n\n&nbsp;\nFollow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?\n",
        "solution_py": "class SummaryRanges:\n    def __init__(self):\n        self.intervals = []\n    def addNum(self, val: int) -> None:\n        left, right = 0, len(self.intervals) - 1\n        while left <= right:\n            mid = (left + right) // 2\n            e = self.intervals[mid]\n            if e[0] <= val <= e[1]: return\n            elif val < e[0]:right = mid - 1\n            else:left = mid + 1\n        pos = left\n        self.intervals.insert(pos, [val, val])\n        if pos + 1 < len(self.intervals) and val + 1 == self.intervals[pos+1][0]:\n            self.intervals[pos][1] = self.intervals[pos+1][1]\n            del self.intervals[pos+1]\n        if pos - 1 >= 0 and val - 1 == self.intervals[pos-1][1]:\n            self.intervals[pos-1][1] = self.intervals[pos][1]\n            del self.intervals[pos]\n\n    def getIntervals(self) -> List[List[int]]:\n        return self.intervals",
        "solution_js": "var SummaryRanges = function() {\n    this.tree = null // { val, left?, right? }\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nSummaryRanges.prototype.addNum = function(val) {\n    if (!this.tree) {\n        this.tree = { val }\n    } else {\n        let node = this.tree\n        let parent, side\n        while (node) {\n            if (node.val === val) { return }\n            parent = node\n            side = node.val > val ? 'left' : 'right'\n            node = node[side]\n        }\n        parent[side] = { val }\n    }\n};\n\n/**\n * @return {number[][]}\n */\nSummaryRanges.prototype.getIntervals = function() {\n    // travel from left to right\n    // generate intervals\n\t// > (x === last[1] + 1) ? update last[1] : create a new one\n    const travel = (node, check) => {\n        if (!node) { return }\n        travel(node.left, check)\n        check(node.val)\n        travel(node.right, check)\n    }\n    const result = []\n    const check = val => {\n        if (!result.length || val > result[result.length - 1][1] + 1) {\n\t\t\tresult.push([val, val])\n\t\t} else {\n\t\t\tresult[result.length - 1][1] = val\n        }\n    }\n    travel(this.tree, check)\n    return result\n};\n\n/** \n * Your SummaryRanges object will be instantiated and called as such:\n * var obj = new SummaryRanges()\n * obj.addNum(val)\n * var param_2 = obj.getIntervals()\n */",
        "solution_java": "class SummaryRanges {\n\n    Map<Integer, int[]> st;\n    Map<Integer, int[]> end;\n    Set<Integer> pending;\n    int[][] prev = new int[0][];\n    Set<Integer> seen = new HashSet<>();\n    int INVALID = -1;\n    public SummaryRanges() {\n        st = new HashMap<>();\n        end= new HashMap<>();\n        pending = new HashSet<>();\n    }\n\n    public void addNum(int val) { // [TC: O(1)]\n        if (!seen.contains(val)){ // only add if not seen.\n            pending.add(val); // pending processing list\n        }\n    }\n\n    public int[][] getIntervals() { // [TC: O(pending list length (= k)) best case (all merges), O(n)+O(klogk) worst case (all inserts)]\n        Set<int[]> addSet = new HashSet<>();\n        for (int n : pending){\n            if (st.containsKey(n+1)&&end.containsKey(n-1)){ // merge intervals on both ends, a new interval form -> add to addSet\n                int[] s = st.get(n+1);\n                int[] e = end.get(n-1);\n                int[] m = new int[]{e[0], s[1]};\n                st.remove(n+1);\n                end.remove(n-1);\n                st.put(m[0], m);\n                end.put(m[1], m);\n                s[0]=e[0]=INVALID;\n                addSet.remove(s); // may be in addSet, remove them\n                addSet.remove(e);\n                addSet.add(m);\n            }else if (st.containsKey(n+1)){ // merge with the next interval, no other action required.\n                st.get(n+1)[0]--;\n                st.put(n, st.get(n+1));\n                st.remove(n+1);\n            }else if (end.containsKey(n-1)){ // merge with the previous interval, no other action required.\n                end.get(n-1)[1]++;\n                end.put(n, end.get(n-1));\n                end.remove(n-1);\n            }else{ // new interval -> add to AddSet\n                int[] m = new int[]{n, n};\n                addSet.add(m);\n                st.put(n, m);\n                end.put(n, m);\n            }\n        }\n\n        seen.addAll(pending);\n        pending.clear(); // remember to clear the pending list.\n\n        if (!addSet.isEmpty()){ // IF there is no new intervals to insert, we SKIP this.\n            List<int[]> addList = new ArrayList<>(addSet);\n            addList.sort(Comparator.comparingInt(o -> o[0]));\n            int i = 0, j = 0; // two pointers because both prev & addList are sorted.\n            List<int[]> ans = new ArrayList<>();\n            while(i < prev.length || j < addList.size()){\n                if (i < prev.length && prev[i][0]==INVALID){\n                    i++;\n                }else if (j == addList.size() || i < prev.length && prev[i][0]<addList.get(j)[0]){\n                    ans.add(prev[i++]);\n                }else if (i == prev.length || prev[i][0]>addList.get(j)[0]){\n                    ans.add(addList.get(j++));\n                }\n            }\n            prev = ans.toArray(new int[0][]);\n        }\n\n        return prev;\n    }\n}",
        "solution_c": "class SummaryRanges {\npublic:\n\n    struct DSU {\n        map<int, int>parent;\n        map<int, int>sz;\n\n        int find_parent(int a) {\n            if(!parent.count(a)) {\n                parent[a] = a;\n                sz[a] = 1;\n            }\n\n            if(parent[a] == a) return a;\n            return parent[a] = find_parent(parent[a]);\n        }\n\n        void union_sets(int a, int b) {\n            if(!parent.count(a)) {\n                parent[a] = a;\n                sz[a] = 1;\n            }\n\n            if(!parent.count(b)) {\n                parent[b] = b;\n                sz[b] = 1;\n            }\n\n\n            a = find_parent(a);\n            b = find_parent(b);\n\n            if(a == b) return;\n\n            parent[b] = a;\n            sz[a] += sz[b];\n\n\n        }\n\n        void add(int a) {\n\n\n            if(!parent.count(a)) {\n                parent[a] = a;\n                sz[a] = 1;\n            } else return;\n\n\n\n            if(parent.count(a + 1)) {\n                union_sets(a, a + 1);\n            }\n            if(parent.count(a - 1)) {\n                union_sets(a - 1, a);\n            }\n        }\n\n        vector<vector<int>>getIntervals() {\n            vector<vector<int>>intervals;\n            for(auto [a, b]: parent) {\n                if(a == b) {\n                    intervals.push_back({a, a + sz[a] - 1});\n                }\n            }\n\n            return intervals;\n        }\n\n    };\n    \n    DSU dsu;\n\n    SummaryRanges() {\n        this->dsu = DSU();\n    }\n    \n    void addNum(int val) {\n        dsu.add(val);\n    }\n    \n    vector<vector<int>> getIntervals() {\n        return dsu.getIntervals();\n    }\n};"
    },
    {
        "title": "Execution of All Suffix Instructions Staying in a Grid",
        "algo_input": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).\n\nYou are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).\n\nThe robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:\n\n\n\tThe next instruction will move the robot off the grid.\n\tThere are no more instructions left to execute.\n\n\nReturn an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, startPos = [0,1], s = \"RRDDLU\"\nOutput: [1,5,4,3,1,0]\nExplanation: Starting from startPos and beginning execution from the ith instruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st:  \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd:   \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd:    \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th:     \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th:      \"U\". If moving up, it would move off the grid.\n\n\nExample 2:\n\nInput: n = 2, startPos = [1,1], s = \"LURD\"\nOutput: [4,1,0,0]\nExplanation:\n- 0th: \"LURD\".\n- 1st:  \"URD\".\n- 2nd:   \"RD\".\n- 3rd:    \"D\".\n\n\nExample 3:\n\nInput: n = 1, startPos = [0,0], s = \"LRUD\"\nOutput: [0,0,0,0]\nExplanation: No matter which instruction the robot begins execution from, it would move off the grid.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == s.length\n\t1 &lt;= n, m &lt;= 500\n\tstartPos.length == 2\n\t0 &lt;= startrow, startcol &lt; n\n\ts consists of 'L', 'R', 'U', and 'D'.\n\n",
        "solution_py": "class Solution:\n    def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:\n        result = []\n        for idx in range(len(s)):\n            count, row, col = 0, startPos[0],startPos[1]\n            while  idx < len(s):\n                if s[idx] == 'D':\n                    row += 1\n                    if row >= n:\n                        break\n                    count += 1\n                elif s[idx] == 'U':\n                    row -= 1\n                    if row < 0:\n                        break\n                    count += 1\n                elif s[idx] == 'R':\n                    col += 1\n                    if col >= n:\n                        break\n                    count += 1\n                else:\n                    col -= 1\n                    if col < 0:\n                        break\n                    count += 1\n                idx += 1\n            result.append(count)\n        return result",
        "solution_js": "// Time: O(n^2)\nvar executeInstructions = function(n, startPos, s) {\n    let answers = [];\n    for (i = 0; i < s.length; i++) {\n        let movement = 0;\n        let [row, col] = startPos;\n        for (j = i; j < s.length; j++) {\n            if (s[j] == \"R\") col++;\n            else if (s[j] == \"L\") col--;\n            else if (s[j] == \"D\") row++;\n            else row--;\n            if(row>n-1 || col > n-1 || row < 0 || col < 0) {\n                break;\n            }\n            movement++;\n        }\n        answers[i] = movement;\n    }\n    return answers;\n};",
        "solution_java": "class Solution {\n    public int[] executeInstructions(int n, int[] startPos, String s) {\n        //Make array of length equal to string length\n        int ans[]=new int[s.length()];\n\n        //Now use two for loops\n        for(int i=0;i<s.length();i++){\n            //countmoves will keep on counting the valid moves from i to s.length\n            int countMoves=0;\n            int yIndex=startPos[0];\n            int xIndex=startPos[1];\n            for(int j=i;j<s.length();j++){\n\n                if(s.charAt(j)=='R'){\n                    xIndex++;\n                }\n                if(s.charAt(j)=='L'){\n                       xIndex--;\n                }\n               if(s.charAt(j)=='U'){\n                        yIndex--;\n                }\n                if(s.charAt(j)=='D'){\n                    yIndex++;\n                }\n                if(xIndex<0 || xIndex>=n || yIndex<0 || yIndex>=n){\n                    break;\n                }\n                else{\n                    countMoves++;\n                }\n            }\n\n            ans[i]=countMoves;\n\n        }\n        return ans;\n\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tvector<int> executeInstructions(int n, vector<int>& start, string s) {\n\t\tint m=s.size();\n\t\tvector<int> ans(m);\n\t\tfor(int l=0;l<m;l++){\n\t\t\tint count=0;\n\t\t\tint i=start[0],j=start[1];\n\t\t\tfor(int k=l;k<m;k++){\n\t\t\t\tif(s[k]=='L'){\n\t\t\t\t\tif(j-1>=0){\n\t\t\t\t\t\tj--;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t\telse if(s[k]=='R'){\n\t\t\t\t\tif(j+1<n){\n\t\t\t\t\t\tj++;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t\telse if(s[k]=='U'){\n\t\t\t\t\tif(i-1>=0){\n\t\t\t\t\t\ti--;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tif(i+1<n){\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans[l]=count;\n\t\t}\n\t\treturn ans;\n\t}\n};"
    },
    {
        "title": "Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree",
        "algo_input": "Given a weighted undirected connected graph with n&nbsp;vertices numbered from 0 to n - 1,&nbsp;and an array edges&nbsp;where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes&nbsp;ai&nbsp;and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles&nbsp;and with the minimum possible total edge weight.\n\nFind all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a&nbsp;critical edge. On&nbsp;the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\n\nNote that you can return the indices of the edges in any order.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput: [[0,1],[2,3,4,5]]\nExplanation: The figure above describes the graph.\nThe following figure shows all the possible MSTs:\n\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n\n\nExample 2:\n\n\n\nInput: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput: [[],[0,1,2,3]]\nExplanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 100\n\t1 &lt;= edges.length &lt;= min(200, n * (n - 1) / 2)\n\tedges[i].length == 3\n\t0 &lt;= ai &lt; bi &lt; n\n\t1 &lt;= weighti&nbsp;&lt;= 1000\n\tAll pairs (ai, bi) are distinct.\n\n",
        "solution_py": "class Solution:\n    def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n        def find(v, parent):\n            if parent[v] != v:\n                parent[v] = find(parent[v], parent)\n            return parent[v]\n        def union(u,v, parent):\n            parent[find(u,parent)] = find(v,parent)\n        edges = [(u,v,w,i) for i, (u,v,w) in enumerate(edges)]\n        edges.sort(key = lambda e:e[2])\n        def find_mst_without_this_edge(idx):\n            parent = list(range(n))\n            res = 0\n            for i, (u, v, w, _) in enumerate(edges):\n                if i == idx: continue\n                if find(u, parent) != find(v, parent):\n                    res += w\n                    union(u, v, parent)\n            root = find(0, parent)\n            return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n        def find_mst_with_this_edge(idx):\n            parent = list(range(n))\n            u0, v0, w0, _ = edges[idx]\n            res = w0\n            union(u0,v0,parent)\n            for i, (u, v, w, _) in enumerate(edges):\n                if i == idx:\n                    continue\n                if find(u, parent) != find(v, parent):\n                    res += w\n                    union(u, v, parent)\n            root = find(0, parent)\n            return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n        base_mst_wgt = find_mst_without_this_edge(-1)\n        cri, pcri = set(), set()\n        for i in range(len(edges)):\n            wgt_excl = find_mst_without_this_edge(i)\n            if wgt_excl > base_mst_wgt:\n                cri.add(edges[i][3])\n            else:\n                wgt_incl = find_mst_with_this_edge(i)\n                if wgt_incl == base_mst_wgt:\n                    pcri.add(edges[i][3])\n        return [cri, pcri]",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nvar findCriticalAndPseudoCriticalEdges = function(n, edges) {\n\t// find and union utils\n    const find = (x, parent) => {\n        if (parent[x] === -1) { return x }\n        const y = find(parent[x], parent)\n        parent[x] = y\n        return y\n    }\n    const union = (a, b, parent) => {\n        a = find(a, parent)\n        b = find(b, parent)\n        if (a === b) { return false }\n        parent[a] = b\n        return true\n    }\n\n\t// sort and group edges by cost\n    const map = {}\n    edges.forEach(([a, b, cost], i) => {\n        map[cost] = map[cost] || []\n        map[cost].push([a, b, i])\n    })\n    const costs = Object.keys(map).sort((a, b) => a - b)\n\n\t// check by group\n    const check = (edges, parent) => {\n        let nextParent\n        let count\n\n\t\t// travel with a skipped point\n\t\t// if skip === -1, skip nothing and update count and nextParent.\n        const travel = skip => {\n            const p = [...parent]\n            const result = []\n            edges.forEach(([a, b, i]) => {\n                if (i === skip) { return }\n                if (union(a, b, p)) { result.push(i) }\n            })\n            if (skip === -1) {\n                count = result.length\n                nextParent = p\n            }\n            return result\n        }\n\n\t\t// get default count and nextParent.\n        travel(-1)\n\n\t\t// special case: there is only one edge in this group\n        if (edges.length === 1) {\n            if (count === 0) { return [[], [], 0, parent] }\n            return [[edges[0][2]], [], 1, nextParent]\n        }\n\n\t\t// aList -> critical, bList -> pseudo\n        const aList = {}\n        const bList = {}\n        edges.forEach(([a, b, i]) => {\n            if (find(a, parent) === find(b, parent)) { return }\n            const result = travel(i)\n            result.length < count ? aList[i] = true : bList[i] = true\n        })\n        return [Object.keys(aList), Object.keys(bList), count, nextParent]\n    }\n\n\t// init traversal state\n    const critical = []\n    const pseudo = []\n    let count = 0\n    let parent = new Array(n).fill(-1)\n\n\t// travel by cost group until all points visited\n    for (let i = 0; i < costs.length; i++) {\n        const [aList, bList, newCount, nextParent] = check(map[costs[i]], parent)\n        critical.push(...aList)\n        pseudo.push(...bList)\n        count += newCount\n        parent = nextParent\n        if (count === n - 1) { break }\n    }\n\n\treturn [critical, pseudo]\n};",
        "solution_java": "class Solution {\n    static class UnionFind{\n        int[]parent;\n        int[]rank;\n        int comp = 0;\n        UnionFind(int n){\n            parent = new int[n];\n            rank = new int[n];\n            comp = n;\n            for(int i=0;i<n;i++){\n                parent[i] = i;\n                rank[i] = 0;\n            }\n        }\n        \n        int find(int x){\n            if(parent[x] == x){\n                return x;\n            }else{\n                parent[x] = find(parent[x]);\n                return parent[x];\n            }\n        }\n        \n        boolean union(int X,int Y){\n            int x = find(X);\n            int y = find(Y);\n            if(x == y){\n                return false;\n            }\n            \n            if(rank[x] < rank[y]){\n                parent[x] = y;\n            }else if(rank[y] < rank[x]){\n                parent[y] = x;\n            }else{\n                parent[y] = x;\n                rank[x]++;\n            }\n            comp--;\n            return true;\n        }\n        \n        boolean isConnected(){\n            return comp == 1;\n        }\n        \n    }\n    \n    static class Edge implements Comparable<Edge>{\n        int u;\n        int v;\n        int wt;\n        Edge(int u,int v,int wt){\n            this.u = u;\n            this.v = v;\n            this.wt = wt;\n        }\n        public int compareTo(Edge o){\n            return this.wt - o.wt;\n        } \n    }\n    public int buildMST(int n,int[][]edges,int[]edgeSkip,int[]edgePick){\n        PriorityQueue<Edge> pq = new PriorityQueue<>();\n        \n        for(int[]edge : edges){\n            if(edge == edgeSkip){\n                continue;\n            }else if(edge == edgePick){\n                continue;\n            }\n            int u = edge[0];\n            int v = edge[1];\n            int wt = edge[2];\n            pq.add(new Edge(u,v,wt));\n        }\n        \n        UnionFind uf = new UnionFind(n);\n        int cost = 0;\n        \n        if(edgePick != null){\n            uf.union(edgePick[0],edgePick[1]);\n            cost += edgePick[2];\n        }\n        while(pq.size() > 0){\n            Edge rem = pq.remove();\n            if(uf.union(rem.u,rem.v) == true){\n                cost += rem.wt;\n            }\n        }\n        \n        if(uf.isConnected() == true){\n            return cost;\n        }else{\n            return Integer.MAX_VALUE;\n        }\n    }\n    \n    public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n        int mstCost = buildMST(n,edges,null,null);\n        \n        ArrayList<Integer> critical = new ArrayList<>();\n        ArrayList<Integer> pcritical = new ArrayList<>();\n        \n        for(int i=0;i<edges.length;i++){\n            int []edge = edges[i];\n            \n            int mstCostWithoutEdge = buildMST(n,edges,edge,null);\n            if(mstCostWithoutEdge > mstCost){\n                critical.add(i);        //Critical edge index\n            }else{\n                int mstCostWithEdge = buildMST(n,edges,null,edge);\n                if(mstCostWithEdge > mstCost){\n                    //redundant\n                }else{\n                    pcritical.add(i);   //pseduo critical edge index\n                }\n            }\n        }\n        \n        List<List<Integer>> res = new ArrayList<>();\n        res.add(critical);\n        res.add(pcritical);\n        return res;\n    }\n}",
        "solution_c": "class UnionFind{\nprivate:\n    vector<int> parent_;\n    vector<int> rank_;\n    int sets_;\npublic:\n    UnionFind(int n)\n    {\n        init(n);\n    }\n    void init(int n)\n    {\n        sets_ = n;\n        parent_.resize(n);\n        rank_.resize(n);\n        iota(parent_.begin(),parent_.end(),0);\n        fill(rank_.begin(),rank_.end(),1);\n    }\n    int find(int u)\n    {\n        return parent_[u] == u ? u: parent_[u] = find(parent_[u]);\n    }\n    bool join(int u,int v)\n    {\n        u = find(u);\n        v = find(v);\n\n        if(u==v)\n        {\n            return false;\n        }\n        \n        if(rank_[u]<rank_[v])\n        {\n            swap(u,v);\n        }\n\n        rank_[u] += rank_[v];\n        parent_[v] = u;\n\n        sets_ --;\n        return true;\n    }\n    bool united()\n    {\n        return sets_ == 1;\n    }\n};\nclass Solution {\npublic:\n    vector<int> edges_idx_;\n    int kruskal(const int n, const int removed_edge_idx,const int init_edge_idx,\n    const vector<vector<int>> &edges)\n    {\n        UnionFind graph(n);\n        int edges_size = edges.size();\n        int total = 0;\n\n        if(init_edge_idx != -1)\n        {\n            graph.join(edges[init_edge_idx][0],edges[init_edge_idx][1]);\n            total += edges[init_edge_idx][2];\n        }\n\n        \n        for(int i = 0; i<edges_size; ++i)    \n        {\n            int edge_idx = edges_idx_[i];\n\n            if(edge_idx == removed_edge_idx)\n            {\n                continue;\n            }\n\n            int u = edges[edge_idx][0];\n            int v = edges[edge_idx][1];\n\n            if(graph.join(u,v))\n            {\n                total+= edges[edge_idx][2];\n            }\n        }\n        \n        return graph.united() ? total : INT_MAX;\n\n    }\n    vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& edges) {\n       int edges_size = edges.size();\n\n       edges_idx_.resize(edges_size);\n\n       iota(edges_idx_.begin(),edges_idx_.end(),0);\n       \n       sort(edges_idx_.begin(),edges_idx_.end(),[&edges](int a, int b){\n           return edges[a][2] < edges[b][2];\n       });\n\n       int mst = kruskal(n,-1,-1,edges);\n       \n\n       vector<int> critical;\n       vector<int> psudo;\n       \n       for(int i = 0; i< edges_size; ++i)\n       {\n           int edge_idx = edges_idx_[i];\n           int total = kruskal(n,-1,edge_idx,edges);\n           \n           if(total == mst)\n           {\n               total = kruskal(n,edge_idx,-1,edges);\n               if(total > mst)\n               {\n                   critical.push_back(edge_idx);\n               }\n               else{\n                   psudo.push_back(edge_idx);\n               }\n           }\n       }\n\n       return {critical,psudo};\n       \n    }\n};"
    },
    {
        "title": "4Sum",
        "algo_input": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:\n\n\n\t0 &lt;= a, b, c, d&nbsp;&lt; n\n\ta, b, c, and d are distinct.\n\tnums[a] + nums[b] + nums[c] + nums[d] == target\n\n\nYou may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,0,-1,0,-2,2], target = 0\nOutput: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2], target = 8\nOutput: [[2,2,2,2]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t-109 &lt;= nums[i] &lt;= 109\n\t-109 &lt;= target &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n        \n        if len(nums) < 4: return []\n        \n        nums.sort()\n        res = []\n        \n        for i in range(len(nums)):\n            for j in range(i + 1, len(nums)):\n                l = j+1\n                r = len(nums)-1\n                while l < r:\n\n                    sum_ = nums[i]+nums[j]+nums[l]+nums[r]\n                    a = [nums[i], nums[j], nums[l], nums[r]]\n                \n                    if sum_ == target and a not in res:\n                        res.append(a)\n                  \n                    if sum_ > target:\n                        r -= 1\n                    \n                    else:\n                        l += 1\n                        while l < r and nums[l-1] == nums[l]:\n                            l += 1\n                  \n        return res\n        \n        # An Upvote will be encouraging\n                    \n        ",
        "solution_js": "var fourSum = function(nums, target) {\n    nums.sort((a, b) => a - b);\n    const res = [];\n    \n    for(let i=0; i<nums.length-3; i++) {\n        for(let j=i+1; j<nums.length-2; j++) {\n            let min = j + 1;\n            let max = nums.length - 1;\n            while(min < max) {\n                const sum = nums[i] + nums[j] + nums[min] + nums[max];\n                if(sum === target) {\n                    res.push([nums[min], nums[max], nums[i], nums[j]]);\n                    while(nums[min] === nums[min+1]) min++;\n                    while(nums[max] === nums[max-1]) max--;\n                    min++;\n                    max--;\n                }\n                \n                else if(sum > target) \n                    max--;\n                else\n                    min++\n            }\n            while(nums[j] === nums[j+1]) j++;\n        }\n        while(nums[i] === nums[i+1]) i++;\n    }\n    \n    return res;\n};",
        "solution_java": "class Solution {\n    public List<List<Integer>> fourSum(int[] nums, int target) {\n        Arrays.sort(nums);\n        List<List<Integer>> llans = new LinkedList<>();\n        if(nums == null || nums.length <= 2){\n            return llans;\n        }\n        for(int i=0;i<nums.length-3;i++){\n            for(int j=i+1;j<nums.length-2;j++){\n                int l = j+1;\n                int r = nums.length-1;\n                long ressum = target - nums[i];\n                ressum = ressum - nums[j];\n                while(l<r){\n                    if(nums[l]+nums[r] == ressum){\n                        List<Integer> ll = new LinkedList<>();\n                        ll.add(nums[i]);\n                        ll.add(nums[j]);\n                        ll.add(nums[l]);\n                        ll.add(nums[r]);\n                        llans.add(ll);\n\n                        while( l<r && nums[l]==nums[l+1]){l++;}\n                        while( l<r && nums[r]==nums[r-1]){r--;}\n                        l++;\n                        r--;\n                    }\n                    else if(nums[l]+nums[r] < ressum){\n                        l++;\n                    }\n                    else{\n                        r--;\n                    }\n                }\n                while( j<nums.length-1 && nums[j]==nums[j+1]){\n                    j++;}\n\n            }\n            while( i<nums.length-1 && nums[i]==nums[i+1]){\n                i++;}\n\n        }\n        return llans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> fourSum(vector<int>& nums, int target) {\n\n        int n = nums.size();\n\n        vector<vector<int> > answer;\n\n        if(n<4) return answer;\n\n        sort(nums.begin(),nums.end());\n\n        for(int i=0;i<n;){\n            for(int j=i+1;j<n;){\n\n                int left = j+1;\n                int right = n-1;\n\n                long long int x = (long long int)target - (long long int)nums[i] - (long long int)nums[j];\n\n                while(left<right){\n\n                    if(x == nums[left]+nums[right]){\n                    vector<int> vect{nums[i] , nums[j] , nums[left] , nums[right]};\n                    answer.push_back(vect);\n\n                    //skipping duplicates while moving right\n                    int k = 1;\n                    while((left+k)<n && nums[left+k]==nums[left]) ++k;\n\n                    if((left+k)>=n) break;\n                    else left = left+k;\n\n                    //skipping duplicates while moving left\n                    k = 1;\n                    while((right-k)>=0 && nums[right-k]==nums[right]) ++k;\n\n                    if((right-k)<0) break;\n                    else right = right-k;\n\n                }\n                else{\n\n                    if(x>nums[left]+nums[right]){\n\n                        //skipping duplicates while moving right\n                        int k = 1;\n                        while((left+k)<n && nums[left+k]==nums[left]) ++k;\n\n                        if((left+k)>=n) break;\n                        else left = left+k;\n\n                    }\n                    else{\n\n                        //skipping duplicates while moving left\n                        int k = 1;\n                        while((right-k)>=0 && nums[right-k]==nums[right]) ++k;\n\n                        if((right-k)<0) break;\n                        else right = right-k;\n\n                    }\n\n                }\n\n                }\n\n               //skipping duplicates while moving right\n               int k = 1;\n                while((j+k)<n && nums[j+k]==nums[j]) ++k;\n\n                if((j+k)>=n) break;\n                else j = j+k;\n\n            }\n\n            //skipping duplicates while moving right\n            int k = 1;\n            while((i+k)<n && nums[i+k]==nums[i]) ++k;\n\n            if((i+k)>=n) break;\n            else i = i+k;\n        }\n\n        return answer;\n    }\n};"
    },
    {
        "title": "Minimum Area Rectangle",
        "algo_input": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\n\nReturn the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput: 4\n\n\nExample 2:\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 500\n\tpoints[i].length == 2\n\t0 &lt;= xi, yi &lt;= 4 * 104\n\tAll the given points are unique.\n\n",
        "solution_py": "class Solution:\n    def minAreaRect(self, points: List[List[int]]) -> int:\n        points = sorted(points, key=lambda item: (item[0], item[1]))\n        cols = defaultdict(list)\n        \n        for x,y in points:\n            cols[x].append(y)\n        \n        lastx = {}\n        ans = float('inf')\n        \n        for x in cols:\n            col = cols[x]\n            for i, y1 in enumerate(col):\n                for j in range(i):\n                    y2 = col[j]\n                    if (y2,y1) in lastx:\n                        ans = min(ans, abs((x-lastx[y2,y1])*(y2-y1)))\n                    lastx[y2,y1] = x\n            \n        return 0 if ans==float('inf') else ans",
        "solution_js": "var minAreaRect = function(points) {\n    const mapOfPoints = new Map();\n    let minArea = Infinity;\n    for(const [x,y] of points) {\n        let keyString = `${x}:${y}`\n        mapOfPoints.set(keyString, [x, y]);\n    }\n    for(const [xLeftBottom, yLeftBottom] of points) {\n        for(const [xRightTop, yRightTop] of points) {\n            if(!foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop)) continue;\n            let leftTopCorner = `${xLeftBottom}:${yRightTop}`;\n            let rightBottomCorner = `${xRightTop}:${yLeftBottom}`;\n            \n            if(mapOfPoints.has(leftTopCorner) && mapOfPoints.has(rightBottomCorner)) {\n                const x2 = mapOfPoints.get(rightBottomCorner)[0];\n                const x1 = xLeftBottom;\n                const y1 = yLeftBottom;\n                const y2 =  mapOfPoints.get(leftTopCorner)[1]\n                const area = calculateArea(x1, x2, y1, y2);\n                \n                minArea = Math.min(minArea,area);\n            }\n        }\n        \n    }\n    return minArea === Infinity ? 0 : minArea;\n};\n\n\nfunction calculateArea(x1, x2, y1, y2) {\n    return ((x2-x1) * (y2-y1))\n}\n\nfunction foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop) {\n    return (xRightTop > xLeftBottom && yRightTop > yLeftBottom);\n}",
        "solution_java": "class Solution {\n\n    public int minAreaRect(int[][] points) {\n\n        Map<Integer, Set<Integer>> map = new HashMap<>();\n\n\t\t// Group the points by x coordinates\n        for (int[] point : points) {\n            if (!map.containsKey(point[0])) map.put(point[0], new HashSet<>());\n            map.get(point[0]).add(point[1]);\n        }\n\n        int min = Integer.MAX_VALUE;\n        for (int i = 0; i < points.length - 1; i++) {\n\n            int x1 = points[i][0];\n            int y1 = points[i][1];\n            for (int j = i + 1; j < points.length; j++) {\n                int x2 = points[j][0];\n                int y2 = points[j][1];\n                if (x1 == x2 || y1 == y2) // We are looking for diagonal point, so if j is neighbour point, then continue\n                    continue;\n\n                // Note - We are calculating area first (before checking whether these points form the correct rectangle), because\n                // cost of checking rectangle is very higher than calculating area. So if area less than the prev area (min), then only \n                // it makes sense to check rectangle and override min (if these points forms the correct rectangle)\n                int area = Math.abs(x1 - x2) * Math.abs(y1 - y2);\n                if (area < min) {\n                    boolean isRectangle = map.get(x1).contains(y2) && map.get(x2).contains(y1);\n                    if (isRectangle) min = area;\n                }\n            }\n        }\n\n        return min == Integer.MAX_VALUE ? 0 : min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minAreaRect(vector<vector<int>>& points) {\n        unordered_map<int, unordered_set<int>> pts;\n        for(auto p : points)\n        {\n            pts[p[0]].insert(p[1]);\n        }\n        \n        int minArea = INT_MAX;\n        int n = points.size();\n        for(int i=0; i<n; i++)\n        {\n            for(int j=i+1; j<n; j++)\n            {\n                auto p1 = points[i];\n                auto p2 = points[j];\n                if(pts[p1[0]].size()<2 || pts[p2[0]].size()<2) continue; // added to avoid extra loop\n                if(p1[0]!=p2[0] && p1[1]!=p2[1]){\n                    if(pts[p1[0]].count(p2[1])>0 && pts[p2[0]].count(p1[1])>0) {\n                        minArea = min(minArea, (abs(p1[0]-p2[0]) * abs(p1[1]-p2[1])) );\n                    }\n                }\n                \n            }\n        }\n        return minArea == INT_MAX ? 0 : minArea;\n    }\n};"
    },
    {
        "title": "Sort Array By Parity II",
        "algo_input": "Given an array of integers nums, half of the integers in nums are odd, and the other half are even.\n\nSort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.\n\nReturn any answer array that satisfies this condition.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,2,5,7]\nOutput: [4,5,2,7]\nExplanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n\n\nExample 2:\n\nInput: nums = [2,3]\nOutput: [2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 2 * 104\n\tnums.length is even.\n\tHalf of the integers in nums are even.\n\t0 &lt;= nums[i] &lt;= 1000\n\n\n&nbsp;\nFollow Up: Could you solve it in-place?\n",
        "solution_py": "class Solution:\n    def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n        arr = [None]*len(nums)\n        even,odd = 0,1\n        for i in(nums):\n            if i % 2 == 0:\n                arr[even] = i\n                even +=2\n        for i in (nums):\n            if i % 2 != 0:\n                arr[odd] = i\n                odd+=2\n        return arr",
        "solution_js": "var sortArrayByParityII = function(nums) {\n    let arrEven = []\n    let arrOdd = []\n    let result = []\n    for(let i in nums){\n    nums[i]%2==0 ? arrEven.push(nums[i]) : arrOdd.push(nums[i])\n    }\n    for(let i in  arrEven){\n        result.push(arrEven[i])\n        result.push(arrOdd[i])\n    }\n   return result\n};",
        "solution_java": "class Solution {\n    public int[] sortArrayByParityII(int[] nums) {\n        \n        int[] ans = new int[nums.length];\n        \n        int even_pointer = 0;\n        int odd_pointer = 1;\n        \n        for(int i = 0; i < nums.length; i++){\n            \n            if(nums[i] % 2 == 0){\n                ans[even_pointer] = nums[i];\n                even_pointer += 2;\n            } else{\n                ans[odd_pointer] = nums[i];\n                odd_pointer += 2;\n            }\n            \n        }\n        \n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> sortArrayByParityII(vector<int>& nums) {\n\n        vector<int>ans(nums.size());\n\n        int even_idx=0;\n        int odd_idx=1;\n\n        for(int i=0;i<nums.size();i++)\n        {\n            if((nums[i]%2)==0) //the num is even\n            {\n                ans[even_idx]=nums[i];\n                even_idx+=2;\n            }\n            else //the num is odd\n            {\n                ans[odd_idx]=nums[i];\n                odd_idx+=2;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Number of Days Between Two Dates",
        "algo_input": "Write a program to count the number of days between two dates.\n\nThe two dates are given as strings, their format is YYYY-MM-DD&nbsp;as shown in the examples.\n\n&nbsp;\nExample 1:\nInput: date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput: 1\nExample 2:\nInput: date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput: 15\n\n&nbsp;\nConstraints:\n\n\n\tThe given dates are valid&nbsp;dates between the years 1971 and 2100.\n\n",
        "solution_py": "from datetime import date\n\nclass Solution:\n    def daysBetweenDates(self, date1: str, date2: str) -> int:\n        return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days)",
        "solution_js": "var daysBetweenDates = function(date1, date2) {\n     let miliSecondInaDay = 24*60*60*1000;\n     if(date1>date2) return (new Date(date1) - new Date(date2)) / miliSecondInaDay\n     else return (new Date(date2) - new Date(date1)) / miliSecondInaDay\n};",
        "solution_java": "class Solution {\n    public int daysBetweenDates(String date1, String date2) {\n        String[] d1 = date1.split(\"-\");\n        String[] d2 = date2.split(\"-\");\n        return (int)Math.abs(\n            daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))\n            - daysFrom1971(Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2])));\n    }\n    private int daysFrom1971(int year, int month, int day) {\n        int total = 0;\n\t\t// count years first\n        total += (year - 1971) * 365;\n        for (int i = 1972; i < year; i += 4) {\n            if (isLeapYear(i)) total++;\n        }        \n        int feb = isLeapYear(year) ? 29 : 28;\n\t\t// sum months and days\n        switch (month) {\n            case 12: \n                total += 30; // 11\n            case 11:\n                total += 31; // 10\n            case 10: \n                total += 30; // 9\n            case 9:\n                total += 31; // 8\n            case 8:\n                total += 31; // 7\n            case 7: \n                total += 30; // 6\n            case 6:\n                total += 31; // 5\n            case 5:\n                total += 30; // 4\n            case 4: \n                total += 31; // 3\n            case 3: \n                total += feb; // 2\n            case 2:\n                total += 31;\n            case 1:\n                total += day;                \n        }\n        return total;\n    }\n    private boolean isLeapYear(int i) {\n        return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0);\n    }\n}",
        "solution_c": "class Solution\n{\npublic:\n    int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n    bool isLeap(int y)\n    {\n        return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));\n    }\n    int calc(string s)\n    {\n        int y = stoi(s.substr(0, 4));\n        int m = stoi(s.substr(5, 2));\n        int d = stoi(s.substr(8));\n        for (int i = 1971; i < y; i++)\n            d += isLeap(i) ? 366 : 365;\n        d += accumulate(begin(days), begin(days) + m - 1, 0);\n        d += (m > 2 && isLeap(y)) ? 1 : 0;\n        return d;\n    }\n    int daysBetweenDates(string date1, string date2)\n    {\n        int ans = abs(calc(date2) - calc(date1));\n        return ans;\n    }\n};"
    },
    {
        "title": "Super Pow",
        "algo_input": "Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.\n\n&nbsp;\nExample 1:\n\nInput: a = 2, b = [3]\nOutput: 8\n\n\nExample 2:\n\nInput: a = 2, b = [1,0]\nOutput: 1024\n\n\nExample 3:\n\nInput: a = 1, b = [4,3,3,8,5,2]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a &lt;= 231 - 1\n\t1 &lt;= b.length &lt;= 2000\n\t0 &lt;= b[i] &lt;= 9\n\tb does not contain leading zeros.\n\n",
        "solution_py": "class Solution:\n    def superPow(self, a: int, b: List[int]) -> int:\n        mod = 1337\n        ans = 1\n\n        for power in b:\n            ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod\n\n        return ans",
        "solution_js": "var superPow = function(a, b) {\n    const MOD = 1337;\n    const pow = (num, n) => {\n        let result = 1;\n        for (let index = 0; index < n; index++) {\n            result = result * num % MOD;\n        }\n        return result;\n    };\n\n    return b.reduceRight((result, n) => {\n        a %= MOD;\n        const powNum = result * pow(a, n) % MOD;\n\n        a = pow(a, 10);\n        return powNum;\n    }, 1);\n};",
        "solution_java": "import java.math.BigInteger;\nclass Solution {\n    public int superPow(int a, int[] b) {\n        StringBuilder bigNum = new StringBuilder();\n        Arrays.stream(b).forEach(i -> bigNum.append(i));\n        \n        return \n            BigInteger.valueOf(a)\n            .modPow(new BigInteger(bigNum.toString()), BigInteger.valueOf(1337))\n            .intValue();\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int binaryExp(int a, int b, int M)\n    {\n        int ans = 1;\n        a %= M;\n        while(b)\n        {\n            if(b&1) ans = (ans * a)%M;\n            a = (a*a)%M, b = b>>1;\n        }\n        return ans;\n    }\n    \n    int superPow(int a, vector<int>& b) {\n        int bmod = 0;\n        for(auto it : b)\n        {\n            bmod = (bmod * 10 + it)%1140;\n        }\n        \n        return binaryExp(a, bmod, 1337);\n    }\n};"
    },
    {
        "title": "Construct Binary Search Tree from Preorder Traversal",
        "algo_input": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.\n\nIt is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.\n\nA binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.\n\nA preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.\n\n&nbsp;\nExample 1:\n\nInput: preorder = [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\n\n\nExample 2:\n\nInput: preorder = [1,3]\nOutput: [1,null,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= preorder.length &lt;= 100\n\t1 &lt;= preorder[i] &lt;= 1000\n\tAll the values of preorder are unique.\n\n",
        "solution_py": "class Solution:\n\tdef bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n\t\tif not preorder:\n\t\t\treturn None\n\t\tnode = preorder.pop(0)\n\t\troot = TreeNode(node)\n\t\tl = []\n\t\tr = []\n\n\t\tfor val in preorder:\n\t\t\tif val < node:\n\t\t\t\tl.append(val)\n\t\t\telse:\n\t\t\t\tr.append(val)\n\n\t\troot.left = self.bstFromPreorder(l)\n\t\troot.right =  self.bstFromPreorder(r)\n\t\treturn root",
        "solution_js": "var bstFromPreorder = function(preorder) {\n  let head = new TreeNode(preorder[0]);\n  for (let i = 1, curr; i<preorder.length; i++) {\n     curr = head;\n     while (1) {\n        if (preorder[i]>curr.val) \n          if (curr.right !=null) { curr = curr.right; }\n          else { curr.right = new TreeNode(preorder[i]); break; }\n        else\n          if (curr.left !=null) { curr = curr.left; }\n          else { curr.left = new TreeNode(preorder[i]); break; }\n     } \n  } \n  return head;  \n};",
        "solution_java": "class Solution {\n    public TreeNode bstFromPreorder(int[] preorder) {\n        return bst(preorder, 0, preorder.length-1);\n    }\n\n    public TreeNode bst(int[] preorder, int start, int end){\n        if(start > end) return null;\n\n        TreeNode root = new TreeNode(preorder[start]);\n        int breakPoint = start+1;\n        while(breakPoint <= end && preorder[breakPoint] < preorder[start]){\n            breakPoint++;\n        }\n\n        root.left = bst(preorder, start+1, breakPoint-1);\n        root.right = bst(preorder, breakPoint, end);\n        return root;\n    }\n}",
        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* help(int &i,vector<int>& preorder, int bound ){\n        if(i==preorder.size() || preorder[i] > bound)\n            return NULL;\n         TreeNode* root = new TreeNode(preorder[i++]);\n         root->left = help(i,preorder,root->val);\n         root->right = help(i,preorder,bound);\n        return root;\n    }\n    TreeNode* bstFromPreorder(vector<int>& preorder) {\n     \n        int i=0;\n        return help(i,preorder,INT_MAX);\n    }\n};"
    },
    {
        "title": "Palindrome Partitioning",
        "algo_input": "Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.\n\nA palindrome string is a string that reads the same backward as forward.\n\n&nbsp;\nExample 1:\nInput: s = \"aab\"\nOutput: [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\nExample 2:\nInput: s = \"a\"\nOutput: [[\"a\"]]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 16\n\ts contains only lowercase English letters.\n\n",
        "solution_py": "\"\"\"\nwe can approach this problem using manacher's algorithm with backtracking and recursion\n\"\"\"\nclass Solution:\n    def partition(self, s: str) -> List[List[str]]:\n        lookup = {\"\": [[]]}\n        def lps(s):\n            if s in lookup:\n                return lookup[s]\n\n            final_res = []\n            result_set = set()\n            for k in range(len(s)):\n                i, j = k, k\n\n                # check for odd length palindromes\n                while i>= 0 and j < len(s) and s[i] == s[j]:\n                    # palindrome found\n                    res = []\n                    for partition in lps(s[:i]):\n                        res.append(partition + [s[i:j+1]])\n                    for partition in res:\n                        for part in lps(s[j+1:]):\n                            temp = partition + part\n                            if tuple(temp) not in result_set:\n                                result_set.add(tuple(temp))\n                                final_res.append(temp)\n                    i-=1\n                    j+=1\n\n                # check for even length palindromes\n                i, j = k, k+1\n                while i >= 0 and j < len(s) and s[i] == s[j]:\n                    # palindrome found\n                    res = []\n                    for partition in lps(s[:i]):\n                        res.append(partition + [s[i:j+1]])\n                    for partition in res:\n                        for part in lps(s[j+1:]):\n                            temp = partition + part\n                            if tuple(temp) not in result_set:\n                                result_set.add(tuple(temp))\n                                final_res.append(temp)\n                    i-=1\n                    j+=1\n            lookup[s] = final_res\n            return final_res\n        return lps(s)",
        "solution_js": "var partition = function(s) {\n    let result = []\n    backtrack(0, [], s, result)\n    return result\n};\n\nfunction backtrack(i, partition, s, result){\n    if(i === s.length){\n        result.push([...partition])\n        return\n    }\n\n    for(let j=i;j<s.length;j++){\n        let str = s.slice(i,j+1)\n        if(isPal(str)){\n            partition.push(str)\n            backtrack(j+1, partition, s, result)\n            partition.pop()\n        }\n    }\n}\n\nfunction isPal(str){\n    return JSON.stringify(str.split('').reverse()) === JSON.stringify(str.split(''))\n}",
        "solution_java": "// Plaindrome Partitioning\n// Leetcode : https://leetcode.com/problems/palindrome-partitioning/\n\nclass Solution {\n    public List<List<String>> partition(String s) {\n        List<List<String>> result = new ArrayList<>();\n        if(s == null || s.length() == 0)\n            return result;\n        helper(s, 0, new ArrayList<String>(), result);\n        return result;\n    }\n    private void helper(String s, int start, List<String> list, List<List<String>> result){\n        if(start == s.length()){\n            result.add(new ArrayList<>(list));\n            return;\n        }\n        for(int i = start; i < s.length(); i++){\n            if(isPalindrome(s, start, i)){\n                list.add(s.substring(start, i+1));\n                helper(s, i+1, list, result);\n                list.remove(list.size()-1);\n            }\n        }\n    }\n    private boolean isPalindrome(String s, int start, int end){\n        while(start < end){\n            if(s.charAt(start++) != s.charAt(end--))\n                return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool check(string k)\n    {\n        string l=k;\n        reverse(l.begin(),l.end());\n        if(k==l)return true;\n        return false;\n    }\n    void solve(string &s,vector<vector<string>>&ans,\n               vector<string>temp,int pos)\n    {\n        if(pos>=s.size()){ans.push_back(temp); return;}\n        string m;\n        for(int i=pos;i<s.size();i++)\n        {\n            m+=s[i];\n            if(check(m))\n            {temp.push_back(m);\n            solve(s,ans,temp,i+1);\n            temp.pop_back();}\n        }\n    }\n    vector<vector<string>> partition(string s) {\n        vector<vector<string>>ans;\n        vector<string>temp;\n        solve(s,ans,temp,0);\n        return ans;\n    }\n};"
    },
    {
        "title": "Element Appearing More Than 25% In Sorted Array",
        "algo_input": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2,2,6,6,6,6,7,10]\nOutput: 6\n\n\nExample 2:\n\nInput: arr = [1,1]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t0 &lt;= arr[i] &lt;= 105\n\n",
        "solution_py": "class Solution:\n    def findSpecialInteger(self, arr: List[int]) -> int:\n        l=len(arr)\n        c=(l//4)+1\n        d={}\n        for i in arr:\n            if i in d:\n                d[i]+=1\n            else:\n                d[i]=1\n            if d[i]>=c:\n                return i",
        "solution_js": "function binarySearch(array, target, findFirst) {\n    function helper(start, end) {\n        if (start > end) {\n            return -1;\n        }       \n        \n        const middle = Math.floor((start + end) / 2);\n        const value = array[middle];\n        \n        if (value === target) {\n            if (findFirst) {\n                if (middle === 0 || array[middle - 1] !== value) {\n                    return middle;\n                }\n                \n                return helper(start, middle - 1);\n            } else {\n                if (middle === array.length -1 || array[middle + 1] !== value) {\n                    return middle;\n                }\n                \n                return helper(middle + 1, end);\n            }\n        } else if (value < target) {\n          return helper(middle + 1, end);    \n        }\n        \n        return helper(start, middle - 1);\n    }\n    \n    return helper(0, array.length - 1)\n}\n\nconst findFirstOccurance = (array, target) => binarySearch(array, target, true);\nconst findLastOccurance = (array, target) => binarySearch(array, target, false);\n\nvar findSpecialInteger = function(arr) {\n    for (const i of [Math.floor(arr.length / 4), Math.floor(arr.length / 2), Math.floor(3 * arr.length / 4)]) {\n        const firstOccurance = findFirstOccurance(arr, arr[i]);\n        const lastOccurance = findLastOccurance(arr, arr[i]);\n                \n        if (lastOccurance - firstOccurance + 1 > arr.length / 4) {\n            return arr[i]\n        }\n    }\n    \n    return -1;\n};",
        "solution_java": "class Solution {\n     public int findSpecialInteger(int[] arr) {\n        if (arr.length == 1) {\n            return arr[0];\n        }\n        int count = (int) Math.ceil(arr.length / 4);\n        System.out.println(count);\n\n        Map<Integer, Integer> map = new HashMap<>();\n\n        for (Integer i : arr) {\n            map.put(i, map.getOrDefault(i, 0) + 1);\n            if (map.get(i) > count) {\n                return i;\n            }\n        }\n        return -1;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findSpecialInteger(vector<int>& arr) {\n        \n        int freq = 0.25 * arr.size();\n        map<int,int>m;\n        for(int i: arr)\n            m[i]++;\n        \n        int k;\n        for(auto i: m)\n        {\n            if(i.second > freq)\n            {\n              k = i.first;\n                break;\n            }\n        }\n        return k;\n    }\n};"
    },
    {
        "title": "Where Will the Ball Fall",
        "algo_input": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.\n\nEach cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.\n\n\n\tA board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.\n\tA board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.\n\n\nWe drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box.\n\nReturn an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.\n\n&nbsp;\nExample 1:\n\n\n\nInput: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput: [1,-1,-1,-1,-1]\nExplanation: This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\n\n\nExample 2:\n\nInput: grid = [[-1]]\nOutput: [-1]\nExplanation: The ball gets stuck against the left wall.\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput: [0,1,2,3,4,-1]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 100\n\tgrid[i][j] is 1 or -1.\n\n",
        "solution_py": "class Solution:\n    def findBall(self, grid: List[List[int]]) -> List[int]:\n\n        m,n=len(grid),len(grid[0])\n        for i in range(m):\n            grid[i].insert(0,1)\n            grid[i].append(-1)\n        res=[]\n\n        for k in range(1,n+1):\n            i , j = 0 , k\n            struck = False\n            while i<m:\n                if grid[i][j]==1:\n                    if grid[i][j+1]==1:\n                        j+=1\n                    else:\n                        struck=True\n                        break\n                else:\n                    if grid[i][j-1]==-1:\n                        j-=1\n                    else:\n                        struck=True\n                        break\n                i+=1\n            if struck:\n                res.append(-1)\n            else:\n                res.append(j-1)\n\n        return res",
        "solution_js": "var findBall = function(grid) {\n    let m = grid.length,\n        n = grid[0].length,\n        ans = []\n    for (let start = 0; start < n; start++) {     // Iterate through the different starting conditions\n        let j = start\n        for (let i = 0; i < m; i++) {             // Then iterate downward from grid[i][j]\n            let dir = grid[i][j]                  // Compare the direction of the current cell to the direction\n            if (dir === grid[i][j+dir]) j += dir  //   of the cell on the slant side and move that way if matched\n            else i = m, j = -1                    // Otherwise jump to the loop's end and set j to the fail value\n        }\n        ans[start] = j                            // Update the answer\n    }\n    return ans                                    // Return the completed answer\n};",
        "solution_java": "class Solution {\n    public int dfs(int[][] grid, int i, int j){\n        if(i==grid.length)\n            return j;\n\n        if(j<0 || j>=grid[0].length)\n            return -1;\n\n        if(grid[i][j]==1 && j+1<grid[0].length && grid[i][j+1]==1)\n            return dfs(grid,i+1,j+1);\n\n        else if(grid[i][j]==-1 && j-1>=0 && grid[i][j-1]==-1)\n            return dfs(grid,i+1,j-1);\n\n        return -1;\n    }\n    public int[] findBall(int[][] grid) {\n        int m = grid[0].length;\n        int[] ar = new int[m];\n\n        for(int j=0;j<m;j++)\n            ar[j]=dfs(grid,0,j);\n\n        return ar;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int util(vector<vector<int>>&grid,bool top,int i,int j)\n    {\n        if(top==0&&i==grid.size()-1)return j;\n        if(top==1)\n        {\n            if(grid[i][j]==1)\n            {\n                if(j+1>=grid[0].size()||grid[i][j+1]==-1)return -1;\n                return util(grid,!top,i,j+1);\n            }\n            else\n            {\n                if(j-1<0||grid[i][j-1]==1)return -1;\n                return util(grid,!top,i,j-1);\n            }\n        }\n        else\n        {\n            return util(grid,!top,i+1,j);\n        }\n    }\n    vector<int> findBall(vector<vector<int>>& grid) {\n        vector<int>ans(grid[0].size(),-1);\n        for(int i=0;i<grid[0].size();i++)\n        {\n            ans[i]=util(grid,true,0,i);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Max Number of K-Sum Pairs",
        "algo_input": "You are given an integer array nums and an integer k.\n\nIn one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.\n\nReturn the maximum number of operations you can perform on the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4], k = 5\nOutput: 2\nExplanation: Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.\n\nExample 2:\n\nInput: nums = [3,1,3,4,3], k = 6\nOutput: 1\nExplanation: Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\t1 &lt;= k &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def maxOperations(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        left = 0\n        right = len(nums) - 1\n        ans = 0\n        while left < right:\n            cur = nums[left] + nums[right]\n            if cur == k:\n                ans += 1\n                left += 1\n                right -= 1\n            elif cur < k:\n                left += 1\n            else:\n                right -= 1\n        \n        return ans",
        "solution_js": "var maxOperations = function(nums, k) {\nlet freq = new Map(),count=0; \nfor (let i = 0; i < nums.length; i++) {\n    if (freq.get(k-nums[i])) {\n        if(freq.get(k-nums[i])==1) freq.delete(k-nums[i])\n        else freq.set(k-nums[i],freq.get(k-nums[i])-1)\n        count++;\n    }else freq.set(nums[i],freq.get(nums[i])+1||1)\n} \nreturn count;\n};",
        "solution_java": "class Solution {\n    public int maxOperations(int[] nums, int k) {\n        HashMap<Integer,Integer>map=new HashMap<>();\n        int count=0;\n        for(int i=0;i<nums.length;i++){\n            //to check if that k-nums[i] present and had some value left or already paired\n            if(map.containsKey(k-nums[i])&&map.get(k-nums[i])>0){\n                count++;\n                map.put(k-nums[i],map.get(k-nums[i])-1);\n            }else{\n                //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1\n                //and if some value is present then it return that value \"similar to map.get(i)\" and I added 1 on it \n                map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxOperations(vector<int>& nums, int k) {\n      unordered_map<int, int> Map;\n      for (auto &num: nums) Map[num]++;  // count freq of nums\n      int ans = 0;\n  \n      for(auto it=Map.begin(); it!=Map.end(); ++it){\n        int num = it->first, count = it->second;\n        if(k - num == num) ans += count/2;   // if num is half of k add half of it's count in ans\n        else if(Map.count(k - num)){   // find k-num in nums and add min freq of num or k-num to ans\n          int Min = min(count, Map[k-num]);\n          ans += Min;\n          Map[num] -= Min;\n          Map[k-num] -= Min;\n        }\n      }\n      \n      return ans;\n    }\n};"
    },
    {
        "title": "Assign Cookies",
        "algo_input": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.\n\nEach child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] &gt;= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.\n\n&nbsp;\nExample 1:\n\nInput: g = [1,2,3], s = [1,1]\nOutput: 1\nExplanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.\n\n\nExample 2:\n\nInput: g = [1,2], s = [1,2,3]\nOutput: 2\nExplanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= g.length &lt;= 3 * 104\n\t0 &lt;= s.length &lt;= 3 * 104\n\t1 &lt;= g[i], s[j] &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def findContentChildren(self, g: List[int], s: List[int]) -> int:\n        g.sort()\n        s.sort()\n        cont = 0\n        c = 0\n        k = 0\n        while k< len(s) and c < len(g):\n            if s[k] >= g[c]:\n                c+=1\n                k+=1\n                cont+=1\n            else:\n                k+=1\n        return cont",
        "solution_js": "var findContentChildren = function(g, s) {\n\tg.sort(function(a, b) {\n\t\treturn b - a;\n\t});\n\ts.sort(function(a, b) {\n\t\treturn a - b;\n\t});\n\t\n    let content = 0;\n    for (let curG of g) {\n        for (let curS of s) {\n            if (curS >= curG) {\n                s.pop();\n\t\t\t\tcontent++;\t\n\t\t\t    break;\n            }\n        }\n    }\n\n\treturn content;\n}",
        "solution_java": "class Solution {\n    public int findContentChildren(int[] g, int[] s) {\n        int i =0,j=0,c=0;\n        \n        Arrays.sort(g);\n        Arrays.sort(s);\n        \n        \n        for(;i< g.length;i++)\n        {\n                // System.out.println(s[j]+\" \"+g[i]);\n \n            while(j<s.length)\n            {\n                if(s[j]>=g[i] )\n                {\n                    // System.out.println(s[j]+\" \"+g[i]);\n                    j++;c++;\n                    break;\n                }\n                j++;\n            }\n        }\n       \n        return c;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findContentChildren(vector<int>& g, vector<int>& s) {\n        int n=g.size();\n        int m=s.size();\n        if(n==0 or m==0)return 0;\n        sort(g.begin(),g.end());\n        sort(s.begin(),s.end());\n        int i=0,j=0;\n        while(i<m and j<n)\n        {\n            if(s[i]>=g[j])\n                j++;\n            i++;\n        }\n        return j;\n    }\n};"
    },
    {
        "title": "Split a String in Balanced Strings",
        "algo_input": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters.\n\nGiven a balanced string s, split it into some number of substrings such that:\n\n\n\tEach substring is balanced.\n\n\nReturn the maximum number of balanced strings you can obtain.\n\n&nbsp;\nExample 1:\n\nInput: s = \"RLRRLLRLRL\"\nOutput: 4\nExplanation: s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.\n\n\nExample 2:\n\nInput: s = \"RLRRRLLRLL\"\nOutput: 2\nExplanation: s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2nd and 5th substrings are not balanced.\n\nExample 3:\n\nInput: s = \"LLLLRRRR\"\nOutput: 1\nExplanation: s can be split into \"LLLLRRRR\".\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 1000\n\ts[i] is either 'L' or 'R'.\n\ts is a balanced string.\n\n",
        "solution_py": "class Solution:\n    def balancedStringSplit(self, s: str) -> int:\n        r_count=l_count=t_count=0\n        for i in s:\n            if i=='R':\n                r_count+=1\n            elif i=='L':\n                l_count+=1\n            if r_count==l_count:\n                t_count+=1\n                r_count=0\n                l_count=0\n            continue\n        return t_count",
        "solution_js": "var balancedStringSplit = function(s) {\n    let r_count = 0;\n    let l_count = 0;\n    let ans =0;\n    for(let i = 0 ; i < s.length;i++){\n        if(s[i]==='R') r_count++;\n        else l_count++;\n\n        if(l_count==r_count) {\n         l_count=0\n        r_count=0;\n            ans++\n        }\n\n    }\n    return ans\n};",
        "solution_java": "class Solution {\n    public int balancedStringSplit(String s) {\n        int nl = 0;\n        int nr = 0;\n        int count = 0;\n        for (int i = 0; i < s.length(); ++i) {\n            if (s.substring(i,i+1).equals(\"L\")) ++nl;\n            else ++nr;\n            if (nr == nl) {\n                ++count;\n            }\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tint balancedStringSplit(string s) {\n\n\t\tint left = 0;\n\t\tint right = 0;\n\t\tint cnt = 0;\n\n\t\tfor(int i=0 ; i<s.size() ; i++){\n\t\t\tif(s[i] == 'L'){\n\t\t\t\tleft++;\n\t\t\t}\n\t\t\tif(s[i] == 'R'){\n\t\t\t\tright++;\n\t\t\t}\n\n\t\t\tif(left - right == 0){\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\n\t\treturn cnt;\n\t}\n}"
    },
    {
        "title": "Form Array by Concatenating Subarrays of Another Array",
        "algo_input": "You are given a 2D integer array groups of length n. You are also given an integer array nums.\n\nYou are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i &gt; 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).\n\nReturn true if you can do this task, and false otherwise.\n\nNote that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.\n\n&nbsp;\nExample 1:\n\nInput: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput: true\nExplanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.\n\n\nExample 2:\n\nInput: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput: false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].\n\n\nExample 3:\n\nInput: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput: false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).\n\n\n&nbsp;\nConstraints:\n\n\n\tgroups.length == n\n\t1 &lt;= n &lt;= 103\n\t1 &lt;= groups[i].length, sum(groups[i].length) &lt;= 103\n\t1 &lt;= nums.length &lt;= 103\n\t-107 &lt;= groups[i][j], nums[k] &lt;= 107\n\n",
        "solution_py": "class Solution:\n    def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n        groups = ['-'.join(str(s) for s in group) for group in groups]\n        nums = '-'.join(str(s) for s in nums)\n        j = k = 0\n        while k < len(groups):\n            group = groups[k]\n            i = nums.find(group, j)\n            if i == -1: return False\n            if i == 0 or i > 0 and nums[i-1] == '-':\n                j = i + len(group)\n                k += 1\n            else: j += 1\n        return True    ",
        "solution_js": "/**\n * @param {number[][]} groups\n * @param {number[]} nums\n * @return {boolean}\n */\nvar canChoose = function(groups, nums) {\n    let i=0;\n    for(let start=0;i<groups.length&&groups[i].length+start<=nums.length;start++){\n        \n        if(search(groups[i], nums, start)){\n            start+=groups[i].length-1;\n            i++;\n        }\n    }\n    return i==groups.length;\n    \n    function search(group, nums, start){\n        for(let i =0;i<group.length;i++){\n            if(group[i]!=nums[i+start]) return false;\n        }\n        return true;\n    }\n};",
        "solution_java": "class Solution {\n    \n    public int search(int[] group, int[] nums, int start, int end )\n    {\n        int i=start, j=0;\n        while(i<end && j<group.length)\n        {\n            if(nums[i] == group[j])\n            {\n                i++;\n                j++;\n\n                if(j == group.length)\n                    return i;\n            }\n\n            else {\n                i = i - j + 1;\n                j = 0;\n            }\n\n        }\n        return -1;\n    }\n    public boolean canChoose(int[][] groups, int[] nums) {\n        int start=0, end =nums.length;\n        \n        for(int[] group : groups)\n        {\n            start = search(group, nums, start, end);\n            if(start == -1)\n                return false;\n        }\n        \n        return true;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    //Idea is to use KMP Longest Prefix Suffix array to match if one array is subarray of another array.\n    bool canChoose(vector<vector<int>>& groups, vector<int>& nums) {\n        int m = nums.size();\n        int index = 0;\n        for(auto group : groups){\n            int n = group.size();\n            //Step-1 Generate LPS\n            vector<int>lps(n,0);\n            for(int i = 1;i<n; i++){\n                int j = lps[i-1];\n                while(j>0 && group[i] != group[j]){\n                    j = lps[j-1];\n                }\n                if(group[i] == group[j]){\n                    j++;\n                }\n                lps[i] = j;\n            }\n\n            //Step 2 - Matching\n            int j = 0;\n            while(index<m){\n                if(nums[index]==group[j]){\n                    j++;\n                    index++;\n                }\n                if(j==n)\n                    break;\n                else\n                 if(index <m && nums[index] != group[j]){\n                    if(j >0){\n                        j=lps[j-1];\n                    }else{\n                        index++;\n                    }\n                }\n            }\n            if(j != n)\n                return false;\n        }\n\n        return true;\n    }\n};"
    },
    {
        "title": "Find K Pairs with Smallest Sums",
        "algo_input": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.\n\nDefine a pair (u, v) which consists of one element from the first array and one element from the second array.\n\nReturn the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput: [[1,2],[1,4],[1,6]]\nExplanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n\n\nExample 2:\n\nInput: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput: [[1,1],[1,1]]\nExplanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n\n\nExample 3:\n\nInput: nums1 = [1,2], nums2 = [3], k = 3\nOutput: [[1,3],[2,3]]\nExplanation: All possible pairs are returned from the sequence: [1,3],[2,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 105\n\t-109 &lt;= nums1[i], nums2[i] &lt;= 109\n\tnums1 and nums2 both are sorted in ascending order.\n\t1 &lt;= k &lt;= 104\n\n",
        "solution_py": "import heapq\nclass Solution:\n    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n\n        ans = []\n\n        heapq.heapify(ans)\n\n        for i in range(min(k,len(nums1))):\n            for j in range(min(k,len(nums2))):\n                pairs = [nums1[i],nums2[j]]\n                if len(ans)<k:\n                    heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs])\n                else:\n                    if nums1[i]+nums2[j]>-ans[0][0]:\n                        break\n                    heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs])\n                    heapq.heappop(ans)\n\n        res = []\n        for i in range(len(ans)):\n            res.append(ans[i][1])\n\n        return res",
        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[][]}\n */\n\nvar kSmallestPairs = function(nums1, nums2, k) {\n    const h = new MinHeap();\n    h.sortKey = 'id';\n    for(i =0; i<nums1.length; i++)\n        h.push({id: nums1[i]+nums2[0], i: i, j: 0});\n    let res = [];\n    while(k--){\n        const t = h.pop();\n        if(!t) return res;\n        let {i, j} =t;\n        res.push([nums1[i], nums2[j]]);\n        if(j< nums2.length-1)\n            h.push({id: nums1[i]+nums2[j+1], i, j: j+1});\n    }\n    return res;\n};\n\n\n/*\nThis is a heap class that I wrote it myself,\nneat? IDK\nbad? IDK\nbug? IDK (tested a few times for both min and max heaps)\nso use it at your own risk :)\n*/\nclass Heap{\n\tconstructor(arr = [], sortKey=null){\n\t\tthis.heap = [];\n\t\tthis.sortKey = sortKey;\n\t\tif(arr && arr.length)\n\t\t\tthis.buildHeap(arr);\n\t}\n    \n\tpush(val){\n\t\tthis.heap.push(val);\n\t\tthis.heapUp(this.heap.length-1);\n\t}\n\n\tpop(){\n\t\tif(!this.heap.length) return null;\n\t\tif(this.heap.length==1) return this.heap.pop();\n\t\tconst res = this.heap[0];\n\t\tthis.heap[0] = this.heap.pop();\n\t\tthis.heapDown(0);\n\t\treturn res;\n\t}\n\n\n\tid(i){\n\t\tif(this.sortKey!==null) return this.heap[i][this.sortKey];\n\t\treturn this.heap[i];\n\t}\n\n\tswap(i, j){\n\t\tconst t = this.heap[i];\n\t\tthis.heap[i] = this.heap[j];\n\t\tthis.heap[j] = t;\n\t}\n\t/*for child class to implement*/\n\theapUp(i){\n\t\t//heap up\n\t}\n\n\theapDown(i){\n\t\t//heap down\n\t}\n\n\tbuildHeap(list){\n\t\t//build heap\n\t\tfor(let i of list)\n\t\t\tthis.push(i);\n\t}\n\n\ttoString(){\n\t\treturn this.heap;\n\t}\n\n}\n\n\nclass MinHeap extends Heap{\n\theapUp(i){\n\t\tconst pI = (i-1)>>1;\n\t\tif(pI<0) return;\n\t\tif(this.id(i)<this.id(pI)){\n\t\t \tthis.swap(i, pI);\n\t\t \treturn this.heapUp(pI);\n\t\t}\n\t}\n\n\theapDown(i){\n\t\tconst lI = i*2+1;\n\t\tconst rI = i*2+2;\n\t\tif(lI>=this.heap.length) return;\n\t\tconst v = Math.min(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MAX_VALUE:this.id(rI));\n\t\tif(v==this.id(i)) return;\n\t\tif(v==this.id(lI)){\n\t\t\tthis.swap(i, lI);\n\t\t\treturn this.heapDown(lI);\n\t\t}\n\t\tthis.swap(i, rI);\n\t\tthis.heapDown(rI);\n\t}\n}\n\n\nclass MaxHeap extends Heap{\n\theapUp(i){\n\t\tconst pI = (i-1)>>1;\n\t\tif(pI<0) return;\n\t\tif(this.id(i)>this.id(pI)){\n\t\t \tthis.swap(i, pI);\n\t\t \treturn this.heapUp(pI);\n\t\t}\n\t}\n\n\theapDown(i){\n\t\tconst lI = i*2+1;\n\t\tconst rI = i*2+2;\n\t\tif(lI>=this.heap.length) return;\n\t\tconst v = Math.max(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MIN_VALUE:this.id(rI));\n\t\tif(v==this.id(i)) return;\n\t\tif(v==this.id(lI)){\n\t\t\tthis.swap(i, lI);\n\t\t\treturn this.heapDown(lI);\n\t\t}\n\t\tthis.swap(i, rI);\n\t\tthis.heapDown(rI);\n\t}\n}",
        "solution_java": "class Solution {\n    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n        PriorityQueue<int []> pq = new PriorityQueue<>(\n            (a, b) -> (a[0] + a[1]) - (b[0] + b[1])\n        );\n        for(int i = 0; i < nums1.length && i < k; i++){\n            pq.add(new int[]{nums1[i], nums2[0], 0});\n        }\n\n        List<List<Integer>> res = new ArrayList<>();\n        for(int i = 0; i < k && !pq.isEmpty(); i++){\n            int [] curr = pq.poll();\n            res.add(Arrays.asList(curr[0], curr[1]));\n            int idx2 = curr[2];\n            if(idx2 < nums2.length - 1){\n                pq.add(new int[]{curr[0], nums2[idx2 + 1], idx2 + 1});\n            }\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {\n        priority_queue<pair<int,pair<int,int>>> pq;\n        int m=nums1.size(),n=nums2.size();\n\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                int sum=nums1[i]+nums2[j];\n                if(pq.size()<k){\n                    pq.push({sum,{nums1[i],nums2[j]}});\n                }else if(sum<pq.top().first){\n                    pq.pop();\n                    pq.push({sum,{nums1[i],nums2[j]}});\n                }else break;\n            }\n        }\n\n        vector<vector<int>> ans;\n        while(!pq.empty()){\n            auto p=pq.top().second;\n            pq.pop();\n\n            ans.push_back({p.first,p.second});\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Binary Tree Pruning",
        "algo_input": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.\n\nA subtree of a node node is node plus every node that is a descendant of node.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,0,0,1]\nOutput: [1,null,0,null,1]\nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n\n\nExample 2:\n\nInput: root = [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\n\nExample 3:\n\nInput: root = [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 200].\n\tNode.val is either 0 or 1.\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n        \n        def dfs(node):\n            if not node:\n                return None\n            \n            left = dfs(node.left)\n            right = dfs(node.right)\n            if node.val == 0 and not left and not right:\n                return None\n            else:\n                node.left = left\n                node.right = right\n                return node\n        \n        return dfs(root)\n            ",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode}\n */\nvar pruneTree = function(root) {\n    let rec = function(node){\n        if(node==null) return null;\n        if(node.val===0 && node.left == null && node.right == null){\n            return null\n        }\n        node.left = rec(node.left);\n        node.right = rec(node.right);\n        // For updated tree structure if threre are leaf nodes with zero value present, if yes then return null otherewise return node itself.\n        if(node.val===0 && node.left == null && node.right == null){\n            return null\n        }\n        return node;\n    }\n    rec (root);\n    if(root.val == 0 && root.left == null && root.right == null) return null\n\n    return root;\n};",
        "solution_java": "class Solution {\n    public TreeNode pruneTree(TreeNode root) {\n        \n        if(root == null) return root;\n        \n        root.left = pruneTree(root.left);\n        root.right = pruneTree(root.right);\n    \n        if(root.left == null && root.right == null && root.val == 0) return null;\n        else return root;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    TreeNode* pruneTree(TreeNode* root) {\n        if(!root) return NULL;\n        root->left = pruneTree(root->left);\n        root->right = pruneTree(root->right);\n        if(!root->left && !root->right && root->val==0) return NULL;\n        return root;\n    }\n    \n   \n};"
    },
    {
        "title": "Apply Discount to Prices",
        "algo_input": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.\n\n\n\tFor example, \"$100\", \"$23\", and \"$6\" represent prices while \"100\", \"$\", and \"$1e5\" do not.\n\n\nYou are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.\n\nReturn a string representing the modified sentence.\n\nNote that all prices will contain at most 10 digits.\n\n&nbsp;\nExample 1:\n\nInput: sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\nOutput: \"there are $0.50 $1.00 and 5$ candies in the shop\"\nExplanation: \nThe words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".\n\n\nExample 2:\n\nInput: sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\nOutput: \"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\nExplanation: \nApplying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentence.length &lt;= 105\n\tsentence consists of lowercase English letters, digits, ' ', and '$'.\n\tsentence does not have leading or trailing spaces.\n\tAll words in sentence are separated by a single space.\n\tAll prices will be positive numbers without leading zeros.\n\tAll prices will have at most 10 digits.\n\t0 &lt;= discount &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def discountPrices(self, sentence: str, discount: int) -> str:\n        s = sentence.split() # convert to List to easily update\n        m = discount / 100 \n        for i,word in enumerate(s):\n            if word[0] == \"$\" and word[1:].isdigit(): # Check whether it is in correct format\n                num = int(word[1:]) * (1-m) # discounted price\n                w = \"$\" + \"{:.2f}\".format(num) #correctly format\n                s[i] = w #Change inside the list\n        \n        return \" \".join(s) #Combine the updated list\n\t\t```",
        "solution_js": "var discountPrices = function(sentence, discount) {\n    let isNum = (num) => {\n        if(num.length <= 1 || num[0] != '$') return false;\n        for(let i = 1; i < num.length; ++i)\n            if(!(num[i] >= '0' && num[i] <= '9'))\n                return false;\n        return true;\n    };\n    let x = sentence.split(' ');\n    discount = 1 - (discount/100);\n    for(let i = 0; i < x.length; ++i) \n        !isNum(x[i]) || (x[i] = `$${(Number(x[i].slice(1))*discount).toFixed(2)}`);\n    return x.join(' ');\n};",
        "solution_java": "class Solution {\n\n    public String discountPrices(String sentence, int discount) {\n        String x[] = sentence.split(\" \");\n        StringBuilder sb = new StringBuilder();\n        for (String s : x) {\n            if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + \" \"); \n            else sb.append(s + \" \");\n        }\n        sb.deleteCharAt(sb.length() - 1);\n        return sb.toString();\n    }\n\n    boolean isPrice(String s) {\n        return s.startsWith(\"$\") && s.substring(1).matches(\"\\\\d+\");\n    }\n\n    String calc(double num, double discount) {\n        double ans = num - (double) ((double) num * discount / 100.00);\n        return \"$\" + String.format(\"%.2f\", ans);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string discountPrices(string sentence, int discount) {\n        \n\t\t// doit is a function\n        auto doit = [&](string word) {\n\t\t\n            int n(size(word));\n            if (word[0] != '$' or n == 1)   return word;\n            \n            long long price = 0;\n            for (int i=1; i<n; i++) {\n                if (!isdigit(word[i]))  return word;\n                price = price*10 + (word[i]-'0');\n            }\n            \n\t\t\tstringstream ss2;\n            double discountPercentage = (100 - discount) / 100.0;\n            ss2 << fixed << setprecision(2) << (discountPercentage * price);\n            return \"$\" + ss2.str();\n        };\n        \n        string word, res;\n        stringstream ss(sentence);\n        \n        while (ss >> word) {\n            res += doit(word)+\" \";\n        }\n        \n        res.pop_back();\n        return res;\n    }\n};"
    },
    {
        "title": "Cherry Pickup",
        "algo_input": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.\n\n\n\t0 means the cell is empty, so you can pass through,\n\t1 means the cell contains a cherry that you can pick up and pass through, or\n\t-1 means the cell contains a thorn that blocks your way.\n\n\nReturn the maximum number of cherries you can collect by following the rules below:\n\n\n\tStarting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).\n\tAfter reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.\n\tWhen passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.\n\tIf there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.\n\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput: 5\nExplanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.\n\n\nExample 2:\n\nInput: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 &lt;= n &lt;= 50\n\tgrid[i][j] is -1, 0, or 1.\n\tgrid[0][0] != -1\n\tgrid[n - 1][n - 1] != -1\n\n",
        "solution_py": "class Solution:\n    def cherryPickup(self, grid):\n        n = len(grid)\n        dp = [[-1] * (n + 1) for _ in range(n + 1)]\n        dp[1][1] = grid[0][0]\n        for m in range(1, (n << 1) - 1):\n            for i in range(min(m, n - 1), max(-1, m - n), -1):\n                for p in range(i, max(-1, m - n), -1):\n                    j, q = m - i, m - p\n                    if grid[i][j] == -1 or grid[p][q] == -1:\n                        dp[i + 1][p + 1] = -1\n                    else:\n                        dp[i + 1][p + 1] = max(dp[i + 1][p + 1], dp[i][p + 1], dp[i + 1][p], dp[i][p])\n                        if dp[i + 1][p + 1] != -1: dp[i + 1][p + 1] += grid[i][j] + (grid[p][q] if i != p else 0)\n        return max(0, dp[-1][-1])",
        "solution_js": "var cherryPickup = function(grid) {\n    let result = 0, N = grid.length, cache = {}, cherries;\n    \n    const solve = (x1, y1, x2, y2) => {\n        if(x1 === N -1 && y1 === N-1) \n            return grid[x1][y1] !== -1 ? grid[x1][y1] : -Infinity;\n        if(x1 > N -1 || y1 > N-1 || x2 > N-1 || y2 > N-1 || grid[x1][y1] === -1 ||grid[x2][y2] === -1) \n            return -Infinity;\n        \n        let lookup_key = `${x1}:${y1}:${x2}:${y2}`;\n        if(cache[lookup_key]) return cache[lookup_key];\n        \n        if(x1 === x2 && y1 === y2) \n            cherries = grid[x1][y1];\n        else\n            cherries = grid[x1][y1] + grid[x2][y2];\n        \n        result = cherries + Math.max(solve(x1 + 1, y1, x2 + 1, y2),\n                solve(x1, y1 + 1, x2, y2 + 1),\n                solve(x1 + 1, y1, x2, y2 + 1),\n                solve(x1, y1 + 1, x2 + 1, y2));\n        \n        cache[lookup_key] = result;\n        return result;\n    };\n    \n    result = solve(0, 0, 0, 0);\n    return result > 0 ? result : 0;\n};",
        "solution_java": "class Solution {\n    public int cherryPickup(int[][] grid) {\n        int m = grid.length, n = grid[0].length;\n        //For O(N^3) Dp sapce solution\n        dp2  = new Integer[m][n][m];\n        int ans=solve2(0,0,0,grid,0,m,n);\n        if(ans==Integer.MIN_VALUE) return 0;\n        return ans;\n    }\n   \n    private Integer[][][] dp2;\n    private int solve2(int x1, int y1, int x2, int[][] g, int cpsf, int m, int n){\n        int y2 = x1+y1+-x2;\n        if(x1>=m||x2>=m||y1>=n||y2>=n||g[x1][y1]==-1||g[x2][y2]==-1) return Integer.MIN_VALUE;\n        if(x1==m-1&&y1==n-1) return g[x1][y1];\n        //If both p1 and p2 reach (m-1,n-1)\n        if(dp2[x1][y1][x2]!=null) return dp2[x1][y1][x2];\n        int cherries=0;\n        //If both p1 and p2 are at same position then we need to add the cherry only once.\n        if(x1==x2&&y1==y2){\n            cherries+=g[x1][y1];\n        }\n        //If p1 and p2 are at different positions then repective cherries can be added.\n        else{\n            cherries+=g[x1][y1]+g[x2][y2];\n        }\n        //4 possibilites for p1 and p2 from each point\n        int dd=solve2(x1+1,y1,x2+1,g,cpsf+cherries,m,n); //both moves down\n        int dr=solve2(x1+1,y1,x2,g,cpsf+cherries,m,n);   //p1 moves down and p2 moves right\n        int rr=solve2(x1,y1+1,x2,g,cpsf+cherries,m,n);  //both moves right \n        int rd=solve2(x1,y1+1,x2+1,g,cpsf+cherries,m,n); //p1 moves right and p2 moves down\n        \n        //We take maximum of 4 possiblities\n        int max=Math.max(Math.max(dd,dr), Math.max(rr,rd));\n        if(max==Integer.MIN_VALUE) return dp2[x1][y1][x2]=max;\n        return dp2[x1][y1][x2]=cherries+=max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    \n    int solve(int r1,int c1,int r2,vector<vector<int>>& grid, vector<vector<vector<int>>> &dp)\n    {\n        //Calculating c2 : \n        /*\n        (r1 + c1) = (r2 + c2)\n        c2 = (r1 + c1) - r2\n        */\n        int c2 = (r1+c1)-r2 ; \n        \n        //Base condition\nif(r1 >= grid.size() || r2 >= grid.size() || c1 >= grid[0].size() || c2 >= grid[0].size() ||                  grid[r1][c1] == -1 || grid[r2][c2] == -1)\n    {\n        return INT_MIN;\n    }\n        if(r1 == grid.size()-1 && c1 == grid[0].size()-1)\n        {   \n            return grid[r1][c1] ;\n        }\n        \n        if(dp[r1][c1][r2] != -1)\n        {\n            return dp[r1][c1][r2];\n        }\n        int ch = 0;\n        if(r1 == r2 && c1 == c2)\n        {\n            ch += grid[r1][c1];     \n            //if both players are at the same place than collect cherry only one time.\n        }\n        else\n        {\n            ch += grid[r1][c1] + grid[r2][c2];\n        }\n        cout<<ch<<\"\\n\";\n        \n        //Trying all the possible paths for both the players\n        \n        int hh = solve(r1, c1+1, r2, grid, dp);\n        int vh = solve(r1+1, c1, r2, grid, dp);\n        int vv = solve(r1+1, c1, r2+1, grid, dp);\n        int hv = solve(r1, c1+1, r2+1, grid, dp);\n        \n        //collecting maximum cherries from possible paths\n        ch += max(max(hh, vh),max(vv, hv)) ; \n        \n        dp[r1][c1][r2] = ch;\n        \n        return ch;    \n    }\n\n    \n    int cherryPickup(vector<vector<int>>& grid) \n    {\n        \n        int n = grid.size();\n        \n        vector<vector<vector<int>>>dp(n, vector<vector<int>>(n, vector<int>(n,-1)));\n        \n        int ans = solve(0,0,0,grid,dp) ;\n        \n        if(ans == INT_MIN || ans <0)\n        {\n            return 0;\n        }\n        \n        return ans;       \n        \n    }\n};"
    },
    {
        "title": "Most Visited Sector in  a Circular Track",
        "algo_input": "Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]\n\nReturn an array of the most visited sectors sorted in ascending order.\n\nNotice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).\n\n&nbsp;\nExample 1:\n\nInput: n = 4, rounds = [1,3,1,2]\nOutput: [1,2]\nExplanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --&gt; 2 --&gt; 3 (end of round 1) --&gt; 4 --&gt; 1 (end of round 2) --&gt; 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\n\nExample 2:\n\nInput: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput: [2]\n\n\nExample 3:\n\nInput: n = 7, rounds = [1,3,5,7]\nOutput: [1,2,3,4,5,6,7]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 100\n\t1 &lt;= m &lt;= 100\n\trounds.length == m + 1\n\t1 &lt;= rounds[i] &lt;= n\n\trounds[i] != rounds[i + 1] for 0 &lt;= i &lt; m\n\n",
        "solution_py": "class Solution:\n    def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n        hash_map = {}\n        for i in range(0 , len(rounds)-1):\n            if i == 0:\n                start = rounds[i]\n            elif rounds[i] == n:\n                start = 1\n            else:\n                start = rounds[i] + 1\n            end = rounds[i+1]\n            if start <= end:\n                for i in range(start , end + 1):\n                    if i in hash_map:\n                        hash_map[i] += 1\n                    else:\n                        hash_map[i] = 1\n            else:\n                for i in range(start , n + 1):\n                    if i in hash_map:\n                        hash_map[i] += 1\n                    else:\n                        hash_map[i] = 1\n                for i in range(1 , end + 1):\n                    if i in hash_map:\n                        hash_map[i] += 1\n                    else:\n                        hash_map[i] = 1\n        k = list(hash_map.keys())\n        v = list(hash_map.values())\n        ans = []\n        m = -1\n        i = 0\n        j = 0\n        while i < len(k) and j < len(v):\n            if len(ans) == 0:\n                ans.append(k[i])\n                m = v[j]\n            elif m < v[j]:\n                ans = []\n                ans.append(k[i])\n                m = v[j]\n            elif m == v[j]:\n                ans.append(k[i])\n            i += 1\n            j += 1\n        ans = sorted(ans)\n        return ans",
        "solution_js": "var mostVisited = function(n, rounds) {\n    const first = rounds[0];\n    const last = rounds[rounds.length - 1];\n   \n    const result = [];\n   \n    if (first <= last) {\n        for (let i = last; i >= first; i--) result.unshift(i)\n    } else {\n        for (let i = 1; i <= last; i++) result.push(i);\n        for (let i = first; i <= n; i++) result.push(i);\n    }\n   \n    return result;\n};",
        "solution_java": "class Solution {\n    public List<Integer> mostVisited(int n, int[] rounds) {\n        int[]psum=new int[n+2];\n        psum[rounds[0]]+=1;\n        psum[rounds[1]+1]-=1;\n        if(rounds[0]>rounds[1])\n            psum[1]+=1;\n        for(int i=2;i<rounds.length;i++){\n            psum[rounds[i-1]+1]+=1;\n            psum[rounds[i]+1]-=1;\n            if(rounds[i-1]>rounds[i])\n                psum[1]+=1;\n        }\n        int max_=0;\n        for(int i=1;i<=n;i++){\n            psum[i]+=psum[i-1];\n            if(psum[i]>max_)\n                max_=psum[i];\n        }\n        List<Integer>ans=new ArrayList<>();\n        for(int i=1;i<=n;i++){\n            if(psum[i]==max_)\n                ans.add(i);\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> mostVisited(int n, vector<int>& rounds) {\n        vector <int> ans;\n        int size = rounds.size();\n        \n        if(rounds[0] <= rounds[size-1]) {\n            for(int i=rounds[0]; i<= rounds[size-1]; i++) {\n                ans.push_back(i);\n            }\n            return ans;\n        }\n        else {\n            for(int i=1; i<= rounds[size-1]; i++) {\n                ans.push_back(i);\n            }   \n            \n            for(int i=rounds[0]; i<=n; i++) {\n                ans.push_back(i);\n            }\n        }\n        \n        return ans;\n    }\n};"
    },
    {
        "title": "Longest Repeating Character Replacement",
        "algo_input": "You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.\n\nReturn the length of the longest substring containing the same letter you can get after performing the above operations.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ABAB\", k = 2\nOutput: 4\nExplanation: Replace the two 'A's with two 'B's or vice versa.\n\n\nExample 2:\n\nInput: s = \"AABABBA\", k = 1\nOutput: 4\nExplanation: Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of only uppercase English letters.\n\t0 &lt;= k &lt;= s.length\n\n",
        "solution_py": "class Solution:\n    def characterReplacement(self, s: str, k: int) -> int:\n        # Initialize variables\n        window_start = 0\n        max_length = 0\n        max_count = 0\n        char_count = {}\n\n        # Traverse the string s\n        for window_end in range(len(s)):\n            # Increment the count of the current character\n            char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1\n            # Update the maximum count seen so far\n            max_count = max(max_count, char_count[s[window_end]])\n            \n            # Shrink the window if required\n            if window_end - window_start + 1 > max_count + k:\n                char_count[s[window_start]] -= 1\n                window_start += 1\n            \n            # Update the maximum length of the substring with repeating characters seen so far\n            max_length = max(max_length, window_end - window_start + 1)\n        \n        return max_length",
        "solution_js": "// O(n) time | O(26) -> O(1) space - only uppercase English letters\nvar characterReplacement = function(s, k) {\n    const sLen = s.length, \n          charCount = {};\n    if (k >= sLen) return sLen;\n    let maxLen = 0,\n        windowStart = 0,\n        maxRepeatChar = 0;\n    for (let windowEnd = 0; windowEnd < sLen; windowEnd++) {\n        // increment charCount\n        charCount[s[windowEnd]] ? charCount[s[windowEnd]]++ : charCount[s[windowEnd]] = 1;\n        // calc max repeating char\n        maxRepeatChar = Math.max(maxRepeatChar, charCount[s[windowEnd]]);\n        // calc number of char that is not (or has fewer chars) repeating in window\n        const remainingChar = windowEnd - windowStart + 1 - maxRepeatChar;\n        // slide window by incrementing start of window\n        if (remainingChar > k) {\n            // decrement charCount\n            charCount[s[windowStart]]--;\n            windowStart++;\n        }\n        // calc maxLen\n        maxLen = Math.max(maxLen, windowEnd - windowStart + 1);\n    }\n    return maxLen;\n};",
        "solution_java": "class Solution {\n    public int characterReplacement(String s, int k) {\n        HashMap<Character,Integer> map=new HashMap<>();\n            int i=-1;\n            int j=-1;\n            int ans=0;\n            while(true){\n            boolean f1=false;\n            boolean f2=false;\n            while(i<s.length()-1){\n                //acquire\n               i++;\n               f1=true;\n               char ch=s.charAt(i);\n               map.put(ch,map.getOrDefault(ch,0)+1);\n               int count=0;\n               for(char key:map.keySet()){\n                   count=Math.max(count,map.get(key));\n               }\n               int replace=(i-j) - count;\n               if(replace<=k) {\n                   ans=Math.max(i-j,ans);\n               } \n               else break;\n                   \n             }\n                \n             while(j<i){\n               //release   \n               f2=true;  \n               j++;\n               char ch=s.charAt(j);\n               isremove(map,ch);\n               int count=0;\n               for(char key:map.keySet()){\n                   count=Math.max(count,map.get(key));\n               }\n               int replace=(i-j) - count;  \n               if(replace<=k){\n                   ans=Math.max(i-j,ans);\n                   break;\n               }\n               else continue;  \n             }   \n             if(f1==false && f2==false) break;   \n                \n         }\n        \n        return ans;\n    }\n    \n    \n    static void isremove(HashMap<Character,Integer> map,char ch){\n        if(map.get(ch)==1) map.remove(ch);\n        else map.put(ch,map.get(ch)-1);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int characterReplacement(string s, int k) {\n        int n = s.length();\n        if(n == k) return n;\n        if(n == 1) return 1;\n\n        int res = 0;\n        int maxCnt = 0;\n        \n        unordered_map<char,int> mp;\n        \n        for(int l = 0, r = 0; r < n; r++)\n        {\n            mp[s[r]]++;\n            maxCnt = max(maxCnt,mp[s[r]]);\n            while(r - l + 1 - maxCnt > k){\n                mp[s[l]]--;\n                l++;\n            }\n            res = max(r - l + 1, res);\n        }\n        return res;\n    }\n};"
    },
    {
        "title": "Find All Lonely Numbers in the Array",
        "algo_input": "You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.\n\nReturn all lonely numbers in nums. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums = [10,6,5,8]\nOutput: [10,8]\nExplanation: \n- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.\n\n\nExample 2:\n\nInput: nums = [1,3,5,3]\nOutput: [1,5]\nExplanation: \n- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 106\n\n",
        "solution_py": "class Solution:\n    def findLonely(self, nums: List[int]) -> List[int]:\n        m = Counter(nums)\n        return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]",
        "solution_js": "var findLonely = function(nums) {\n    let countMap = new Map();\n    let result = [];\n    for (let num of nums) {\n        countMap.set(num, (countMap.get(num) || 0) + 1);\n    }\n    for (let num of nums) {\n        if (!countMap.has(num - 1) && !countMap.has(num + 1) && countMap.get(num) === 1) {\n\n            result.push(num);\n        }\n\n    }\n    return result;\n};",
        "solution_java": "class Solution {\n    public List<Integer> findLonely(int[] nums) {\n        Arrays.sort(nums);\n        ArrayList<Integer> list = new ArrayList<>();\n        for (int i = 1; i < nums.length - 1; i++) {\n            if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) {\n                list.add(nums[i]);\n            }\n        }\n        if (nums.length == 1) {\n            list.add(nums[0]);\n        }\n        if (nums.length > 1) {\n            if (nums[0] + 1 < nums[1]) {\n                list.add(nums[0]);\n            }\n            if (nums[nums.length - 2] + 1 < nums[nums.length - 1]) {\n                list.add(nums[nums.length - 1]);\n            }\n        }\n        return list;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> findLonely(vector<int>& nums) {\n        int n=nums.size();\n        unordered_map<int,int> ump;\n        vector<int> sol;\n        for(int i=0;i<n;i++)\n        {\n            ump[nums[i]]++;\n        }\n        for(auto a: ump)\n        {\n            if(a.second==1 and !ump.count(a.first+1) and !ump .count(a.first-1))\n                sol.push_back(a.first);\n        }\n\n        return sol;\n    }\n};"
    },
    {
        "title": "Number of Unique Good Subsequences",
        "algo_input": "You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\").\n\nFind the number of unique good subsequences of binary.\n\n\n\tFor example, if binary = \"001\", then all the good subsequences are [\"0\", \"0\", \"1\"], so the unique good subsequences are \"0\" and \"1\". Note that subsequences \"00\", \"01\", and \"001\" are not good because they have leading zeros.\n\n\nReturn the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\n&nbsp;\nExample 1:\n\nInput: binary = \"001\"\nOutput: 2\nExplanation: The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".\n\n\nExample 2:\n\nInput: binary = \"11\"\nOutput: 2\nExplanation: The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".\n\nExample 3:\n\nInput: binary = \"101\"\nOutput: 5\nExplanation: The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= binary.length &lt;= 105\n\tbinary consists of only '0's and '1's.\n\n",
        "solution_py": "class Solution:\n    def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n        \n        \n        # zero_as_last: the count of S0, good sequence ending in 0\n        # one_as_last : the count of S1: good sequence ending in 1\n        # zero_exist:   existence flag of 0 in given binary\n        \n        dp = {\"zero_as_last\": 0, \"one_as_last\": 0, \"zero_exist\": 0}\n        \n        for bit in map(int, binary):\n            \n            if bit:\n                # current good = ( S0 concate with 1 ) + ( S1 concate with 1 ) + 1 alone\n                # + \"1\" is allowed because leading 1 is valid by description\n                dp[\"one_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"] + 1\n            \n            else:\n                # current good = ( S0 concate with 0 ) + ( S1 concate with 0 ) \n                # + \"0\" is NOT allowed because leading 0 is invalid by description\n                dp[\"zero_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"]\n            \n            # check the existence of 0\n            dp[\"zero_exist\"] |= (1-bit)\n        \n        \n        return sum( dp.values() ) % ( 10**9 + 7 )",
        "solution_js": "const MOD = 1000000007;\n\nvar numberOfUniqueGoodSubsequences = function(binary) {\n    let endsZero = 0;\n    let endsOne = 0;\n    let hasZero = 0;\n    for (let i = 0; i < binary.length; i++) {\n        if (binary[i] === '1') {\n            endsOne = (endsZero + endsOne + 1) % MOD;\n        } else {\n            endsZero = (endsZero + endsOne) % MOD;\n            hasZero = 1;\n        }\n    }\n    return (endsZero + endsOne + hasZero) % MOD;\n};",
        "solution_java": "class Solution {\n    public int numberOfUniqueGoodSubsequences(String binary) {\n        int initialZeroCount= 0;\n        while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++;\n        if(initialZeroCount == binary.length()) return 1;\n        long[] dp = new long[binary.length()];\n        dp[initialZeroCount] = 1;\n        int lastOne = 0, lastZero = 0;\n        long mod = (long) Math.pow(10, 9)+7;\n        for(int i=initialZeroCount+1;i<binary.length();i++){\n            int j = binary.charAt(i) == '1' ? lastOne : lastZero;\n            long dup = j > 0 ? dp[j-1] : 0;\n            dp[i] = 2 * dp[i-1] - dup;\n            if(dp[i] < 0) dp[i] += mod;\n            dp[i] %= mod;\n            if(binary.charAt(i) == '0') lastZero = i;\n            else lastOne = i;\n        }\n        \n        int hasZero = 0;\n        if(binary.contains(\"0\")) hasZero = 1;\n        \n        \n        return (int) (dp[binary.length()-1] + hasZero);\n    }\n}",
        "solution_c": "class Solution {\n    int MOD = 1000000007;\npublic:\n    int numberOfUniqueGoodSubsequences(string binary) {\n        int zero = 0;\n        long long ones = 0;\n        long long zeros = 0;\n        \n        for (int i = binary.size() - 1; i >= 0; --i) {\n            if (binary[i] == '1') {\n                ones = (ones + zeros + 1) % MOD;\n            } else {\n                zero = 1;\n                zeros = (ones + zeros + 1) % MOD;\n            }\n        }\n        return (ones + zero) % MOD;\n    }\n};"
    },
    {
        "title": "Largest Palindrome Product",
        "algo_input": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987\n\n\nExample 2:\n\nInput: n = 1\nOutput: 9\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 8\n\n",
        "solution_py": "class Solution:\n    def largestPalindrome(self, n: int) -> int:\n        return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n]\n\n        \n    def isPalindrome(x):\n        return str(x) == str(x)[::-1]\n\n    def solve(n):\n        best = 0\n        for i in range(10**n-1, 0, -1):\n            for j in range(max(i, (best-1)//i+1), 10**n):\n                if isPalindrome(i*j):\n                    #print(i, j, i*j)\n                    best = i*j\n        return best",
        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar largestPalindrome = function(n) {\n    if (n === 1) return 9;\n    let hi = BigInt(Math.pow(10, n) - 1);\n    let num = hi;\n    while(num > 0) {\n        num -= 1n;\n        const palindrome = BigInt(String(num) + String(num).split('').reverse().join(''));\n        for (let i = hi; i >= 2n; i -= 2n) {\n            const j = palindrome / i; \n            if (j > hi) break;\n            if (palindrome % i === 0n) {\n                return String(palindrome % 1337n);\n            };\n        }\n    }\n};",
        "solution_java": "class Solution {\n    public int largestPalindrome(int n) {\n        if(n == 1 ){\n            return 9;\n        }\n       if(n == 2){\n           return 987;\n       }\n        if(n == 3){\n            return 123;\n        }\n        if(n == 4){\n            return 597;\n        }\n        if(n == 5){\n            return  677;\n        }\n        if(n == 6){\n            return 1218;\n        }\n        if(n == 7){\n            return 877;\n        }\n        return 475;\n        \n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int largestPalindrome(int n) {\n        if(n==1)\n        {\n            return 9;\n        }\n        int hi=pow(10,n)-1;\n        int lo=pow(10,n-1);\n        int kk=1337;\n        for(int i=hi;i>=lo;i--)\n        {\n            string s=to_string(i);\n            string k=s;\n            reverse(k.begin(),k.end());\n            s+=k;\n            long long int ll=stol(s);\n            for(int j=hi;j>=sqrtl(ll);j--)\n            {\n                if(ll%j==0)\n                {\n                    return ll%kk;\n                }\n            }\n            \n        }\n        return 0;\n    }\n};"
    },
    {
        "title": "Angle Between Hands of a Clock",
        "algo_input": "Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.\n\nAnswers within 10-5 of the actual value will be accepted as correct.\n\n&nbsp;\nExample 1:\n\nInput: hour = 12, minutes = 30\nOutput: 165\n\n\nExample 2:\n\nInput: hour = 3, minutes = 30\nOutput: 75\n\n\nExample 3:\n\nInput: hour = 3, minutes = 15\nOutput: 7.5\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= hour &lt;= 12\n\t0 &lt;= minutes &lt;= 59\n\n",
        "solution_py": "class Solution:\n    def angleClock(self, hour: int, minutes: int) -> float:\n        \n        x = abs(minutes * 6 -(hour * 30 + minutes/2))\n        return min(360-x , x)",
        "solution_js": "var angleClock = function(hour, minutes) {\n    const angle = Math.abs((hour * 30) - 5.5 * minutes)\n    return angle > 180 ? 360 - angle : angle\n};",
        "solution_java": "class Solution {\n    public double angleClock(int hour, int minutes) {\n        // Position of hour hand in a circle of 0 - 59\n        double hrPos = 5 * (hour % 12);\n\n        // Adjust hour hand position according to minute hand\n        hrPos += (5 * minutes/60.0);\n\n        double units = Math.abs(minutes - hrPos);\n\n        // Take the min of distance between minute & hour hand and hour & minute hand\n        return Math.min(units, 60-units) * 6;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double angleClock(int hour, int minutes) {\n\n        double hourAngle = 30*(double(hour) + double(minutes/60.0));\n\n        double minuteAngle = 6 * (double)minutes;\n\n        return 180 - abs(180 - abs(minuteAngle - hourAngle));\n\n    }\n};"
    },
    {
        "title": "Decode Ways",
        "algo_input": "A message containing letters from A-Z can be encoded into numbers using the following mapping:\n\n'A' -&gt; \"1\"\n'B' -&gt; \"2\"\n...\n'Z' -&gt; \"26\"\n\n\nTo decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n\n\n\t\"AAJF\" with the grouping (1 1 10 6)\n\t\"KJF\" with the grouping (11 10 6)\n\n\nNote that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\n\nGiven a string s containing only digits, return the number of ways to decode it.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: s = \"12\"\nOutput: 2\nExplanation: \"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).\n\n\nExample 2:\n\nInput: s = \"226\"\nOutput: 3\nExplanation: \"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).\n\n\nExample 3:\n\nInput: s = \"06\"\nOutput: 0\nExplanation: \"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts contains only digits and may contain leading zero(s).\n\n",
        "solution_py": "class Solution:\n    def numDecodings(self, s: str) -> int:\n        if s[0] == '0' or '00' in s:\n            return 0\n        l = len(s)\n        if l == 1:\n            return 1\n        elif l == 2:\n            if s[1] == '0':\n                if s[0] == '1' or s[0] == '2':\n                    return 1\n                else:\n                    return 0\n            else:\n                if int(s) <= 26:\n                    return 2\n                else:\n                    return 1\n        dp = [1]\n        if s[1] == '0':\n            if s[0] == '1' or s[0] == '2':\n                dp.append(1)\n            else:\n                return 0\n        else:\n            if int(s[:2]) <= 26:\n                dp.append(2)\n            else:\n                dp.append(1)\n        for i in range(2, l):\n            num = 0\n            if s[i] == '0':\n                if s[i-1] != '1' and s[i-1] != '2':\n                    return 0\n                else:\n                    num = dp[i-2]\n            elif s[i-1] == '1' or (s[i-1] == '2' and int(f'{s[i-1]}{s[i]}') <= 26):\n                num = dp[i-1]+dp[i-2]\n            else:\n                num = dp[i-1]\n            dp.append(num)\n        return dp[l-1]",
        "solution_js": "var numDecodings = function(s) {\n    let dp = Array(s.length).fill(0); // dp[i] means, the total ways of decode for substring up to i\n    dp[0] = (s[0] !== '0') ? 1 : 0;\n    \n    for(let i = 1; i < s.length; i++){\n\t//case1\n        if(s[i] !== '0'){\n            dp[i] = dp[i - 1];\n        }\n   //case2\n        if(s[i-1] === '1' || (s[i-1] === '2' && parseInt(s[i]) <= 6)){\n            dp[i] += dp[i - 2] ?? 1;\n        }\n    }\n    \n    return dp[s.length - 1];\n};",
        "solution_java": "class Solution {\n    public int numDecodings(String s) {\n        int[]dp = new int[s.length() + 1];\n        dp[0] = 1;\n        dp[1] = s.charAt(0) == '0' ? 0 : 1;\n        \n        for(int i = 2;i<=s.length();i++) {\n            int oneDigit = Integer.valueOf(s.substring(i-1,i));\n            int twoDigit = Integer.valueOf(s.substring(i-2,i));\n            \n            if(oneDigit >= 1) {\n                dp[i] += dp[i - 1];\n            }\n            if(twoDigit >= 10 && twoDigit <= 26) {\n                dp[i] += dp[i - 2];\n            }\n        }\n        return dp[s.length()];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numDecodings(string s) {\n        \n        if(s[0] == 0)\n            return 0;\n        int n  = s.length();\n       vector<int> dp(n+1, 0);\n        \n        //Storing DP[n-1]\n        if(s[n-1] == '0' )\n            dp[n-1] = 0;\n        else \n            dp[n-1] = 1;\n        \n        if(n == 1)\n            return dp[0];\n        \n        //Storing DP[n-2]\n            if(s[n-2] == '0')\n                dp[n-2] = 0;\n            else\n            {\n                string temp ;\n                temp.push_back(s[n-2]);\n                temp.push_back(s[n-1]);\n                \n                int x = stoi(temp);\n                if(x<27)\n                    dp[n-2] = 1;\n                dp[n-2] += dp[n-1];\n            }\n        \n        \n        for(int i = n-3; i>=0 ; i--)\n        {\n            if(s[i] == '0')\n                continue;\n            \n            string temp ;\n                temp.push_back(s[i]);\n                temp.push_back(s[i+1]);\n                \n                int x = stoi(temp);\n                if(x<27)\n                    dp[i] = dp[i+2];\n                dp[i]+=dp[i+1];\n        }\n        \n        return dp[0];\n    }\n};"
    },
    {
        "title": "Check if Binary String Has at Most One Segment of Ones",
        "algo_input": "Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"1001\"\nOutput: false\nExplanation: The ones do not form a contiguous segment.\n\n\nExample 2:\n\nInput: s = \"110\"\nOutput: true\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts[i]​​​​ is either '0' or '1'.\n\ts[0] is&nbsp;'1'.\n\n",
        "solution_py": "class Solution:\n    def checkOnesSegment(self, s: str) -> bool:\n        return \"01\" not in s",
        "solution_js": "var checkOnesSegment = function(s) {\n   return s.indexOf(\"01\") == -1\n};",
        "solution_java": "class Solution {\n    public boolean checkOnesSegment(String s) {\n        return !s.contains(\"01\");\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tbool checkOnesSegment(string s) {\n\t\tfor(int i = 1; i < s.size(); i++){\n\t\t\tif(s[i - 1] == '0' and s[i] == '1'){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};"
    },
    {
        "title": "Number of Subarrays with Bounded Maximum",
        "algo_input": "Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].\n\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,1,4,3], left = 2, right = 3\nOutput: 3\nExplanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\n\n\nExample 2:\n\nInput: nums = [2,9,2,5,6], left = 2, right = 8\nOutput: 7\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 109\n\t0 &lt;= left &lt;= right &lt;= 109\n\n",
        "solution_py": "class Solution:\n    def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n        n = len(nums)\n        stack = []\n        next_greater = [n] * n\n        prev_greater = [-1] * n\n        for i in range(n):\n            while len(stack) > 0 and nums[i] > nums[stack[-1]]:\n                curr = stack.pop()\n                next_greater[curr] = i\n            if len(stack) > 0:\n                prev_greater[i] = stack[-1]\n            stack.append(i)\n        res = 0\n        for i in range(n):\n            if left <= nums[i] <= right:\n                l = prev_greater[i]\n                r = next_greater[i]\n                res += (i - l) * (r - i)\n        return res",
        "solution_js": "  var numSubarrayBoundedMax = function(nums, left, right) {\n        // si is start index\n        // ei is end index\n    let si=0, ei=0, finalCount=0, currentCount=0;\n\n    while(ei<nums.length){ // moving ei till length of array\n        if(left<=nums[ei] && nums[ei]<=right) // considering case number falls in the range\n            {\n                currentCount= ei-si+1;  // to get the subarrays b/w start index and end index\n                finalCount+=currentCount; // add current count of subarrays to final count  which we will return at end\n            }\n        if(nums[ei]<left){\n              finalCount+=currentCount;  // in this case when num is smaller than left range we won't calculate subarrays but just include the current count in final count.\n        }\n         if(nums[ei]>right){\n              si=ei+1; // in this case when num is greater than right range we need to move our start index to end+1 because there won't be any subarrays that will fall in range.\n             currentCount=0; // we will set current count 0 in such case.\n        }\n\n        ei++;\n     }\n    return finalCount;\n\n    };",
        "solution_java": "class Solution {\n    public int numSubarrayBoundedMax(int[] nums, int left, int right) {\n        int res = 0;\n\n        int s = -1;\n        int e = -1;\n\n        for(int i=0;i<nums.length;i++){\n\n            if(nums[i] >= left && nums[i] <= right){\n                e = i;\n            }else if(nums[i] > right){\n                e = s = i;\n            }\n\n            res += (e - s);\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {\n        int ans = 0; // store ans\n        int j=-1; // starting window\n        int sub = 0; // if current element is less than left bound then count how may element before current element which is less than left and must be continues(it means any element which is greater than left bound reset the count to 0 )\n        for(int i=0;i<nums.size();i++){\n            if(nums[i]>right){\n                j = i;\n                sub = 0;\n            }\n            else if(nums[i]<left){\n                sub++;\n            }\n            else sub = 0;\n            ans = ans + i - j - sub;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Subrectangle Queries",
        "algo_input": "Implement the class SubrectangleQueries&nbsp;which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:\n\n1.&nbsp;updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)\n\n\n\tUpdates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).\n\n\n2.&nbsp;getValue(int row, int col)\n\n\n\tReturns the current value of the coordinate (row,col) from&nbsp;the rectangle.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]\nOutput\n[null,1,null,5,5,null,10,5]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);  \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5   5   5\n// 5   5   5\n// 5   5   5\n// 10  10  10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5\n\n\nExample 2:\n\nInput\n[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]\nOutput\n[null,1,null,100,100,null,20]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20\n\n\n&nbsp;\nConstraints:\n\n\n\tThere will be at most 500&nbsp;operations considering both methods:&nbsp;updateSubrectangle and getValue.\n\t1 &lt;= rows, cols &lt;= 100\n\trows ==&nbsp;rectangle.length\n\tcols == rectangle[i].length\n\t0 &lt;= row1 &lt;= row2 &lt; rows\n\t0 &lt;= col1 &lt;= col2 &lt; cols\n\t1 &lt;= newValue, rectangle[i][j] &lt;= 10^9\n\t0 &lt;= row &lt; rows\n\t0 &lt;= col &lt; cols\n\n",
        "solution_py": "class SubrectangleQueries:\n\n    def __init__(self, rectangle: List[List[int]]):\n        self.rectangle = rectangle\n\n    def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n        for i in range(row1,row2+1):\n            for j in range(col1,col2+1):\n                self.rectangle[i][j] = newValue\n                \n    def getValue(self, row: int, col: int) -> int:\n        return self.rectangle[row][col]",
        "solution_js": "/**\n * @param {number[][]} rectangle\n */\nvar SubrectangleQueries = function(rectangle) {\n    this.rectangle = rectangle;\n};\n\n/** \n * @param {number} row1 \n * @param {number} col1 \n * @param {number} row2 \n * @param {number} col2 \n * @param {number} newValue\n * @return {void}\n */\nSubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) {\n    for(let i=row1; i<=row2; i++){\n            for(let j=col1; j<=col2; j++){\n                this.rectangle[i][j] = newValue;\n            }\n        }\n};\n\n/** \n * @param {number} row \n * @param {number} col\n * @return {number}\n */\nSubrectangleQueries.prototype.getValue = function(row, col) {\n    return this.rectangle[row][col];\n};\n\n/** \n * Your SubrectangleQueries object will be instantiated and called as such:\n * var obj = new SubrectangleQueries(rectangle)\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue)\n * var param_2 = obj.getValue(row,col)\n */",
        "solution_java": "class SubrectangleQueries {\n    int[][] rectangle;\n    public SubrectangleQueries(int[][] rectangle) {\n        this.rectangle = rectangle;\n    }\n\n    public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n        for(int i=row1;i<=row2;i++){\n            for(int j=col1;j<=col2;j++){\n                rectangle[i][j] = newValue;\n            }\n        }\n    }\n\n    public int getValue(int row, int col) {\n        return this.rectangle[row][col];\n    }\n}\n\n/**\n * Your SubrectangleQueries object will be instantiated and called as such:\n * SubrectangleQueries obj = new SubrectangleQueries(rectangle);\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue);\n * int param_2 = obj.getValue(row,col);\n */",
        "solution_c": "class SubrectangleQueries {\npublic:\n    vector<vector<int>> rect;\n    SubrectangleQueries(vector<vector<int>>& rectangle) {\n        rect= rectangle;\n    }\n    \n    void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n        for(int i=row1; i<=row2; ++i){\n            for(int j=col1; j<=col2; ++j){\n                rect[i][j]= newValue;\n            }\n        }\n    }\n    \n    int getValue(int row, int col) {\n        return rect[row][col];\n    }\n};"
    },
    {
        "title": "Minimum Operations to Halve Array Sum",
        "algo_input": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)\n\nReturn the minimum number of operations to reduce the sum of nums by at least half.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,19,8,1]\nOutput: 3\nExplanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 &gt;= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\nExample 2:\n\nInput: nums = [3,8,20]\nOutput: 3\nExplanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 &gt;= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 107\n\n",
        "solution_py": "class Solution:\n    def halveArray(self, nums: List[int]) -> int:\n        # Creating empty heap\n        maxHeap = []\n        heapify(maxHeap) # Creates minHeap \n        \n        totalSum = 0\n        for i in nums:\n            # Adding items to the heap using heappush\n            # for maxHeap, function by multiplying them with -1\n            heappush(maxHeap, -1*i) \n            totalSum += i\n        \n        requiredSum = totalSum / 2\n        minOps = 0\n        \n        while totalSum > requiredSum:\n            x = -1*heappop(maxHeap) # Got negative value make it positive\n            x /= 2\n            totalSum -= x\n            heappush(maxHeap, -1*x) \n            minOps += 1\n        \n        return minOps",
        "solution_js": "var halveArray = function(nums) {\n    const n = nums.length;\n    const maxHeap = new MaxPriorityQueue({ priority: x => x });\n\n    let startSum = 0;\n\n    for (const num of nums) {\n        maxHeap.enqueue(num);\n        startSum += num;\n    }\n\n    let currSum = startSum;\n\n    let numberOfOperations = 0;\n\n    while (currSum > startSum / 2) {\n        const biggestNum = maxHeap.dequeue().element;\n\n        const halfNum = biggestNum / 2;\n\n        numberOfOperations += 1;\n        currSum -= halfNum;\n\n        maxHeap.enqueue(halfNum);\n    }\n\n    return numberOfOperations;\n};",
        "solution_java": "class Solution {\n    public int halveArray(int[] nums) {\n        PriorityQueue<Double> q = new PriorityQueue<>(Collections.reverseOrder());\n        double sum=0;\n        for(int i:nums){\n            sum+=(double)i;\n            q.add((double)i);\n        }\n        int res=0;\n        double req = sum;\n        while(sum > req/2){\n            double curr = q.poll();\n            q.add(curr/2);\n            res++;\n            sum -= curr/2;\n        }\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int halveArray(vector<int>& nums) {\n\t\tpriority_queue<double> pq;\n        double totalSum = 0;\n        double requiredSum = 0;\n        for(auto x: nums){\n            totalSum += x;\n            pq.push(x);\n        }\n        \n        requiredSum = totalSum/2;\n        int minOps = 0;\n        while(totalSum > requiredSum){\n            double currtop = pq.top();\n            pq.pop();\n            currtop = currtop/2;\n            totalSum -= currtop;\n            pq.push(currtop);\n            minOps++;\n        }\n        return minOps;\n\t}\n}\n\t\t"
    },
    {
        "title": "Two Sum IV - Input is a BST",
        "algo_input": "Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.\n\n&nbsp;\nExample 1:\n\nInput: root = [5,3,6,2,4,null,7], k = 9\nOutput: true\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,7], k = 28\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-104&nbsp;&lt;= Node.val &lt;= 104\n\troot is guaranteed to be a valid binary search tree.\n\t-105&nbsp;&lt;= k &lt;= 105\n\n",
        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n        def inorder(root,l):\n            if root:\n                inorder(root.left,l)\n                l.append(root.val)\n                inorder(root.right,l)\n        l = []\n        inorder(root,l)\n        left,right=0,len(l)-1\n        while left!=right:\n            sum = l[left] + l[right]\n            if sum > k :\n                right -=1\n            elif sum <k:\n                left +=1\n            else:\n                return 1\n        return 0",
        "solution_js": "var findTarget = function(root, k) {\n\n    const set = new Set();\n\n    const search = (root, k) => {\n        if (!root) return false;\n        if (set.has(k - root.val)) return true;\n        set.add(root.val);\n        return search(root.left, k) || search(root.right, k);\n    }\n\n    return search(root,k);\n};",
        "solution_java": "class Solution {\n    Set<Integer> set = new HashSet<>();\n    public boolean findTarget(TreeNode root, int k) {\n        if(root == null){\n            return false;\n        }\n        if(set.contains(k-root.val)){\n            return true;\n        }\n        set.add(root.val);\n        return findTarget(root.left,k) || findTarget(root.right,k);\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countNodes(TreeNode *root) {\n        if (root == NULL) {\n            return 0;\n        }\n        return countNodes(root->left) + countNodes(root->right) + 1;\n    }\n\n    bool findTarget(TreeNode* root, int k) {\n        int totalCount = countNodes(root);\n        int count = 0;\n        stack<TreeNode*> inorder;\n        stack<TreeNode*> revInorder;\n\n        TreeNode* currNode = root;\n        while(currNode != NULL){\n            inorder.push(currNode); //Store all elements in left of tree\n            currNode = currNode->left;\n        }\n\n        currNode = root;\n        while(currNode != NULL){\n            revInorder.push(currNode); //Store all elements in right of tree\n            currNode = currNode->right;\n        }\n\n        while(count < totalCount-1){\n            TreeNode* inordertop = inorder.top();\n            TreeNode* revinordertop = revInorder.top();\n            if(inordertop->val + revinordertop->val == k){ // If inordertop + revinordertop is equal to k, we have found a pair, so return true\n                return true;\n            }\n            else if(inordertop->val + revinordertop->val > k){ //If they are greater than k, we have to found a value\n            //which is just smaller than revinordertop, which means we have to find predecessor of revinordertop, as\n            //we have to reduce the sum to make it equal to k\n                TreeNode* currtop = revinordertop;\n                count++;\n                revInorder.pop();\n                if(currtop->left){\n                    currtop = currtop->left;\n                    while(currtop){\n                        revInorder.push(currtop);\n                        currtop = currtop->right;\n                    }\n                }\n            }\n            else{\n            //If they are smaller than k, we have to found a value which is just larger than inordertop, which means\n            //we have to find successor of revinordertop, as we have to increase the sum to make it equal to k\n                TreeNode* currtop = inordertop;\n                count++;\n                inorder.pop();\n                if(currtop->right){\n                    currtop = currtop->right;\n                    while(currtop){\n                        inorder.push(currtop);\n                        currtop = currtop->left;\n                    }\n                }\n            }\n        }\n        return false;\n    }\n};"
    },
    {
        "title": "Excel Sheet Column Title",
        "algo_input": "Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.\n\nFor example:\n\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n\n\n&nbsp;\nExample 1:\n\nInput: columnNumber = 1\nOutput: \"A\"\n\n\nExample 2:\n\nInput: columnNumber = 28\nOutput: \"AB\"\n\n\nExample 3:\n\nInput: columnNumber = 701\nOutput: \"ZY\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= columnNumber &lt;= 231 - 1\n\n",
        "solution_py": "class Solution:\n    def convertToTitle(self, num: int) -> str:\n\t\t# We make this lookup list, having A-Z in ascending order\n        alpha = [chr(x) for x in range(ord(\"A\"), ord(\"Z\")+1)]     # range(65, 90+1) -> 91-65 = 26\n        res = \"\"\n\n        while num > 0:\n            res += alpha[(num-1)%26]     # since 0 indexed list, num-1 % 26 gives the index of ch in alpha\n            num = (num-1) // 26 \n        return res[::-1]",
        "solution_js": "/**\n * @param {number} columnNumber\n * @return {string}\n */\nvar convertToTitle = function(columnNumber) {\n    let ans = \"\";\n    while(columnNumber >0){\n        let n = (--columnNumber) % 26;\n        columnNumber = Math.floor(columnNumber/ 26);\n\n        // console.log(String.fromCharCode(65+n),)\n        ans+=String.fromCharCode(65 + n);\n\n    }\n    ans = ans.split(\"\").reverse().join(\"\")\n    return ans\n};",
        "solution_java": "class Solution {\n    public String convertToTitle(int columnNumber) {\n        String ans = \"\";\n        while(columnNumber > 0){\n            columnNumber--;\n            ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans;\n            columnNumber /= 26;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    string convertToTitle(int columnNumber) {\n        string s = \"\";\n        while(columnNumber){\n            char c = (columnNumber-1)%26+65;\n            s = c+s;\n            columnNumber = (columnNumber-1)/26;\n        }\n        return s;\n    }\n};"
    },
    {
        "title": "Number of Provinces",
        "algo_input": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.\n\nA province is a group of directly or indirectly connected cities and no other cities outside of the group.\n\nYou are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.\n\nReturn the total number of provinces.\n\n&nbsp;\nExample 1:\n\nInput: isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput: 2\n\n\nExample 2:\n\nInput: isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 200\n\tn == isConnected.length\n\tn == isConnected[i].length\n\tisConnected[i][j] is 1 or 0.\n\tisConnected[i][i] == 1\n\tisConnected[i][j] == isConnected[j][i]\n\n",
        "solution_py": "class Solution:\n    def findCircleNum(self, isConnected: List[List[int]]) -> int:\n        graph = defaultdict(list)\n        for i,x in enumerate(isConnected):\n            for j,n in enumerate(x):\n                if j!=i and n == 1:\n                    graph[i].append(j)\n            \n        visit = set()\n        \n        def dfs(node):\n            if node not in graph:\n                return \n            for neighbor in graph[node]:\n                if neighbor not in visit:\n                    visit.add(neighbor)\n                    dfs(neighbor)\n        count = 0\n        for i in range(len(isConnected)):\n            if i in visit:\n                continue\n            count+=1\n            dfs(i)\n        return count",
        "solution_js": "function DisjointSet (size) {\n    this.root = []\n    this.rank = []\n    this.size = size\n    for (let i = 0; i < size; i++) {\n        this.root.push(i)\n        this.rank.push(1)\n    }\n    this.find = function(x) {\n        if (x === this.root[x]) {\n            return x\n        }\n        this.root[x] = this.find(this.root[x])\n        return this.root[x]\n    }\n    this.union = function(x, y) {\n        const rootX = this.find(x)\n        const rootY = this.find(y)\n        if (rootX === rootY) return\n        this.size--\n        if (this.rank[rootX] > this.rank[rootY]) {\n            this.root[rootY] = this.root[rootX]\n        }\n        else if (this.rank[rootX] < this.rank[rootY]) {\n            this.root[rootX] = this.root[rootY]\n        }\n        else {\n            this.root[rootY] = this.root[rootX]\n            this.rank[rootX]++\n        }\n    }\n}\n\n/**\n * @param {number[][]} isConnected\n * @return {number}\n */\nvar findCircleNum = function(isConnected) {\n    const n = isConnected.length\n    const disjointSet = new DisjointSet(isConnected.length)\n    for (let i = 0; i < n; i++) {\n        for (let j = 0; j < n; j++) {\n            if (isConnected[i][j]) {\n                disjointSet.union(i, j)\n            }\n        }\n    }\n    return disjointSet.size\n};",
        "solution_java": "class Solution {\n    public int findCircleNum(int[][] isConnected) {\n        int size = isConnected.length;\n        boolean[] isCheck = new boolean[size+1];\n        int ans = 0;\n\n        for(int i=1; i<=size; i++){\n\n            if(!isCheck[i]){ // Doing BFS if it's false in isCheck[]\n                Queue<Integer> q = new LinkedList<>();\n                q.add(i);\n                ans++; // No. of queue = No. of Graphs\n\n                while(!q.isEmpty()){\n                    int temp = q.remove();\n                    isCheck[temp] = true;\n\n                    for(int j=0; j<size; j++){\n                        if(isConnected[temp-1][j]==1 && !isCheck[j+1])\n                            q.add(j+1);\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\nprivate:\n    void dfs(int node,vector<vector<int>> &graph,int n,vector<bool> &vis){\n\n        vis[node] = true;\n\n        for(int j = 0; j < graph[node].size(); j++){\n            if(graph[node][j] == 1 and !vis[j]){\n                dfs(j,graph,n,vis);\n            }\n        }\n\n    }\npublic:\n    int findCircleNum(vector<vector<int>>& isConnected) {\n\n        int n = isConnected.size();\n\n        vector<bool> vis(n,false);\n\n        int ans = 0;\n\n        for(int i = 0; i < n; i++){\n            if(!vis[i]){\n                ans++;\n                dfs(i,isConnected,n,vis);\n            }\n        }\n\n        return ans;\n\n    }\n};"
    },
    {
        "title": "Minimum Number of Days to Make m Bouquets",
        "algo_input": "You are given an integer array bloomDay, an integer m and an integer k.\n\nYou want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.\n\nThe garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.\n\nReturn the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.\n\n&nbsp;\nExample 1:\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput: 3\nExplanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _]   // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x]   // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x]   // we can make 3 bouquets. The answer is 3.\n\n\nExample 2:\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput: -1\nExplanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\n\n\nExample 3:\n\nInput: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput: 12\nExplanation: We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.\n\n\n&nbsp;\nConstraints:\n\n\n\tbloomDay.length == n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= bloomDay[i] &lt;= 109\n\t1 &lt;= m &lt;= 106\n\t1 &lt;= k &lt;= n\n\n",
        "solution_py": "class Solution:\n    \n    def minDays(self, listOfFlowerBloomDays: List[int], targetNumberOfBouquets: int, flowersPerBouquet: int) -> int:\n        \n        def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking):\n            \n            currentListOfAdjacentBloomedFlowers = []\n            numberOfBouquetsWeCanMakeOnThisDay = 0\n            \n            for dayThatFlowerBlooms in listOfFlowerBloomDays:\n                \n                # check if the flower has bloomed on this day \n                if dayThatFlowerBlooms <= dayThatWeAreChecking:\n                    \n                    # add to the list an adjacent bloomed flowers, I use 'x' because the description uses an 'x'\n                    currentListOfAdjacentBloomedFlowers.append('x')\n                    \n                else:\n                    # we've hit a day where we don't have a bloomed flower, so the list of adjacent bloomed flowers has to be reset\n                    # BUT FIRST figure out how many bouquets we can make with this list of adjacent bloomed flowers\n                    numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n                    \n                    # RESET list of adjacent bloomed flowers cause we're on a day where the a flower has not bloomed yet\n                    currentListOfAdjacentBloomedFlowers = []\n            \n            # we've gone through the entire listOfFlowerBloomDays list and need to check if the \"residual\" current list \n            # of adjacent bloomed flowers can make a bouquet ... so handle it here\n            numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n                    \n            return numberOfBouquetsWeCanMakeOnThisDay\n        \n        \n        # if the TOTAL amount of flowers we need doesn't match the number of possible flowers we can grow,\n        # then the given inputs are impossible for making enough bouquets (we don't have enough flowers)\n        totalNumberOfFlowersNeeded = targetNumberOfBouquets*flowersPerBouquet\n        numberOfFlowersWeCanGrow = len(listOfFlowerBloomDays)\n        if numberOfFlowersWeCanGrow < totalNumberOfFlowersNeeded: \n            return -1\n        \n        # no need to go past the day of the flower with the longest bloom date\n        leftDay = 0\n        rightDay = max(listOfFlowerBloomDays)\n        \n        while leftDay < rightDay:\n            \n            # currentDay is functioning as the \"mid\" of a binary search\n            currentDay = leftDay + (rightDay-leftDay)//2\n            \n            # as in most binary searches, we check if the mid (which I'm calling 'currentDay') satisfies the constraint\n            # that is, if we can make the target amount of bouquets on this day\n            if numberOfBouquetsWeCanMakeOnThisDay(currentDay) < targetNumberOfBouquets:\n                \n                # womp womp, we can't make enough bouquets on this day, so set up for next iteration\n                # the \"correct day\" is on the right side, so we get rid of all the \"incorrect days\" on the left side\n                # by updating the left to the currentDay+1\n                leftDay = currentDay+1\n            else:\n                \n                # yay, we can make enough bouquets on this day, but we don't know if this is the \"minimum day\"\n                # we discard the right side to keep searching\n                rightDay = currentDay\n        \n        # leftDay >= rightDay, so we've found the \"minimum day\"\n        return leftDay\n\t\t",
        "solution_js": "var minDays = function(bloomDay, m, k) {\n    if (m * k > bloomDay.length) {\n        return -1;\n    }\n\n    let left = 0;\n    let right = 0;\n\n    for (const day of bloomDay) {\n        left = Math.min(day, left);\n        right = Math.max(day, right);\n    }\n\n    let ans = right;\n\n    while (left < right) {\n        const day = Math.floor((left + right) / 2);\n\n        let count = 0;\n        let current = 0;\n\n        for (let j = 0; j < bloomDay.length; j++) {\n            if (bloomDay[j] <= day) {\n                current++;\n            } else {\n                current = 0;\n            }\n\n            if (current === k) {\n                count++;\n                current = 0;\n            }\n        }\n\n        if (count === m) {\n            ans = Math.min(ans, day);\n        }\n\n        if (count < m) {\n            left = day + 1;\n        } else {\n            right = day;\n        }\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int minDays(int[] bloomDay, int m, int k) {\n        if(m*k > bloomDay.length) return -1;\n        \n        int low = Integer.MAX_VALUE, high = 0;\n        for(int i:bloomDay){\n            low = Math.min(low,i);\n            high = Math.max(high,i);\n        }\n        while(low<=high){\n            int mid = low + (high-low)/2;\n            if(isPossible(bloomDay,mid,m,k)) high = mid - 1;\n            else low = mid + 1;\n        }\n        return low;\n    }\n    private boolean isPossible(int[] bloomDay,int maxDays,int m,int k){\n        for(int i=0;i<bloomDay.length;i++){\n            int count = k;\n            while(i<bloomDay.length && bloomDay[i]<=maxDays){\n                count--;\n                if(count==0){\n                    m--;\n                    break;\n                }\n                i++;\n            }\n            if(m==0) return true;\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n      bool check(int mid,vector<int> &v, int m, int k)\n      {\n          int n=v.size();\n          int cnt=0;// taking cnt for the no of k adjacent bouquets possible\n          for(int i=0;i<v.size();i++)\n          {\n              if(v[i]<=mid)\n              {\n                  int c=0;\n                  while(i<n and v[i]<=mid)\n                  {\n                      i++;\n                      c++;// c->checking for adjacent count\n                  }\n                 cnt+=c/k;\n              }\n          }\n          if(cnt>=m)\n              return true;\n          return false;\n\n      }\n    int minDays(vector<int>& bloomDay, int m, int k) {\n        int s=*min_element(bloomDay.begin(),bloomDay.end());\n        int e=*max_element(bloomDay.begin(),bloomDay.end());\n        int ans=e;\n        if((m*k)>bloomDay.size())\n            return -1;\n        while(s<=e)\n        {\n           int mid=s+(e-s)/2;\n            if(check(mid,bloomDay,m,k))\n            {\n                ans=mid;\n                e=mid-1;\n            }\n            else\n                s=mid+1;\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Find the Winner of the Circular Game",
        "algo_input": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 &lt;= i &lt; n, and moving clockwise from the nth friend brings you to the 1st friend.\n\nThe rules of the game are as follows:\n\n\n\tStart at the 1st friend.\n\tCount the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.\n\tThe last friend you counted leaves the circle and loses the game.\n\tIf there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.\n\tElse, the last friend in the circle wins the game.\n\n\nGiven the number of friends, n, and an integer k, return the winner of the game.\n\n&nbsp;\nExample 1:\n\nInput: n = 5, k = 2\nOutput: 3\nExplanation: Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n\nExample 2:\n\nInput: n = 6, k = 5\nOutput: 1\nExplanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= n &lt;= 500\n\n\n&nbsp;\nFollow up:\n\nCould you solve this problem in linear time with constant space?\n",
        "solution_py": "class Solution:\ndef findTheWinner(self, n: int, k: int) -> int:\n    ls=list(range(1,n+1))\n    while len(ls)>1:\n        i=(k-1)%len(ls)\n        ls.pop(i)\n        ls=ls[i:]+ls[:i]\n    \n    return ls[0]",
        "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar findTheWinner = function(n, k) {\n    let friends = Array.from({length: n}, (_, index) => index + 1)\n    let start = 0;\n    while(friends.length != 1){\n        start += (k - 1)\n        start = start % friends.length\n        friends.splice(start,1)\n    }\n    return friends[0]\n};",
        "solution_java": "class Solution {\n    public int findTheWinner(int n, int k) {\n\t    // Initialisation of the LinkedList\n        LinkedList<Integer> participants = new LinkedList<>();\n        for (int i = 1; i <= n; i++) {\n\t\t    participants.add(i);\n\t\t}\n\t\t\n\t\tint lastKilled = 0;\n\t\t// Run the game\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < k-1; j++) {\n\t\t\t    participants.add(participants.poll());\n\t\t\t}\n            lastKilled = participants.poll();\n        }\n        // Return the last one killed\n        return lastKilled;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int findTheWinner(int n, int k) {\n        vector<int>temp;\n\n        for(int i=1;i<=n;i++) temp.push_back(i);\n\n        int i=0;\n\n        while(temp.size()>1){\n            int t=temp.size();\n            i=(i+k-1)%t;\n            temp.erase(temp.begin()+i);\n        }\n        return *temp.begin();\n    }\n};"
    },
    {
        "title": "Maximize Distance to Closest Person",
        "algo_input": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\n\nThere is at least one empty seat, and at least one person sitting.\n\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized.&nbsp;\n\nReturn that maximum distance to the closest person.\n\n&nbsp;\nExample 1:\n\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\n\n\nExample 2:\n\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\n\n\nExample 3:\n\nInput: seats = [0,1]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= seats.length &lt;= 2 * 104\n\tseats[i]&nbsp;is 0 or&nbsp;1.\n\tAt least one seat is empty.\n\tAt least one seat is occupied.\n\n",
        "solution_py": "class Solution:\n    def maxDistToClosest(self, seats: List[int]) -> int:\n        # strategy is greedy solution:\n        # calculate local maximum for each interval: (b-a)//2\n        # then take max of local maximums\n        # the solution is O(n)\n        # I find this solution clear, but uses 5 passes\n        \n        # get all the occupied seat nums\n        seat_nums = [ix for ix, val in enumerate(seats) if val == 1]\n        \n        # check the ends\n        left_max, right_max = min(seat_nums), len(seats)-max(seat_nums)-1\n        \n        # calculate max distance for each gap\n        dists = [(y-x)//2 for x, y in zip(seat_nums, seat_nums[1:])]\n        \n        # take max of sitting on either end + each gap\n        return max([left_max, right_max, *dists])",
        "solution_js": "/**\n * @param {number[]} seats\n * @return {number}\n */\nvar maxDistToClosest = function(seats) {\n    let arr = seats.join('').split('1');\n    for(let i = 0; i < arr.length;i++){\n        if(arr[i] == '')\n            arr[i] = 0;\n        else{\n            let middle = true;\n            if(i == 0 || i == arr.length-1){\n                arr[i] = arr[i].length;\n            }else {\n                arr[i] = Math.ceil(arr[i].length/2);\n            }\n        }\n    }\n    return arr.sort((a,b) => (a >= b)?-1:1)[0]\n};",
        "solution_java": "class Solution {\n    public int maxDistToClosest(int[] seats) {\n        int size = seats.length;\n        int max = 0;\n        int start = -1;\n        int end = -1;\n\n        for(int i = 0; i<size; i++){\n            if(seats[i] != 0){\n                start = end; // update start to end when we have a filled seat.\n                end = i; // update end with i pointer when we have a filled seat.\n                if(start == -1) max = i; // for special case when there is only '1' in the array\n                else max = Math.max((end-start)/2,max); // updating max.\n            }\n        }\n\n        // Handeling speical cases before returning max.\n        // 1) last element is 0 as we wont be updating max for that in above loop.\n        // 2) when there only single '1' in the array, we need to make sure whether right half is bigger than the left half.\n\n        if(seats[size - 1] == 0 || start == -1) return Math.max(max, (size - 1 - end));\n        return max;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int maxDistToClosest(vector<int>& seats) {\n        vector<int> d;\n        int cnt = -1, ans = 0;\n\n        for(int i=0; i<seats.size(); i++) {\n            cnt++;\n            if(seats[i]) d.push_back(cnt), cnt = 0;\n        }\n        d.push_back(cnt);\n\n        for(int i=0; i<d.size(); i++) {\n            if(i > 0 && i < d.size() - 1) d[i] /= 2;\n            ans = max(ans, d[i]);\n        }\n\n        return ans;\n    }\n};"
    },
    {
        "title": "Reverse Words in a String III",
        "algo_input": "Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.\n\n&nbsp;\nExample 1:\nInput: s = \"Let's take LeetCode contest\"\nOutput: \"s'teL ekat edoCteeL tsetnoc\"\nExample 2:\nInput: s = \"God Ding\"\nOutput: \"doG gniD\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 104\n\ts contains printable ASCII characters.\n\ts does not contain any leading or trailing spaces.\n\tThere is at least one word in s.\n\tAll the words in s are separated by a single space.\n\n",
        "solution_py": "class Solution:\n    def reverseWords(self, s: str) -> str:\n        s = s + ' '\n        l = len(s)\n        t = ''\n        w = ''\n        for i in range(l):\n            if s[i]!=' ':\n                t = s[i] + t  # t stores the word in reverse order\n            else:\n\t\t\t\t# w stores the reversed word in the same order\n                w = w + t + ' ' # could have used .join() function and not write .strip()\n                t = \"\" # value of t is null so that it won't affect upcoming words\n        return w.strip() # removes extra whitespace",
        "solution_js": "var reverseWords = function(s) {\n    // make array of the words from s\n    let words = s.split(\" \");\n    for (let i in words) {\n\t    // replace words[i] with words[i] but reversed\n        words.splice(i, 1, words[i].split(\"\").reverse().join(\"\"))\n    } return words.join(\" \");\n};",
        "solution_java": "class Solution {\n    public String reverseWords(String s) {\n        if(s == null || s.trim().equals(\"\")){\n            return null;\n        }\n        String [] words = s.split(\" \");\n        StringBuilder resultBuilder = new StringBuilder();\n        for(String word: words){\n            for(int i = word.length() - 1; i>=0; i --){\n                resultBuilder.append(word.charAt(i));\n            }\n            resultBuilder.append(\" \");\n        }\n        return resultBuilder.toString().trim();\n    }\n}",
        "solution_c": "Time: O(n+n)  Space: O(1)\n\nclass Solution {\npublic:\n    string reverseWords(string s) {\n        int i,j;\n        for( i=0,j=0;i<size(s);i++){\n            if(s[i]==' '){\n                reverse(begin(s)+j,begin(s)+i);\n                j=i+1;\n            }\n        }\n        reverse(begin(s)+j,end(s));\n        return s;\n    }\n};"
    },
    {
        "title": "Unique Paths",
        "algo_input": "There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.\n\nGiven the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.\n\nThe test cases are generated so that the answer will be less than or equal to 2 * 109.\n\n&nbsp;\nExample 1:\n\nInput: m = 3, n = 7\nOutput: 28\n\n\nExample 2:\n\nInput: m = 3, n = 2\nOutput: 3\nExplanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -&gt; Down -&gt; Down\n2. Down -&gt; Down -&gt; Right\n3. Down -&gt; Right -&gt; Down\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def uniquePaths(self, m: int, n: int) -> int:\n        @cache\n        def dfs(i ,j):\n            if i == 0 and j == 0: return 1\n            elif i < 0 or j < 0: return 0\n            \n            return dfs(i-1, j) + dfs(i, j-1)\n        return dfs(m-1, n-1)",
        "solution_js": "var uniquePaths = function(m, n) {\n    let count = Array(m)\n    for(let i=0; i<m; i++) count[i] = Array(n)\n    for(let i=0; i<m; i++){\n        for(let j=0; j<n; j++){\n            if(i == 0 || j == 0) count[i][j] = 1\n            else count[i][j] = count[i][j-1] + count[i-1][j]\n        }\n    }\n    return count[m-1][n-1]\n};",
        "solution_java": "class Solution {\n    public int uniquePaths(int m, int n) {\n        int[][] dp = new int[m][n];\n        \n        for(int i = 0; i < m; i ++) {\n            for(int j = 0; j < n; j ++) {\n                dp[i][j] = -1;\n            }\n        }\n        \n        return helper(m, 0, n, 0, dp);\n    }\n    \n    private int helper(int m, int i, int n, int j, int[][] dp) {\n        if(i == m || j == n) {\n            return 0;\n        }\n        \n        if(i == m-1 && j == n-1) {\n            dp[i][j] = 1;\n        }\n        \n        if(dp[i][j] == -1) {\n            dp[i][j] = helper(m, i+1, n, j, dp) + helper(m, i, n, j+1, dp);\n        }\n        \n        return dp[i][j];\n    }\n}",
        "solution_c": "#define vi vector<int>\n#define vvi vector<vi>\nclass Solution {\npublic:\n    \n    int countPath(vvi& dp,int r,int c, int m , int n){\n          if(m==r-1 || n==c-1)\n              return 1;\n           \n        if(dp[m][n]!=-1)\n            return dp[m][n];\n        \n       return dp[m][n] = countPath(dp,r,c,m+1,n) + countPath(dp,r,c,m,n+1);\n    }\n    int uniquePaths(int m, int n) {\n        \n        vvi dp(m,vi(n,-1));\n        \n        return countPath(dp,m,n,0,0);\n    }\n};"
    },
    {
        "title": "Count Number of Pairs With Absolute Difference K",
        "algo_input": "Given an integer array nums and an integer k, return the number of pairs (i, j) where i &lt; j such that |nums[i] - nums[j]| == k.\n\nThe value of |x| is defined as:\n\n\n\tx if x &gt;= 0.\n\t-x if x &lt; 0.\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n\n\nExample 2:\n\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\n\n\nExample 3:\n\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t1 &lt;= nums[i] &lt;= 100\n\t1 &lt;= k &lt;= 99\n\n",
        "solution_py": "class Solution:\n    def countKDifference(self, nums: List[int], k: int) -> int:\n        seen = defaultdict(int)\n        counter = 0\n        for num in nums:\n            tmp, tmp2 = num - k, num + k\n            if tmp in seen:\n                counter += seen[tmp]\n            if tmp2 in seen:\n                counter += seen[tmp2]\n            \n            seen[num] += 1\n        \n        return counter",
        "solution_js": "var countKDifference = function(nums, k) {\n    nums = nums.sort((b,a) => b- a)\n   let count = 0;\n\n    for(let i = 0; i< nums.length; i++) {\n         for(let j = i + 1; j< nums.length; j++) {\n            if(Math.abs(nums[i] - nums[j]) == k) {\n                count++\n            }\n          }\n    }\n    return count ;\n};",
        "solution_java": "class Solution {\n    public int countKDifference(int[] nums, int k) {\n        Map<Integer,Integer> map = new HashMap<>();\n        int res = 0;\n\n        for(int i = 0;i< nums.length;i++){\n            if(map.containsKey(nums[i]-k)){\n                res+= map.get(nums[i]-k);\n            }\n            if(map.containsKey(nums[i]+k)){\n                res+= map.get(nums[i]+k);\n            }\n            map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n        }\n\n        return res;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int countKDifference(vector<int>& nums, int k) {\n        unordered_map<int, int> freq;\n        int res = 0;\n\n        for (auto num : nums) {\n            res += freq[num+k] + freq[num-k];\n            freq[num]++;\n        }\n\n        return res;\n    }\n};"
    },
    {
        "title": "Count Unreachable Pairs of Nodes in an Undirected Graph",
        "algo_input": "You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.\n\nReturn the number of pairs of different nodes that are unreachable from each other.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput: 0\nExplanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.\n\n\nExample 2:\n\nInput: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput: 14\nExplanation: There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= edges.length &lt;= 2 * 105\n\tedges[i].length == 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tThere are no repeated edges.\n\n",
        "solution_py": "'''\n* Make groups of nodes which are connected\n    eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\n\n    0 ---- 2 1 --- 6 3\n    | |\n    | |\n    5 ---- 4\n\n    groups will be {0: 4, 1: 2, 3: 1},\n    i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3\n\n* Now, we have [4, 2, 1] as no of nodes in each group, we have to multiply each of no. with remaining\n    ans = (4 * 2 + 4 * 1) + (2 * 1)\n    but calculating ans this way will give TLE.\n\n* if we notice, (4 * 2 + 4 * 1) + (2 * 1), we can combine, equation like this,\n    4 * 2 + (4 + 2) * 1, using this, we can reduce complexity.\n    so, if we have count of groups array as [a, b, c, d], ans will be,\n    ans = a * b + (a + b) * c + (a + b + c) * d\n\n* will use, union for generating groups.\n* ps, you can modify UnionFind class as per your need. Have implemented full union-find for beginners.\n'''\n\nclass UnionFind:\n    def __init__(self, size):\n        self.root = [i for i in range(size)]\n        self.rank = [1] * size\n    def find(self, x):\n        if x == self.root[x]:\n            return x\n        self.root[x] = self.find(self.root[x])\n        return self.root[x]\n    def union(self, x, y):\n        rootX = self.find(x)\n        rootY = self.find(y)\n        if rootX != rootY:\n            if self.rank[rootX] > self.rank[rootY]:\n                self.root[rootY] = rootX\n            elif self.rank[rootX] < self.rank[rootY]:\n                self.root[rootX] = rootY\n            else:\n                self.root[rootY] = rootX\n                self.rank[rootX] += 1\n\nclass Solution:\n    def countPairs(self, n: int, edges: List[List[int]]) -> int:\n        dsu = UnionFind(n)\n        for u, v in edges:\n            dsu.union(u, v)\n        C = Counter([dsu.find(i) for i in range(n)])\n        groupCounts = list(C.values())\n        ans = 0\n        firstGroupCount = groupCounts[0]\n        for i in range(1, len(groupCounts)):\n            ans += firstGroupCount * groupCounts[i]\n            firstGroupCount += groupCounts[i]\n        return ans",
        "solution_js": "var countPairs = function(n, edges) {\n    const adj = [];\n\n    for (let i = 0; i < n; i++) {\n        adj.push([]);\n    }\n    \n    for (let [from, to] of edges) {\n        adj[from].push(to);\n        adj[to].push(from);\n    }\n    \n    const visited = new Set();\n\n    function dfs(from) {\n        visited.add(from);\n\n        let count = 1;\n\n        for (const to of adj[from]) {\n            if (!visited.has(to)) {\n                count += dfs(to);\n            }\n        }\n        \n        return count;\n    }\n\n    const groups = [];\n        \n    for (let i = 0; i < n; i++) {\n        if (!visited.has(i)) {\n            const count = dfs(i);\n            groups.push(count);\n        }\n    }\n    \n    let ans = 0;\n    \n    for (let i = 0; i < groups.length - 1; i++) {\n        for (let j = i + 1; j < groups.length; j++) {\n            ans += groups[i] * groups[j];\n        }\n    }\n    \n    return ans;\n};",
        "solution_java": "class Solution {\n  public long countPairs(int n, int[][] edges) {\n    //Building Graph\n    ArrayList < ArrayList < Integer >> graph = new ArrayList < > ();\n    for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ());\n    for (int arr[]: edges) {\n      graph.get(arr[0]).add(arr[1]);\n      graph.get(arr[1]).add(arr[0]);\n    }\n    boolean visited[] = new boolean[n];\n    long res = 0;\n    int prev = 0;\n    int count[] = {\n      0\n    };\n    for (int i = 0; i < graph.size(); i++) { // Running for loop on all connected components of graph\n      if (visited[i] == true) continue; // if the node is alredy reached by any of other vertex then we don't need to terverse it again\n      dfs(graph, i, visited, count);\n      long a = n - count[0]; // (total - current count)\n      long b = count[0] - prev; // (current count - prev )\n      prev = count[0]; // Now Store count to prev\n      res += (a * b);\n    }\n    return res;\n  }\n  void dfs(ArrayList < ArrayList < Integer >> graph, int v, boolean vis[], int count[]) {\n    vis[v] = true;\n    count[0]++; //for counting connected nodes\n    for (int child: graph.get(v)) {\n      if (!vis[child]) {\n        dfs(graph, child, vis, count);\n      }\n    }\n  }\n}",
        "solution_c": "class Solution {\npublic:\n    typedef long long ll;\n    void dfs(int node, unordered_map<int,vector<int>>& m, ll& cnt, vector<int>& vis){\n        vis[node] = 1;\n        cnt++;\n        for(auto& i: m[node]){\n            if(vis[i]==0) dfs(i,m,cnt,vis);   \n        }\n    }\n    long long countPairs(int n, vector<vector<int>>& edges) {\n        unordered_map<int,vector<int>> m; // making adjacency list\n        for(int i=0;i<edges.size();i++){\n            m[edges[i][0]].push_back(edges[i][1]);\n            m[edges[i][1]].push_back(edges[i][0]);\n        }\n        ll ans = ((ll)n*(n-1))/2;\n        vector<int> vis(n,0);\n        for(int i=0;i<n;i++){\n            if(vis[i]==0){ // as node is not visited, we find the no. of nodes in current component.\n                ll cnt = 0;\n                dfs(i,m,cnt,vis);\n                ans -= (cnt*(cnt-1))/2;\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Minimum Flips to Make a OR b Equal to c",
        "algo_input": "Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make (&nbsp;a OR b == c&nbsp;). (bitwise OR operation).\nFlip operation&nbsp;consists of change&nbsp;any&nbsp;single bit 1 to 0 or change the bit 0 to 1&nbsp;in their binary representation.\n\n&nbsp;\nExample 1:\n\n\n\nInput: a = 2, b = 6, c = 5\nOutput: 3\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)\n\nExample 2:\n\nInput: a = 4, b = 2, c = 7\nOutput: 1\n\n\nExample 3:\n\nInput: a = 1, b = 2, c = 3\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= a &lt;= 10^9\n\t1 &lt;= b&nbsp;&lt;= 10^9\n\t1 &lt;= c&nbsp;&lt;= 10^9\n",
        "solution_py": "class Solution:\n    def minFlips(self, a: int, b: int, c: int) -> int:\n        res = 0\n        for i in range(32):\n            if (a & 1) | (b & 1) != (c & 1):\n                if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1\n                    res += 1\n                else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1\n                    res += (a & 1) + (b & 1)\n            a, b, c = a>>1, b>>1, c>>1 # right-shift by 1\n\n        return res\n\n# Time: O(1)\n# Space: O(1)",
        "solution_js": "var minFlips = function(a, b, c) {\n    let ans = 0;\n    for(let bit = 0; bit < 32; bit++) {\n        let bit_a = (a >> bit)&1, bit_b = (b >> bit)&1, bit_c = (c >> bit)&1;\n        if(bit_c !== (bit_a | bit_b)) {\n            if(bit_c === 1) { //a b will be 0 0\n                ans += 1;\n            } else { //a b -> 0 1 -> 1 0 -> 1 1\n                ans += (bit_a + bit_b === 2 ? 2 : 1);\n            }\n        }\n    }\n    return ans;\n};",
        "solution_java": "class Solution {\n    public int minFlips(int a, int b, int c) {\n        int j=-1;\n        int x=a|b;\n        int count=0;\n        while(c!=0 || x!=0){\n            j++;\n            int aa=x%2;\n            int bb=c%2;\n            if(aa==0 && bb==1)count++;\n            else if(aa==1 && bb==0) count+=funcount(j,a,b);\n            x=x>>1;\n            c=c>>1;\n        }\n        return count;\n    }\n    public static int funcount(int shift,int a,int b){\n        int cc=0;\n        int mask=1<<shift;\n        int b1=a&mask;\n        int b2=b&mask;\n        if(b1!=0)cc++;\n        if(b2!=0)cc++;\n        return cc;\n    }\n}```",
        "solution_c": "class Solution {\npublic:\n    int minFlips(int a, int b, int c) {\n        int changeBits = 0;\n\n        for(int i=0; i<32; i++){\n            int lastBitA = 0;\n            int lastBitB = 0;\n            int lastBitC = 0;\n            if(((a >> i) & 1) == 1){\n                lastBitA = 1;\n            }\n            if (((b >> i) & 1) == 1){\n                lastBitB = 1;\n            }\n            if (((c >> i) & 1) == 1){\n                lastBitC = 1;\n            }\n            if(lastBitC == 1){\n                if(lastBitA == 0 & lastBitB == 0){\n                    changeBits++;\n                }\n            }\n            else{\n                if(lastBitA == 1 || lastBitB == 1){\n                    if(lastBitA == 1){\n                        changeBits++;\n                    }\n                    if(lastBitB == 1){\n                        changeBits++;\n                    }\n                }\n            }\n        }\n        return changeBits;\n    }\n};"
    },
    {
        "title": "Minimum Number of Swaps to Make the String Balanced",
        "algo_input": "You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.\n\nA string is called balanced if and only if:\n\n\n\tIt is the empty string, or\n\tIt can be written as AB, where both A and B are balanced strings, or\n\tIt can be written as [C], where C is a balanced string.\n\n\nYou may swap the brackets at any two indices any number of times.\n\nReturn the minimum number of swaps to make s balanced.\n\n&nbsp;\nExample 1:\n\nInput: s = \"][][\"\nOutput: 1\nExplanation: You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".\n\n\nExample 2:\n\nInput: s = \"]]][[[\"\nOutput: 2\nExplanation: You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".\n\n\nExample 3:\n\nInput: s = \"[]\"\nOutput: 0\nExplanation: The string is already balanced.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == s.length\n\t2 &lt;= n &lt;= 106\n\tn is even.\n\ts[i] is either '[' or ']'.\n\tThe number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.\n\n",
        "solution_py": "class Solution:\n    def minSwaps(self, s: str) -> int:\n        res, bal = 0, 0\n        for ch in s:\n            bal += 1 if ch == '[' else -1\n            if bal == -1:\n                res += 1\n                bal = 1\n        return res",
        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minSwaps = function(s) {\n    let stk = []\n    for(let c of s){\n        if(stk && c == ']')    stk.pop()\n        else if(c == '[')   stk.push(c)\n    }\n    return (stk.length) / 2\n};",
        "solution_java": "class Solution {\n    public int minSwaps(String s) {\n        // remove the balanced part from the given string\n        Stack<Character> stack = new Stack<>();\n        for(char ch : s.toCharArray()) {\n            if(ch == '[')\n                stack.push(ch);\n            else {\n                if(!stack.isEmpty() && stack.peek() == '[')\n                    stack.pop();\n                else\n                    stack.push(ch);\n            }\n        }\n        int unb = stack.size()/2; // # of open or close bracket\n        return (unb+1)/2;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minSwaps(string s) {\n        int ans=0;\n        stack<char> stack;\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='['){\n                stack.push(s[i]);\n            }\n            if(s[i]==']' && stack.size()!=0 && stack.top()=='['){\n                stack.pop();\n            }\n\n        }\n\n        ans=stack.size();\n        if(ans%2==0)\n            return ans/2;\n        else\n            return (ans+1)/2;\n\n    }\n};"
    },
    {
        "title": "Frog Position After T Seconds",
        "algo_input": "Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.\n\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.\n\nReturn the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput: 0.16666666666666666 \nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \n\n\nExample 2:\n\n\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput: 0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t1 &lt;= ai, bi &lt;= n\n\t1 &lt;= t &lt;= 50\n\t1 &lt;= target &lt;= n\n\n",
        "solution_py": "class Solution:\n    def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n        adj = [[] for i in range(n)]\n        for u,v in edges:\n            adj[u-1].append(v-1)\n            adj[v-1].append(u-1)\n        def f(u,p,tt):\n            if(u==target-1): return tt==0 or len(adj[u])==(p>=0)\n            if(tt==0): return 0\n            res = 0\n            for v in adj[u]:\n                if(p==v): continue\n                res = max(res,(1/(len(adj[u])-(p!=-1)))*f(v,u,tt-1))\n            return res\n        return f(0,-1,t)\n            \n            \n        ",
        "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} t\n * @param {number} target\n * @return {number}\n */\nfunction dfs(n, map, t, target, visited, prop) {\n    // edge case1: if run out of steps, cannot find target\n    if(t === 0 && n !== target) return 0;\n    // edge case2: if run out of steps, but found target\n    if(t === 0 && n === target) return prop;\n\n    visited.add(n);\n    // get unvisited children/neighbors\n    const validChildren = [];\n    (map[n] ?? []).forEach((child) => {\n        if(!visited.has(child)) validChildren.push(child);\n    })\n    // edge case3, if still more steps to use, but no more children to move,\n    // if already at the targeted node, should just return\n    if(n === target && t > 0 && !validChildren.length) return prop;\n    // edge case4, if still more steps to use and no more children to move,\n    // but current node is not target node, cannot find target, return 0\n    if(n !== target && t > 0 && !validChildren.length) return 0;\n\n    // go to next valid child/neighbor\n    for(let i = 0; i < validChildren.length; i ++) {\n        if(visited.has(validChildren[i])) continue;\n        let result = dfs(validChildren[i], map, t - 1, target, visited, prop * (1 / validChildren.length))\n        if(result !== 0) return result;\n    }\n\n    return 0;\n}\n\nvar frogPosition = function(n, edges, t, target) {\n    const map = new Array(n + 1);\n    // make bidirectional edge map\n    edges.forEach(item => {\n        if(!map[item[0]]) map[item[0]] = [];\n        if(!map[item[1]]) map[item[1]] = [];\n        map[item[0]].push(item[1]);\n        map[item[1]].push(item[0]);\n    });\n\n    return dfs(1, map, t, target, new Set(), 1);\n};",
        "solution_java": "class Solution {\n    public double frogPosition(int n, int[][] edges, int t, int target) {\n       \n        List<List<Integer>> graph=new ArrayList<>();\n        for(int i=0;i<=n;i++) graph.add(new ArrayList<>());\n        \n          for(int i=0;i<edges.length;i++) {\n         \n           graph.get(edges[i][0]).add(edges[i][1]);\n           graph.get(edges[i][1]).add(edges[i][0]);\n          \n      }\n        boolean[] vis=new boolean[n+1];\n        return Sol(graph,1, t, target,vis);\n        \n    }\n    public double Sol(List<List<Integer>> graph,int ver,int t,int tar,boolean[] vis){\n        \n         int count=0;\n        for(Integer child:graph.get(ver)){\n            if(!vis[child]) count++;\n        }\n        \n        \n        vis[ver]=true;\n        if(t<0) return 0;\n        \n        if(ver==tar){\n            if(count==0 || t==0) return 1.0;\n         }\n        \n        if(graph.get(ver).size()==0) return 0;\n        \n        double ans=0.0;\n        \n       \n        for(Integer child:graph.get(ver)){\n\n           // System.out.println(child);\n            if(!vis[child])\n            ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis);\n        }\n       // System.out.println(ans);\n        vis[ver]=false;\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {\n        unordered_map<int, vector<int>> adjList;\n        for(const auto& edge : edges) {\n            adjList[edge[0]].push_back(edge[1]);\n            adjList[edge[1]].push_back(edge[0]);\n        }\n\n        // BFS way\n        queue<pair<int, double>> Q;\n        Q.push({1, 1.0});\n        int time = 0;\n        vector<int> visited(n+1, false);\n\n        while(not Q.empty()) {\n            int size = Q.size();\n\n            if (time > t) break;\n\n            while(size--) {\n                auto pp = Q.front(); Q.pop();\n                int node = pp.first;\n                double prob = pp.second;\n\n                visited[node] = true;\n\n                // Count the unvisited nbr\n                int nbrCount = 0;\n                for(auto& nbr : adjList[node]) {\n                    if (not visited[nbr]) nbrCount++;\n                }\n\n                if (node == target) {\n                    if (time == t) return prob;\n                    if (time < t) {\n                        // Check if any unvisited ? if yes, then frog would jump there and not be able to jump back here\n                        if (nbrCount > 0) return 0.0;\n\n                        // else return the same prob\n                        return prob;\n                    }\n                }\n\n                for(auto& nbr : adjList[node]) {\n                    if (not visited[nbr]) {\n                        // update the prob as it will be divided by number of nbr\n                        Q.push({nbr, (prob * (1.0/nbrCount))});\n                    }\n                }\n            }\n\n            time++;\n        }\n\n        return 0.0;\n    }\n};"
    },
    {
        "title": "Minimum Sideway Jumps",
        "algo_input": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.\n\nYou are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.\n\n\n\tFor example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.\n\n\nThe frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.\n\n\n\tFor example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.\n\n\nReturn the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.\n\nNote: There will be no obstacles on points 0 and n.\n\n&nbsp;\nExample 1:\n\nInput: obstacles = [0,1,2,3,0]\nOutput: 2 \nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n\n\nExample 2:\n\nInput: obstacles = [0,1,1,3,3,0]\nOutput: 0\nExplanation: There are no obstacles on lane 2. No side jumps are required.\n\n\nExample 3:\n\nInput: obstacles = [0,2,1,0,3,0]\nOutput: 2\nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n\n\n&nbsp;\nConstraints:\n\n\n\tobstacles.length == n + 1\n\t1 &lt;= n &lt;= 5 * 105\n\t0 &lt;= obstacles[i] &lt;= 3\n\tobstacles[0] == obstacles[n] == 0\n\n",
        "solution_py": "class Solution:\n    def minSideJumps(self, obstacles: List[int]) -> int:\n        \n        \"\"\"\n        # TLE Recursion DP\n        @cache\n        def dp(curr_lane = 2, point = 0):\n            if point == len(obstacles)-1:\n                return 0\n            if obstacles[point+1] == curr_lane:\n                return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n            \n            return dp(curr_lane, point+1)\n        \n        \n        return dp()\n            \n        \"\"\"\n        \n        n = len(obstacles)        \n        dp = [[0, 0, 0, 0] for _ in range(n)]\n        \n        for point in range(n-2, -1, -1):\n            for curr_lane in range(4):\n                if obstacles[point+1] == curr_lane:\n                    dp[point][curr_lane] = min(dp[point+1][lane] for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n                else:\n                    dp[point][curr_lane] = dp[point+1][curr_lane]\n                    \n        return dp[0][2]",
        "solution_js": "var minSideJumps = function(obstacles) {\n    // create a dp cache for tabulation\n    const dp = [...obstacles].map(() => new Array(4).fill(Infinity));\n    \n    // initialize the first positions\n    dp[0][2] = 0;\n    for (const lane of [1,3]) {\n        if (obstacles[0] === lane) continue;\n        dp[0][lane] = 1;\n    }\n\n    // for every index we will do the following\n    for (let i = 1; i < obstacles.length; i++) {\n        \n        // first we find the best way to get to this position from the previous index\n        for (let nextLane = 1; nextLane <= 3; nextLane++) {\n            if (obstacles[i] === nextLane) continue;\n            dp[i][nextLane] = dp[i - 1][nextLane]\n        }\n        \n        // then we find the best way to get to this position from the current index;\n        for (let nextLane = 1; nextLane <= 3; nextLane++) {\n            for (let prevLane = 1; prevLane <= 3; prevLane++) {\n                if (prevLane === nextLane) continue;\n                if (obstacles[i] === nextLane) continue;\n                dp[i][nextLane] = Math.min(dp[i][nextLane], dp[i][prevLane] + 1)\n            }\n        }\n    }\n\n    // return the best result after reaching the end\n    return Math.min(...dp[dp.length - 1])\n};",
        "solution_java": "class Solution {\n    public int minSideJumps(int[] obstacles) {\n        int[] dp = new int[]{1, 0, 1};\n        for(int i=1; i<obstacles.length; i++){\n            switch(obstacles[i]){\n                case 0:\n                    dp[0] = min(dp[0], dp[1]+1, dp[2]+1);\n                    dp[1] = min(dp[0]+1, dp[1], dp[2]+1);\n                    dp[2] = min(dp[0]+1, dp[1]+1, dp[2]);\n                    break;\n                case 1:\n                    dp[0] = Integer.MAX_VALUE;\n                    dp[1] = min(dp[1], dp[2]+1);\n                    dp[2] = min(dp[1]+1, dp[2]);\n                    break;\n                case 2:\n                    dp[0] = min(dp[0], dp[2]+1);\n                    dp[1] = Integer.MAX_VALUE;\n                    dp[2] = min(dp[0]+1, dp[2]);\n                    break;\n                case 3:\n                    dp[0] = min(dp[0], dp[1]+1);\n                    dp[1] = min(dp[0]+1, dp[1]);\n                    dp[2] = Integer.MAX_VALUE;\n                    break;\n            }\n        }\n        return min(dp[0], dp[1], dp[2]);\n    }\n    \n    int min(int... vals){\n        int min = Integer.MAX_VALUE;\n        for(int val: vals){\n            if(val>=0) min = Math.min(min, val);\n        }\n        return min;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int func(int i,int l,vector<int>&obstacles,vector<vector<int>>&dp){\n        if(i==obstacles.size()-2){\n            if(obstacles[i+1]==l)return 1;\n            return 0;\n        }\n\n        if(dp[i][l]!=-1)return dp[i][l];\n\n        if(obstacles[i+1]!=l){\n            return dp[i][l] = func(i+1,l,obstacles,dp);\n        }\n\n    \n        int b=INT_MAX;\n        for(int j=1;j<=3;j++){\n            if(l==j)continue;\n            if(obstacles[i]==j)continue;\n            b=min(b,1+func(i,j,obstacles,dp));\n        }\n    \n\n        return dp[i][l] = b;\n    }\n\n    int minSideJumps(vector<int>& obstacles) {\n        int n=obstacles.size();\n        vector<vector<int>>dp(n,vector<int>(4,-1));\n        return func(0,2,obstacles,dp);\n    }\n};"
    },
    {
        "title": "Minimum Number of Operations to Move All Balls to Each Box",
        "algo_input": "You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.\n\nIn one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\n\nReturn an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.\n\nEach answer[i] is calculated considering the initial state of the boxes.\n\n&nbsp;\nExample 1:\n\nInput: boxes = \"110\"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n\n\nExample 2:\n\nInput: boxes = \"001011\"\nOutput: [11,8,5,4,3,4]\n\n&nbsp;\nConstraints:\n\n\n\tn == boxes.length\n\t1 &lt;= n &lt;= 2000\n\tboxes[i] is either '0' or '1'.\n\n",
        "solution_py": "class Solution:\n    def minOperations(self, boxes: str) -> List[int]:\n        ans = [0]*len(boxes)\n        leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n        for i in range(1, n):\n            if boxes[i-1] == '1': leftCount += 1\n            leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n            ans[i] = leftCost\n        for i in range(n-2, -1, -1):\n            if boxes[i+1] == '1': rightCount += 1\n            rightCost += rightCount\n            ans[i] += rightCost\n        return ans",
        "solution_js": " var minOperations = function(boxes) {\n    \n    const ans = new Array(boxes.length).fill(0);\n\n    let ballsLeft = 0, ballsRight = 0;\n    let movesLeft = 0, movesRight = 0;\n\n    const len = boxes.length - 1;\n    \n    for(let i = 0; i <= len; i++) {\n       \n       movesLeft += ballsLeft;\n       movesRight += ballsRight;\n       ans[i] += movesLeft;\n       ans[len - i] += movesRight;\n       ballsLeft += +boxes[i];\n       ballsRight += +boxes[len - i];\n    }\n\n    return ans;\n};",
        "solution_java": "class Solution{\n    public int[] minOperations(String boxes){\n        int n = boxes.length();\n        int[] ans = new int[n];\n        for(int i=0; i<n; i++){\n            int t = 0;\n            for(int j=0; j<n; j++){\n                char c = boxes.charAt(j);\n                if(c=='1') t += Math.abs(i-j);\n            }\n            ans[i] = t;\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> minOperations(string boxes) {\n        int n = boxes.size();\n        vector<int> ans;\n        for(int i = 0; i < n; i++)\n        {\n            int res = 0;\n            for(int j = 0; j < n; j++)\n            {\n                if(boxes[j] == '1')\n                {\n                    res += abs(i-j);\n                }\n            }\n            ans.push_back(res);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Dungeon Game",
        "algo_input": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.\n\nThe knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.\n\nSome of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).\n\nTo reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n\nReturn the knight's minimum initial health so that he can rescue the princess.\n\nNote that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n\n&nbsp;\nExample 1:\n\nInput: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput: 7\nExplanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN.\n\n\nExample 2:\n\nInput: dungeon = [[0]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tm == dungeon.length\n\tn == dungeon[i].length\n\t1 &lt;= m, n &lt;= 200\n\t-1000 &lt;= dungeon[i][j] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n\n\n\tdef calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n\n\t\tdp = defaultdict(lambda: inf)\n\t\tdp[(len(dungeon), len(dungeon[0]) - 1)] = 1\n\n\t\tfor i in range(len(dungeon) - 1, -1, -1):\n\n\t\t\tfor j in range(len(dungeon[0]) - 1, -1, -1):\n\n\t\t\t\tdp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i][j]\n\n\t\t\t\tif dp[(i, j)] <= 0:\n\t\t\t\t\tdp[(i, j)] = 1\n\n\t\treturn dp[(0, 0)]",
        "solution_js": "/**\n * The dynamic programming solution.\n * \n * Time Complexity:  O(m*n)\n * Space Complexity: O(1)\n * \n * @param {number[][]} dungeon\n * @return {number}\n */\nvar calculateMinimumHP = function(dungeon) {\n\tconst m = dungeon.length\n\tconst n = dungeon[0].length\n\n\tconst ii = m - 1\n\tconst jj = n - 1\n\n\tfor (let i = ii; i >= 0; i--) {\n\t\tfor (let j = jj; j >= 0; j--) {\n\t\t\tif (i < ii || j < jj) {\n\t\t\t\tconst hc = dungeon[i][j]\n\n\t\t\t\tconst hp1 = (i < ii) ? Math.min(hc, hc + dungeon[i + 1][j]) : -Infinity\n\t\t\t\tconst hp2 = (j < jj) ? Math.min(hc, hc + dungeon[i][j + 1]) : -Infinity\n\n\t\t\t\tdungeon[i][j] = Math.max(hp1, hp2)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Math.max(1 - dungeon[0][0], 1)\n}",
        "solution_java": "class Solution {\n    Integer[][] min;\n    public int calculateMinimumHP(int[][] dungeon) {\n        min = new Integer[dungeon.length][dungeon[0].length];\n        int answer = min(0, 0, dungeon);\n        return Math.max(answer, 1);\n    }\n    public int min(int i, int j, int[][] dungeon){\n        if(i > dungeon.length - 1 || j > dungeon[0].length - 1) return 400000;\n        if(i == dungeon.length - 1 && j == dungeon[0].length - 1) return - dungeon[i][j] + 1; \n        if(min[i][j] == null){\n            int down = min(i + 1, j, dungeon);\n            int right = min(i, j + 1, dungeon);\n            min[i][j] = Math.min(Math.max(right, 1), Math.max(down, 1)) - dungeon[i][j];\n        }\n        return min[i][j];\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int solve(int i, int j, int m , int n, vector<vector<int>> &grid)\n    {\n        // if we come out of the grid simply return a large value\n        if(i >= m || j >= n)\n            return INT_MAX;\n        \n        // calucate health by the 2 possible ways\n        int down = solve(i + 1, j, m, n, grid);\n        int right = solve(i, j + 1, m, n, grid);\n        \n\t\t// take the min both both\n        int health = min(down, right);\n        \n        // we reach the destination when both the sides return INT_MAX\n        if(health == INT_MAX)\n        {\n            health = 1; // both are +ve large integers so min health required = 1\n        }\n        \n        int ans = 0;\n        if(health - grid[i][j] > 0)\n        {\n            ans = health - grid[i][j];\n        }\n        else\n        {\n            ans = 1;\n        }\n             \n        return ans;\n    }\n    \n    int calculateMinimumHP(vector<vector<int>>& dungeon) \n    {\n        int m = dungeon.size();\n        int n = dungeon[0].size();\n        \n        return solve(0, 0, m, n, dungeon);\n    }\n};"
    },
    {
        "title": "The K Weakest Rows in a Matrix",
        "algo_input": "You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.\n\nA row i is weaker than a row j if one of the following is true:\n\n\n\tThe number of soldiers in row i is less than the number of soldiers in row j.\n\tBoth rows have the same number of soldiers and i &lt; j.\n\n\nReturn the indices of the k weakest rows in the matrix ordered from weakest to strongest.\n\n&nbsp;\nExample 1:\n\nInput: mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput: [2,0,3]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].\n\n\nExample 2:\n\nInput: mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput: [0,2]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].\n\n\n&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t2 &lt;= n, m &lt;= 100\n\t1 &lt;= k &lt;= m\n\tmatrix[i][j] is either 0 or 1.\n\n",
        "solution_py": "class Solution:\n    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n\n        row = []\n        for i in range(len(mat)):\n            row.append((sum(mat[i]), i))\n\n        row.sort()\n        ans = [idx for (val, idx) in row[:k]]\n\n        return ans",
        "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number[]}\n\n * S: O(N)\n * T: O(N*logN)\n */\nvar kWeakestRows = function(mat, k) {\n    return mat.reduce((acc, row, index) => {\n        let left = 0;\n        let right = row.length - 1;\n\n        while(left <= right) {\n            let mid = Math.floor( (left + right) / 2);\n\n            if(row[mid]) {\n                left = mid + 1;\n            } else {\n                right = mid - 1;\n            }\n        }\n\n        acc.push({ index, value: left });\n\n        return acc;\n    }, []).sort((a, b) => a.value - b.value).splice(0, k).map(item => item.index);\n};",
        "solution_java": "class Solution {\n    public int[] kWeakestRows(int[][] mat, int k) {\n        Map<Integer, Integer> map = new HashMap<>();\n        List<Integer> list = new ArrayList<>();\n        int[] arr = new int[k];\n        for (int i = 0; i < mat.length; i++){\n            int n = getBits(mat[i]);\n            map.put(i, n);\n            list.add(n);\n        }\n        Collections.sort(list);\n        int z = 0;\n        for (int i = 0; i < k; i++){\n            for (Map.Entry<Integer, Integer> m : map.entrySet()){\n                if (list.get(i).equals(m.getValue())){\n                    arr[z++] = m.getKey();\n                    map.remove(m.getKey(), m.getValue());\n                    break;\n                }\n            }\n        }\n\n        return arr;\n    }\n\n    private static Integer getBits(int[] arr) {\n        int count = 0;\n        for (int i = 0; i < arr.length; i++) {\n            if (arr[i] == 1) count++;\n        }\n\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {\n        // <idx, count>\n        vector<pair<int,int>> freqMapper;\n        int civilian = 0;\n        for(int i=0; i<mat.size(); ++i) {\n            int degree = count(mat[i].begin(), mat[i].end(), civilian);\n            freqMapper.push_back({i, degree});\n        }\n        sort(freqMapper.begin(), freqMapper.end(), [](pair<int,int> pair1, pair<int,int> pair2) {\n        if (pair1.second > pair2.second) {\n            return true;\n        } else if (pair1.second == pair2.second) {\n            return pair1.first < pair2.first;\n        }\n        return pair1.second > pair2.second;\n    });\n        vector<int> kWeakest;\n        for(int i=0; i<k; i++) kWeakest.push_back(freqMapper[i].first);\n        return kWeakest;\n    }\n    \n};"
    },
    {
        "title": "Spiral Matrix",
        "algo_input": "Given an m x n matrix, return all elements of the matrix in spiral order.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,2,3,6,9,8,7,4,5]\n\n\nExample 2:\n\nInput: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nOutput: [1,2,3,4,8,12,11,10,9,5,6,7]\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 10\n\t-100 &lt;= matrix[i][j] &lt;= 100\n\n",
        "solution_py": "class Solution:\n    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n        col, row = len(matrix[0]), len(matrix)\n        l, t, r, b = 0, 0, col - 1, row - 1\n        res = []\n        while l <= r and t <= b:\n            for i in range(l, r):\n                res.append(matrix[t][i])\n            for i in range(t, b):\n                res.append(matrix[i][r])\n            \n\t\t\t# Append the orphan left by the open interval\n            if t == b:\n                res.append(matrix[t][r])\n            else:\n                # From right to left at the bottom\n                for i in range(r, l, -1):\n                    res.append(matrix[b][i])\n            \n\t\t\t# Avoid duplicated appending if it is a square\n            if l == r and t != b:\n                res.append(matrix[b][r])\n            else:\n                # From bottom to top at the left\n                for i in range(b, t, -1):\n                    res.append(matrix[i][l])\n            l += 1\n            t += 1\n            r -= 1\n            b -= 1\n\n        return res",
        "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nvar spiralOrder = function(matrix) {\n    let [top, bot, left, right, ans] = [0, matrix.length - 1, 0, matrix[0].length - 1,[]]\n\n    while ((top <= bot) && (left <= right)) {\n        for (let j = left; j <= right; j++) {\n            ans.push(matrix[top][j])\n        }\n        top ++;\n        for (let i = top; i <= bot; i++) {\n            ans.push(matrix[i][right])\n        }\n        right --;\n        if ((bot < top) || (right < left)) {\n            break\n        }\n        for (let j = right; left <= j; j--){\n            ans.push(matrix[bot][j])\n        }\n        bot --;\n        for (let i = bot; top <= i; i--){\n            ans.push(matrix[i][left])\n        }\n        left ++;\n    }\n    return ans\n}",
        "solution_java": "class Solution {\n    public List<Integer> spiralOrder(int[][] matrix) {\n        List<Integer> ans = new ArrayList<>();\n        int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;\n\n        while (top <= bottom && left <= right) \n        {\n            for (int i = left; i <= right; i++)\n                ans.add(matrix[top][i]);\n            top++;\n\n            for (int i = top; i <= bottom; i++)\n                ans.add(matrix[i][right]);\n            right--;\n\n            if (top <= bottom) {\n                for (int i = right; i >= left; i--)\n                    ans.add(matrix[bottom][i]);\n                bottom--;\n            }\n\n            if (left <= right) {\n                for (int i = bottom; i >= top; i--)\n                    ans.add(matrix[i][left]);\n                left++;\n            }\n        }\n        return ans;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\n    vector<int> _res;\n    vector<vector<bool>> _visited;\n\n    void spin(vector<vector<int>>& matrix, int direction, int i, int j) {\n\n        _visited[i][j] = true;\n        _res.push_back(matrix[i][j]);\n\n        switch (direction){\n            // left to right\n            case 0:\n                if ( j+1 >= matrix[0].size() || _visited[i][j+1]) {\n                    direction = 1;\n                    i++;\n                } else {\n                    j++;\n                }\n                break;\n            // up to bottom\n            case 1:\n                if ( i+1 >= matrix.size() || _visited[i+1][j]) {\n                    direction = 2;\n                    j--;\n                } else {\n                    i++;\n                }\n                break;\n            // right to left\n            case 2:\n                if ( j == 0 || _visited[i][j-1]) {\n                    direction = 3;\n                    i--;\n                } else {\n                    j--;\n                }\n                break;\n            // bottom to up\n            case 3:\n                if ( i == 0 || _visited[i-1][j]) {\n                    direction = 0;\n                    j++;\n                } else {\n                    i--;\n                }\n                break;\n        }\n        if ( i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() ) {\n            return;\n        }\n        if ( _visited[i][j] ) {\n            return;\n        }\n        spin(matrix, direction, i, j);\n    }\n    \n    vector<int> spiralOrder(vector<vector<int>>& matrix) {\n        _res.clear();\n        _visited = vector<vector<bool>>(matrix.size(), std::vector<bool>(matrix[0].size(), false));\n        spin(matrix, 0, 0, 0);\n        return _res;\n    }\n};"
    },
    {
        "title": "Random Pick Index",
        "algo_input": "Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.\n\nImplement the Solution class:\n\n\n\tSolution(int[] nums) Initializes the object with the array nums.\n\tint pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\nOutput\n[null, 4, 0, 2]\n\nExplanation\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 104\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\ttarget is an integer from nums.\n\tAt most 104 calls will be made to pick.\n\n",
        "solution_py": "class Solution:\n\n    def __init__(self, nums: List[int]):\n        #self.nums = nums\n        #create a hash of values with their list of indices\n        self.map = defaultdict(list)\n        for i,v in enumerate(nums):\n            self.map[v].append(i)\n        \n\n    def pick(self, target: int) -> int:\n        return random.sample(self.map[target],1)[0]\n        '''\n        reservoir = 0\n        count = 0\n        for i in range(len(self.nums)):\n            if self.nums[i] == target:\n                count+=1\n                if random.random() < 1/count:\n                    reservoir = i\n        return reservoir\n\n        \n        samp = []\n        for i in range(len(self.nums)):\n            if self.nums[i] == target:\n                samp.append(i)\n        return (random.sample(samp,1))[0]\n        '''\n        \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(nums)\n# param_1 = obj.pick(target)",
        "solution_js": "var Solution = function(nums) {\n    this.map = nums.reduce((result, num, index) => {\n        const value = result.get(num) ?? [];\n\n        value.push(index);\n        result.set(num, value);\n        return result;\n    }, new Map());\n};\n\nSolution.prototype.pick = function(target) {\n    const pick = this.map.get(target);\n    const random = Math.random() * pick.length | 0;\n\n    return pick[random];\n};",
        "solution_java": "class Solution {\n    ArrayList<Integer> ll=new ArrayList<>();\n    public Solution(int[] nums) {\n        for(int i=0;i<nums.length;i++){\n            ll.add(nums[i]);\n        \n        }\n    }\n    public int pick(int target) {\n        double a=Math.random();\n        int n=(int)(a*this.ll.size());\n        while(this.ll.get(n)!=target){\n            a=Math.random();\n            n=(int)(a*this.ll.size());\n        }\n        return n; \n    }\n}",
        "solution_c": "class Solution {\n    unordered_map<int,vector<int>> itemIndicies;\npublic:\n    Solution(vector<int>& nums)\n    {\n        srand(time(NULL));\n        \n        for (int i = 0; i < nums.size(); i++)\n        {\n            if (itemIndicies.find(nums[i]) == itemIndicies.end())\n                itemIndicies[nums[i]] = {i};\n            else\n                itemIndicies[nums[i]].push_back(i);\n        }\n    }\n    \n    int pick(int target) {\n        int size = itemIndicies[target].size();\n        int randomValue = rand() % size;\n        return itemIndicies[target][randomValue];\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution* obj = new Solution(nums);\n * int param_1 = obj->pick(target);\n */"
    },
    {
        "title": "Check if All Characters Have Equal Number of Occurrences",
        "algo_input": "Given a string s, return true if s is a good string, or false otherwise.\n\nA string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).\n\n&nbsp;\nExample 1:\n\nInput: s = \"abacbc\"\nOutput: true\nExplanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.\n\n\nExample 2:\n\nInput: s = \"aaabb\"\nOutput: false\nExplanation: The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def areOccurrencesEqual(self, s: str) -> bool:\n        return len(set(Counter(s).values())) == 1",
        "solution_js": "var areOccurrencesEqual = function(s) {\n    var freq = {}\n    for (let c of s) freq[c] = (freq[c] || 0) + 1\n    var val = freq[s[0]]\n    for (let c in freq) if (freq[c] && freq[c] != val) return false;\n    return true;\n};",
        "solution_java": "class Solution {\n    public boolean areOccurrencesEqual(String s) {\n        int[] freq = new int[26];\n        \n        for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++;\n\n        int val = freq[s.charAt(0) - 'a'];\n        for (int i = 0; i < 26; i++)\n            if (freq[i] != 0 && freq[i] != val) return false; \n\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool areOccurrencesEqual(string s) {\n        unordered_map<char, int> freq;\n        for (auto c : s) freq[c]++;\n        int val = freq[s[0]];\n        for (auto [a, b] : freq) if (b != val) return false;\n        return true;\n    }\n};"
    },
    {
        "title": "Palindrome Partitioning IV",
        "algo_input": "Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​\n\nA string is said to be palindrome if it the same string when reversed.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abcbdd\"\nOutput: true\nExplanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n\n\nExample 2:\n\nInput: s = \"bcbddxy\"\nOutput: false\nExplanation: s cannot be split into 3 palindromes.\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 2000\n\ts​​​​​​ consists only of lowercase English letters.\n\n",
        "solution_py": "class Solution:\n    def checkPartitioning(self, s: str) -> bool:\n        n = len(s)\n\n        @lru_cache(None)\n        def pal(i,j):\n            if i == j:\n                return True\n            if s[i] != s[j]:\n                return False\n            if i+1 == j:\n                return True\n            else:\n                return pal(i+1,j-1)\n\n        for i in range(n-2):\n            if pal(0,i):\n                for j in range(i+1,n-1):\n                    if pal(i+1,j) and pal(j+1,n-1):\n                        return True\n        return False",
        "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar checkPartitioning = function(s) {\n    // create a dp that will represent the starting and ending index of a substring\n    // if dp[i][j] is true that means that the string starting from i and ending at j is a palindrome\n    const dp = new Array(s.length).fill(null).map(() => new Array(s.length).fill(false));\n    \n    // all substrings of length 1 are palindromes so we mark all matching indices as true\n    for (let i = 0; i < s.length; i++) {\n        dp[i][i] = true;\n    }\n    \n    \n    // slowly grow the substring from each index\n    // we will know the substring is a palindrom if the substring prior was a palindrome\n    for (let lengthOfSubString = 2; lengthOfSubString <= s.length; lengthOfSubString++) {\n        for (let startingIndex = 0; startingIndex + lengthOfSubString <= s.length; startingIndex++) {\n            \n            // if it's not the same character, then it can not be a palindrome\n            if (s[startingIndex] !== s[startingIndex + lengthOfSubString - 1]) continue;\n            \n            if (lengthOfSubString <= 3 || \n                \n                // this checks if the prior substring was a palindrome\n                dp[startingIndex + 1][startingIndex + lengthOfSubString - 2]) {\n                \n                dp[startingIndex][startingIndex + lengthOfSubString - 1] = true;\n            }\n        }\n    }\n    \n    // find out if any 3 of the partitions are palindromes\n    for (let i = 0; i < s.length; i++) {\n        for (let j = i + 1; j < s.length; j++) {\n            if (dp[0][i] && dp[i + 1][j] && dp[j + 1][s.length - 1]) return true;\n        }\n    }\n    \n    // if we haven't found a partition, return false\n    return false;\n};",
        "solution_java": "class Solution {\n    public boolean checkPartitioning(String s) {\n        int n = s.length();\n        boolean[][] dp = new boolean[n][n];\n        for(int g=0 ; g<n ; g++){\n            for(int i=0, j=g ; j<n ; j++, i++){\n                if(g == 0)\n                    dp[i][j] = true;\n                else if(g == 1)\n                    dp[i][j] = (s.charAt(i) == s.charAt(j)) ? true : false;\n                else{\n                    dp[i][j] = (dp[i+1][j-1]&((s.charAt(i) == s.charAt(j)) ? true : false));\n                }\n            }\n        }\n        for(int i=0 ; i<n-2 ; i++){\n             if(dp[0][i]){\n                for(int j=i+1 ; j<n-1 ; j++){\n                    if(dp[i+1][j] && dp[j+1][n-1]){\n                        return true;\n                    }\n                }\n             }\n        }\n        return false;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n\tvector<vector<int>> dp1;\n\tbool isPalindrome(string& s, int i, int j) {\n\t\tif (i >= j) return true;\n\t\tif (dp1[i][j] != -1) return dp1[i][j];\n\t\tif (s[i] == s[j]) return dp1[i][j] = isPalindrome(s, i + 1, j - 1);\n\t\treturn dp1[i][j] = false;\n\t}\n\tbool checkPartitioning(string s) {\n\t\tint n = s.size();\n\t\tdp1.resize(n,vector<int> (n,-1));\n\t\tfor(int i=0;i<n;i++){\n\t\t\tfor(int j=i+1;j<n-1;j++){\n\t\t\t\tif(isPalindrome(s,0,i) && isPalindrome(s,i+1,j) && isPalindrome(s,j+1,n-1))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n};"
    },
    {
        "title": "Generate Parentheses",
        "algo_input": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n\n&nbsp;\nExample 1:\nInput: n = 3\nOutput: [\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]\nExample 2:\nInput: n = 1\nOutput: [\"()\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 8\n\n",
        "solution_py": "class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n\n        # Initialize the result\n        res = []\n\n        # Recursively go through all possible combinations\n        def add(open, close, partialRes):\n\n            nonlocal res\n\n            # If we have added opening and closing parentheses n times, we reaches a solution\n            if open == close == n:\n                res.append(\"\".join(partialRes))\n                return\n\n            # Add a closing parenthesis to the partial result if we have at least 1 opening parenthesis\n            if close < open:\n                add(open, close + 1, partialRes + [\")\"])\n\n            # Add an opening parenthesis to the partial result if we haven't added n parenthesis yet\n            if open < n:\n                add(open + 1, close, partialRes + [\"(\"])\n\n        add(0, 0, [])\n\n        return res",
        "solution_js": "var generateParenthesis = function(n) {\n    let ans = []\n    generate_parenthisis(n, 0, 0, \"\")\n    return ans\n\n    function generate_parenthisis(n, open, close, res){\n\n        if(open==n && close == n){\n            ans.push(res)\n            return\n        }\n\n        if(open<n){\n            generate_parenthisis(n, open+1, close, res + \"(\")\n        }\n\n        if(close<open){\n            generate_parenthisis(n, open, close+1, res+\")\")\n        }\n\n    }\n};",
        "solution_java": "class Solution {\n    List<String> s = new ArrayList<>();\n    public void get(int n, int x, String p)\n    {\n        if(n==0 && x==0)\n        {\n            s.add(p);\n            return;\n        }\n        if(n==0)\n        {\n            get(n,x-1,p+\")\");\n        }\n        else if(x==0)\n        {\n            get(n-1,x+1,p+\"(\");\n        }\n        else\n        {\n            get(n,x-1,p+\")\");\n            get(n-1,x+1,p+\"(\");\n        }\n    }\n    public List<String> generateParenthesis(int n) \n    {\n        s.clear();\n        get(n,0,\"\");\n        return s;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<string> generateParenthesis(int n) {\n        vector<string> ans;\n        \n        generate(ans,\"\",n,n);\n        \n        return ans;\n    }\n    \n    void generate(vector<string> &ans,string s,int open,int close)\n    {\n        if(open == 0 && close == 0)\n        {\n            ans.push_back(s);\n            return ;\n        }\n        \n        if(open > 0)\n        {\n            generate(ans,s+'(',open-1,close);\n        }\n        \n        if(open < close)\n        {\n            generate(ans,s+')',open,close-1);\n        }\n    }\n};"
    },
    {
        "title": "Largest Combination With Bitwise AND Greater Than Zero",
        "algo_input": "The bitwise AND of an array nums is the bitwise AND of all integers in nums.\n\n\n\tFor example, for nums = [1, 5, 3], the bitwise AND is equal to 1 &amp; 5 &amp; 3 = 1.\n\tAlso, for nums = [7], the bitwise AND is 7.\n\n\nYou are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.\n\nReturn the size of the largest combination of candidates with a bitwise AND greater than 0.\n\n&nbsp;\nExample 1:\n\nInput: candidates = [16,17,71,62,12,24,14]\nOutput: 4\nExplanation: The combination [16,17,62,24] has a bitwise AND of 16 &amp; 17 &amp; 62 &amp; 24 = 16 &gt; 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 &amp; 12 &amp; 24 &amp; 14 = 8 &gt; 0.\n\n\nExample 2:\n\nInput: candidates = [8,8]\nOutput: 2\nExplanation: The largest combination [8,8] has a bitwise AND of 8 &amp; 8 = 8 &gt; 0.\nThe size of the combination is 2, so we return 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= candidates.length &lt;= 105\n\t1 &lt;= candidates[i] &lt;= 107\n\n",
        "solution_py": "class Solution:\n    def largestCombination(self, candidates: List[int]) -> int:\n        return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))",
        "solution_js": "var largestCombination = function(candidates) {\n  const indexArr=Array(24).fill(0)\n\n  for(let candidate of candidates){\n      let index =0\n      while(candidate>0){\n          if((candidate&1)===1)indexArr[index]+=1\n          candidate>>>=1\n          index++\n      }\n  }\n\n  return Math.max(...indexArr)\n};",
        "solution_java": "class Solution {\n  public static int largestCombination(int[] candidates) {\n\t\tint arr[] = new int[32];\n\t\tfor (int i = 0; i < candidates.length; i++) {\n\t\t\tString temp = Integer.toBinaryString(candidates[i]);\n\t\t\tint n = temp.length();\n\t\t\tint index = 0;\n\t\t\twhile (n-- > 0) {\n\t\t\t\tarr[index++] += temp.charAt(n) - '0';\n\t\t\t}\n\t\t}\n\t\tint res = Integer.MIN_VALUE;\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tres = Math.max(res, arr[i]);\n\t\t}\n\t\treturn res;\n\t}\n}",
        "solution_c": "class Solution {\npublic:\n    int largestCombination(vector<int>& candidates) {\n        vector<int> bits(32);\n        for(int i = 0; i < candidates.size(); i++){\n            int temp = 31;\n            while(candidates[i] > 0){\n                bits[temp] += candidates[i] % 2;\n                candidates[i] = candidates[i] / 2;\n                temp--;\n            }\n        }\n        int ans = 0;\n        for(int i = 0; i < 32; i++){\n            //cout<<bits[i]<<\" \";\n            ans = max(ans, bits[i]);\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "K Closest Points to Origin",
        "algo_input": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).\n\nThe distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).\n\nYou may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,3],[-2,2]], k = 1\nOutput: [[-2,2]]\nExplanation:\nThe distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) &lt; sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].\n\n\nExample 2:\n\nInput: points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput: [[3,3],[-2,4]]\nExplanation: The answer [[-2,4],[3,3]] would also be accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= points.length &lt;= 104\n\t-104 &lt; xi, yi &lt; 104\n\n",
        "solution_py": "def cal(ele):\n    return ele[0]**2 +ele[1]**2\n\ndef partition(arr,start,end):\n    # We must take a pivot element randomly to make Quick select work faster\n    rdIdx = randint(start,end)\n    arr[rdIdx],arr[end] = arr[end],arr[rdIdx]\n    pivot = arr[end]\n    i = start-1\n    pivot_dis = cal(pivot)\n    for j in range(start,end):\n        if cal(arr[j]) <= pivot_dis:\n            i+=1\n            arr[j],arr[i] = arr[i],arr[j]\n\n    arr[i+1],arr[end] = arr[end],arr[i+1]\n    return i+1\ndef qSelect(arr,kth,start,end):\n    if start < end:\n        pv= partition(arr,start,end)\n        # _______________________\n        # | Left |ele| Right|\n        # ------------------------\n        # pv\n        # after partition function call, pv is the index that sacrify:\n        # all elements in Left will smaller than ele\n        # all elements in Right side will greater than ele\n        if pv == kth:#\n            return\n        if kth < pv:\n            return qSelect(arr,kth,start,pv-1)\n        else:\n            return qSelect(arr,kth,pv+1,end)\n# Space O (logn) because of using recursion\n# Time: Average case: O(N)\n# Worst case: O(N**2)\nclass Solution:\n    def kClosest(self, points, k):\n        # print(points)\n        qSelect(points,k-1,0,len(points)-1)# kth smallest number will be at (k-1) index in sorted array\n        return points[:k]",
        "solution_js": "/**\n * @param {number[][]} points\n * @param {number} k\n * @return {number[][]}\n */\nvar kClosest = function(points, k) {\n    let res = [];\n    let hashMap = new Map();\n    for(let i = 0; i < points.length; i++) {\n\t\t//store the distance and the index of the points in a map\n        const dis = calcDis(points[i]);\n        hashMap.set(i, dis);\n    }\n\t//sort the map by its distance to the origin\n    const hashMapNew = new Map([...hashMap].sort((a,b) => a[1] - b[1]));\n\t//use the index sorted by distance to get the result\n    let i = 0;\n    for(const x of hashMapNew.keys()) {\n\t\t//do it k times\n        if(i === k) break;\n        res.push(points[x]);\n        i++;\n    }\n    return res;\n};\nvar calcDis = (b) => {\n    return Math.sqrt( Math.pow(b[0], 2) + Math.pow(b[1], 2) );\n}",
        "solution_java": "class Solution {\n    static class Distance {\n        int i;\n        int j;\n        double dist;\n\n        public Distance(int i, int j, double dist) {\n            this.i = i;\n            this.j = j;\n            this.dist = dist;\n        }\n    }\n\n    public int[][] kClosest(int[][] points, int k) {\n        PriorityQueue<Distance> pq = new PriorityQueue<>((x,y) -> Double.compare(x.dist, y.dist));\n        for(int[] point : points) {\n            double dist = calcDistance(point[0], point[1]);\n            pq.offer(new Distance(point[0], point[1], dist));\n        }\n        int cnt = 0;\n        ArrayList<int[]> l = new ArrayList<>();\n        while(cnt < k) {\n            Distance d = pq.poll();\n            l.add(new int[]{d.i, d.j});\n            cnt++;\n        }\n        int[][] res = l.toArray(new int[l.size()][]);\n        return res;\n    }\n\n    private double calcDistance(int i, int j) {\n       double dist = Math.sqrt(Math.pow(i,2) + Math.pow(j,2));\n       return dist;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> kClosest(vector<vector<int>>& points, int k)\n    {\n        //max heap\n        priority_queue<pair<int,pair<int,int>>> pq;//first integer is distance(no need for sq root as comparison is same and next part of pair is coordinate\n        int n= points.size();\n        for(int i=0;i<n;i++)\n        {\n            int dist=(points[i][0]*points[i][0]+points[i][1]*points[i][1]);\n            pq.push({dist, {points[i][0],points[i][1]}});\n            if(pq.size()>k)\n                pq.pop();\n        }\n        vector<vector<int>> ans;\n        while(!pq.empty())\n        {\n            vector<int> temp={(pq.top().second.first),pq.top().second.second};\n            ans.push_back(temp);\n            pq.pop();\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "All Nodes Distance K in Binary Tree",
        "algo_input": "Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.\n\nYou can return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput: [7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\n\n\nExample 2:\n\nInput: root = [1], target = 1, k = 3\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 500].\n\t0 &lt;= Node.val &lt;= 500\n\tAll the values Node.val are unique.\n\ttarget is the value of one of the nodes in the tree.\n\t0 &lt;= k &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n\n        # DFS to make the adj List\n        adjList = defaultdict(list)\n        def dfs(node):\n            if not node:\n                return\n\n            if node.left:\n                adjList[node].append(node.left)\n                adjList[node.left].append(node)\n\n            if node.right:\n                adjList[node].append(node.right)\n                adjList[node.right].append(node)\n            dfs(node.left)\n            dfs(node.right)\n\n        dfs(root)\n\n        # bfs to find the nodes with k distance\n\n        q = deque([(target, 0)])\n        visit = set()\n        visit.add(target)\n        res = []\n        while q:\n            for i in range(len(q)):\n                node, dist = q.popleft()\n\n                if dist == k:\n                    res.append(node.val)\n\n                if dist > k:\n                    break\n                for nei in adjList[node]:\n                    if nei not in visit:\n                        visit.add(nei)\n                        q.append((nei, dist + 1))\n        return res",
        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {TreeNode} target\n * @param {number} k\n * @return {number[]}\n */\nvar distanceK = function(root, target, k) {\n    if(k === 0)\n        return [target.val];\n\n    let res = [];\n\n    const helper = (node, k, bool) => {\n        if(node === null)\n            return [false, 0];\n\n        if(k === 0 && node.val !== target.val) {\n            res.push(node.val);\n            return null;\n        }\n\n        if(bool) {\n            helper(node.left, k - 1, bool);\n            helper(node.right, k - 1, bool);\n            return null;\n        }\n\n        if(node.val === target.val) {\n           //Here nodes of k distance are at bottom\n            helper(node.left, k - 1, true);\n            helper(node.right, k - 1, true);\n            return [true, 1];\n        } else {\n\n            let [l, d] = helper(node.left, k, false);\n\n             //Found target node on left side, now get nodes of k distance from right side as well\n            if(l === true) {\n                if(k - d === 0) //for current node\n                    res.push(node.val);\n                helper(node.right, k - d - 1, true);\n                return [true, d + 1];\n            }\n\n            let [r, d1] = helper(node.right, k, false);\n\n            if(r === true) {\n                if(k - d1 === 0)\n                    res.push(node.val);\n                helper(node.left, k - d1 - 1, true);\n                return [true, d1 + 1];\n            }\n\n            return [false, 0];\n        }\n\n    }\n\n    helper(root, k, false);\n\n    return res;\n};",
        "solution_java": "class Solution {\n    public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {\n        HashMap<TreeNode,TreeNode> map=new HashMap<>();\n        get_parent(root,map);\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(target);\n        int distance=0;\n        HashSet<TreeNode> visited=new HashSet<>();\n        visited.add(target);\n        while(!q.isEmpty())\n        {\n            if(distance==k)\n                break;\n            distance++;\n            int size=q.size();\n            for(int i=0;i<size;i++)\n            {\n                TreeNode current=q.poll();\n                if(current.left!=null && !visited.contains(current.left))\n                {\n                    q.add(current.left);\n                    visited.add(current.left);\n                }\n                if(current.right!=null && !visited.contains(current.right))\n                {\n                    q.add(current.right);\n                    visited.add(current.right);\n                }\n                if(map.containsKey(current) && !visited.contains(map.get(current)))\n                {\n                    q.add(map.get(current));\n                    visited.add(map.get(current));\n                }\n                \n            }\n        }\n        List<Integer> ans=new ArrayList<>();\n        while(!q.isEmpty())\n            ans.add(q.poll().val);\n        return ans;\n        \n    }\n    public void get_parent(TreeNode root,HashMap<TreeNode,TreeNode> map)\n    {\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(root);\n        while(!q.isEmpty())\n        {\n            int size=q.size();\n            for(int i=0;i<size;i++)\n            {\n                TreeNode current=q.poll();\n                if(current.left!=null)\n                {\n                    map.put(current.left,current);\n                    q.add(current.left);\n                }\n                if(current.right!=null)\n                {\n                    map.put(current.right,current);\n                    q.add(current.right);\n                }\n            }\n        }\n    }\n}",
        "solution_c": "void makeParent(TreeNode *root, unordered_map<TreeNode*, TreeNode*> &parent)\n{\n\tqueue<TreeNode*> q;\n\tq.push(root);\n\n\twhile(q.empty()==false)\n\t{\n\t\tTreeNode *curr = q.front();\n\t\tq.pop();\n\n\t\tif(curr->left!=NULL)\n\t\t{\n\t\t\tparent[curr->left] = curr;\n\t\t\tq.push(curr->left);\n\t\t}\n\n\t\tif(curr->right!=NULL)\n\t\t{\n\t\t\tparent[curr->right] = curr;\n\t\t\tq.push(curr->right);\n\t\t}\n\t}\n}\n\nclass Solution {\npublic:\n\nvoid solve(TreeNode* target, unordered_map<TreeNode*,TreeNode*> &parent,unordered_map<TreeNode*,bool> &visited,                     vector<int> &res, int k)\n{        \n    if(k==0){\n        res.push_back(target->val);\n        return;\n    }\n    \n    queue<TreeNode *>q;\n    int distance = 0;\n    \n    q.push(target);\n    visited[target] = 1;\n    \n    while(q.empty()==false)\n    {\n        int count = q.size();\n        distance++;// increment distance value for current level of our level order traversal\n        \n        for(int i=0;i<count;i++)\n        {\n            TreeNode *curr = q.front();\n            q.pop();\n            \n            if(curr->left!=NULL && visited[curr->left]==false)\n            {\n                visited[curr->left] = true;\n                q.push(curr->left);\n                \n                if(distance==k)// when we reach the node at distance = k, push it to res\n                    res.push_back(curr->left->val);\n            }\n            \n            if(curr->right!=NULL && visited[curr->right]==false)\n            {\n                visited[curr->right] = true;\n                q.push(curr->right);\n                \n                if(distance==k)// when we reach the node at distance = k, push it to res\n                    res.push_back(curr->right->val);\n            }\n            \n            if(parent[curr] && visited[parent[curr]]==false)\n            {\n                visited[parent[curr]] = true;\n                q.push(parent[curr]);\n                \n                if(distance==k)// when we reach the node at distance = k, push it to res\n                    res.push_back(parent[curr]->val);\n            }\n        }\n        \n        if(distance==k)// if in curr iteration all k distances nodes have been pushed, we break\n            break;\n    }\n}\n\nvector<int> distanceK(TreeNode* root, TreeNode* target, int k)\n{\n    unordered_map<TreeNode*,TreeNode*> parent;\n    makeParent(root,parent);\n    \n    unordered_map<TreeNode*,bool> visited;\n    vector<int> ans;\n    \n    solve(target,parent,visited,ans,k);// begin from target Node\n    return ans;\n}"
    },
    {
        "title": "Merge Two Sorted Lists",
        "algo_input": "You are given the heads of two sorted linked lists list1 and list2.\n\nMerge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\n\nReturn the head of the merged linked list.\n\n&nbsp;\nExample 1:\n\nInput: list1 = [1,2,4], list2 = [1,3,4]\nOutput: [1,1,2,3,4,4]\n\n\nExample 2:\n\nInput: list1 = [], list2 = []\nOutput: []\n\n\nExample 3:\n\nInput: list1 = [], list2 = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in both lists is in the range [0, 50].\n\t-100 &lt;= Node.val &lt;= 100\n\tBoth list1 and list2 are sorted in non-decreasing order.\n\n",
        "solution_py": "class Solution:\n    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n        cur = dummy = ListNode()\n        while list1 and list2:               \n            if list1.val < list2.val:\n                cur.next = list1\n                list1, cur = list1.next, list1\n            else:\n                cur.next = list2\n                list2, cur = list2.next, list2\n                \n        if list1 or list2:\n            cur.next = list1 if list1 else list2\n            \n        return dummy.next",
        "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} list1\n * @param {ListNode} list2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(list1, list2) {\n\n    if(!list1) return list2\n    if(!list2) return list1\n\n    let mergedList = new ListNode(0);\n    let ptr = mergedList;\n    let curr1 = list1;\n    let curr2 = list2;\n\n    while(curr1 && curr2){\n\n        let newNode = new ListNode();\n        if(!curr2 || curr1.val < curr2.val){\n            newNode.val = curr1.val;\n            newNode.next = null;\n            ptr.next = newNode\n            curr1 =curr1.next;\n        } else{\n            newNode.val = curr2.val;\n            newNode.next = null;\n            ptr.next = newNode\n            curr2 =curr2.next;\n        }\n\n        ptr = ptr.next\n    }\n\n    if(curr1 !== null){\n        ptr.next = curr1;\n        curr1 = curr1.next;\n    }\n\n    if(curr2 !== null){\n        ptr.next = curr2;\n        curr2 = curr2.next;\n    }\n\n    return mergedList.next\n};",
        "solution_java": "class Solution {\n    public ListNode mergeTwoLists(ListNode list1, ListNode list2)\n    {\n        if(list1==null && list2==null)\n            return null;\n        if(list1 == null)\n            return list2;\n        if(list2 == null)\n            return list1;\n\n        ListNode newHead = new ListNode();\n        ListNode newNode = newHead;\n\n        while(list1!=null && list2!=null)\n        {\n            //ListNode newNode = new ListNode();\n            if(list1.val <= list2.val)\n            {\n                newNode.next = list1;\n                list1 = list1.next;\n            }\n            else if(list1.val >= list2.val)\n            {\n                newNode.next = list2;\n                list2 = list2.next;\n            }\n            newNode = newNode.next;\n        }\n        if(list1!=null)\n            newNode.next = list1;\n        else if(list2!=null)\n            newNode.next = list2;\n        return newHead.next;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        ListNode dummy(INT_MIN);\n        ListNode *tail = &dummy;\n        \n        while (l1 && l2) {\n            if (l1->val < l2->val) {\n                tail->next = l1;\n                l1 = l1->next;\n            } else {\n                tail->next = l2;\n                l2 = l2->next;\n            }\n            tail = tail->next;\n        }\n\n        tail->next = l1 ? l1 : l2;\n        return dummy.next;\n    }\n};"
    },
    {
        "title": "Find Eventual Safe States",
        "algo_input": "There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].\n\nA node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).\n\nReturn an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.\n\n&nbsp;\nExample 1:\n\nInput: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput: [2,4,5,6]\nExplanation: The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\n\nExample 2:\n\nInput: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput: [4]\nExplanation:\nOnly node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == graph.length\n\t1 &lt;= n &lt;= 104\n\t0 &lt;= graph[i].length &lt;= n\n\t0 &lt;= graph[i][j] &lt;= n - 1\n\tgraph[i] is sorted in a strictly increasing order.\n\tThe graph may contain self-loops.\n\tThe number of edges in the graph will be in the range [1, 4 * 104].\n\n",
        "solution_py": "import collections\n\nclass Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n\n        n = len(graph)\n        ans = []\n        \n        for i in range(n):\n            if not graph[i]:\n                ans.append(i)\n        \n        def loop(key, loops):\n    \n            loops.append(key)\n            for i in graph[key]:\n                if i in loops:\n                    return False\n                elif i in ans: \n                    continue\n                else:\n                    r = loop(i, loops)\n                    if r == True: \n                        continue\n                    else: \n                        return False\n\n            idx = loops.index(key)\n            loops.pop(idx)\n            return True\n                    \n        for i in range(n):\n            loops = []\n            if i in ans:\n                continue\n            r = loop(i, loops)\n            if r == True: ans.append(i)\n \n        return sorted(ans)",
        "solution_js": "/**\n * @param {number[][]} graph\n * @return {number[]}\n */\nvar eventualSafeNodes = function(graph) {\n    const ans = [];\n    const map = new Map();\n    for(let i=0; i<graph.length; i++) {\n        if(dfs(graph, i, map)) {\n            ans.push(i);\n        }\n    }\n    return ans;\n};\n\nvar dfs = function(graph, node, map) {\n    if(map.has(node)) return map.get(node);\n    map.set(node, false);\n    for(let nei of graph[node]) {\n        if(!dfs(graph, nei, map)) {\n            return false;\n        }\n    }\n    map.set(node, true);\n    return true;\n}",
        "solution_java": "class Solution {\n   public List<Integer> eventualSafeNodes(int[][] graph) {\n    int n=graph.length;\n    List<Integer> ans=new ArrayList<>();\n\n    boolean visited[]=new boolean[n];\n    boolean dfsVisited[]=new boolean[n];\n\n    boolean nodeCycles[]=new boolean[n];\n\n    for(int i=0;i<n;i++){\n        if(visited[i]==false){\n             isCycle(i,graph,dfsVisited,visited,nodeCycles);\n        }\n    }\n    for(int i=0;i<nodeCycles.length;i++){\n        if(nodeCycles[i]==false)\n            ans.add(i);\n    }\n    return ans;\n}\n\npublic boolean isCycle(int node,int graph[][],boolean dfsVisited[],boolean visited[],boolean [] nodeCycles) {\n    visited[node]=true;\n    dfsVisited[node]=true;\n\n    for(int adjNode:graph[node]){\n        if(visited[adjNode]==false){\n           if(isCycle(adjNode,graph,dfsVisited,visited,nodeCycles))\n                return nodeCycles[node]=true;\n        }else if(visited[adjNode]==true && dfsVisited[adjNode]==true){\n            return nodeCycles[node]=true;\n        }\n    }\n    dfsVisited[node]=false;\n    return false;\n}\n}",
        "solution_c": "class Solution {\npublic:\n    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {\n        int n=graph.size();\n        vector<bool> vis(n, false), curr_vis(n, false), safe(n, true);\n\n        for(int i=0; i<n; i++)\n            if(!vis[i])\n                dfs(i, vis, curr_vis, safe, graph);\n\n        vector<int> ans;\n        for(int i=0; i<n; i++)\n            if(safe[i])\n                ans.push_back(i);\n\n        return ans;\n    }\n\n    bool dfs(int i, vector<bool> &vis, vector<bool> &curr_vis, vector<bool> &safe, vector<vector<int>>& graph){\n        vis[i]=true, curr_vis[i]=true;\n\n        for(auto j : graph[i]){\n            if(!vis[j]){\n                if(dfs(j, vis, curr_vis, safe, graph)==false)\n                    return safe[i] = false;\n            }\n            else if(curr_vis[j])\n                return safe[i] = false;\n        }\n\n        curr_vis[i]=false;\n        return safe[i];\n    }\n};"
    },
    {
        "title": "Minimum Time to Collect All Apples in a Tree",
        "algo_input": "Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.\n\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput: 8 \nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  \n\n\nExample 2:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput: 6\nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  \n\n\nExample 3:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 &lt;= ai &lt; bi &lt;= n - 1\n\tfromi &lt; toi\n\thasApple.length == n\n\n",
        "solution_py": "class Solution:\n\n    def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:\n        graph_map = {i: set() for i in range(n)}\n        for edge in edges:\n            graph_map[edge[0]].add(edge[1])\n            graph_map[edge[1]].add(edge[0])\n\n        self.result = set()\n        visited = set()\n        def dfs(node, path):\n            visited.add(node)\n            if hasApple[node]:\n                temp = path + '|' + str(node)\n                temp = temp.split('|')[1:]\n                # print(temp)\n                for i in range(1, len(temp)):\n                    self.result.add((temp[i], temp[i-1]))\n            for nei in graph_map[node]:\n                if nei not in visited:\n                    dfs(nei, path + '|' + str(node))\n\n        dfs(0, \"\")\n        # print(self.result)\n        return len(self.result) * 2",
        "solution_js": "    var cnvrtAdjLst = (mat) => {//converts the list of edges to adjacency list\n    let map = new Map();\n    for(let i=0; i<mat.length; i++){\n        let [p,c] = mat[i];\n        if(map[p]===undefined) map[p] = [c];\n        else map[p].push(c);\n\n        if(map[c]===undefined) map[c] = [p];\n        else map[c].push(p);\n    }\n    return map;\n}\nvar minTime = function(n, edges, hasApple) {\n    let adjList = cnvrtAdjLst(edges);//convert to adjacency list for undirected graph\n    let visited = new Set();// visited set for checking trivial loop\n    let dfsForApples = (src, len) => {\n        visited.add(src);// add root to visited set, as we start exploring the subtree\n        let lengthFromNow = 0;//total length of path visited by each child, 0 if no child has apple\n        for(let i in adjList[src]){\n            if(!visited.has(adjList[src][i])){\n                lengthFromNow += dfsForApples(adjList[src][i],len+1);// add child path length to total length\n            }\n\n        }\n        if(lengthFromNow>0){\n            //if there is an apple present in the subtree\n            return lengthFromNow + 2;\n        }\n        else if(hasApple[src]){\n            //if there is no apple in subtree but apple is present on the root node\n            return 2;\n        }\n        else{\n            // if no apple is present in subtree\n            return 0;\n        }\n    }\n    visited.add(0);\n    let res = dfsForApples(0,0);\n    return res?res-2:0;//check if the root node itself has an apple or no apple is present\n};",
        "solution_java": "class Solution {\n    public int minTime(int n, int[][] edges, List<Boolean> hasApple) {\n        HashMap<Integer,List<Integer>> graph = new HashMap<>(n);\n        for(int edge[] : edges){\n            int a = edge[0], b = edge[1];\n            graph.putIfAbsent(a, new LinkedList<>());\n            graph.putIfAbsent(b, new LinkedList<>());\n            graph.get(a).add(b);\n            graph.get(b).add(a);\n        }\n        \n        boolean[] visited = new boolean[n];\n        Arrays.fill(visited,false);\n        \n        int a = move(0,graph,hasApple,n,visited);\n        \n        return a==-1?0:a;\n    }\n                \n    public int move(int i,HashMap<Integer,List<Integer>> graph,List<Boolean> hasApple,int n,boolean[] visited){\n        visited[i]=true;\n        boolean cont = false;\n        if(hasApple.get(i)){\n            cont=true;\n        }\n        \n        List<Integer> list = graph.get(i);\n        \n        if(list==null){\n            return cont?0:-1;\n        }\n        int j = 0;\n        for(int k : list){\n            if(!visited[k]){\n                int a = move(k,graph,hasApple,n,visited);\n                if(a!=-1){\n                    j+=2+a;\n                }\n            }\n        }\n        if(j==0 && cont) return 0;\n        return j==0?-1:j;\n    }\n}",
        "solution_c": "class DSU{\nprivate:\n    vector<int> parent,rank ;\npublic:\n    DSU(int n){\n        rank.resize(n,1) ;\n        parent.resize(n) ;\n        iota(begin(parent),end(parent),0) ;\n    }\n\n    int find_parent(int node){\n        if(node == parent[node]) return node ;\n        return parent[node] = find_parent(parent[node]) ;\n    }\n    void Union(int u , int v){\n        int U = find_parent(u) , V = find_parent(v) ;\n        if(U == V) return ;\n        if(rank[U] < rank[V]) swap(U,V) ;\n        rank[U] += rank[V] ;\n        parent[V] = U ;\n    }\n    int getRank(int node){\n        return rank[parent[node]] ;\n    }\n\n};\n\nclass Solution {\npublic:\n    vector<bool> dp ;\n    vector<bool> hasApple ;\n    vector<int> adj[100001] ;\n    vector<int> visited ;\n\n    void dfs(int src){\n        visited[src] = 1 ;\n        for(auto &nbr : adj[src]){\n            if(!visited[nbr]){\n                dfs(nbr) ;\n                dp[src] = dp[src] or dp[nbr] ;\n            }\n        }\n    }\n\n    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {\n        DSU dsu(n) ;\n        dp = hasApple ; visited.resize(n,0) ; this->hasApple = hasApple ;\n\n        for(auto &x : edges) adj[x[0]].push_back(x[1]) , adj[x[1]].push_back(x[0]) ;\n        dfs(0) ;\n\n        int start = -1 ;\n        for(int i = 0 ; i < n ; ++i ){\n            if(!dp[i]) continue ;\n            if(start == -1){\n                start = i ; continue ;\n            }\n            dsu.Union(start,i) ;\n        }\n\n        return (dsu.getRank(0) - 1) * 2 ;\n    }\n};"
    },
    {
        "title": "Count Number of Teams",
        "algo_input": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value.\n\nYou have to form a team of 3 soldiers amongst them under the following rules:\n\n\n\tChoose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).\n\tA team is valid if: (rating[i] &lt; rating[j] &lt; rating[k]) or (rating[i] &gt; rating[j] &gt; rating[k]) where (0 &lt;= i &lt; j &lt; k &lt; n).\n\n\nReturn the number of teams you can form given the conditions. (soldiers can be part of multiple teams).\n\n&nbsp;\nExample 1:\n\nInput: rating = [2,5,3,4,1]\nOutput: 3\nExplanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). \n\n\nExample 2:\n\nInput: rating = [2,1,3]\nOutput: 0\nExplanation: We can't form any team given the conditions.\n\n\nExample 3:\n\nInput: rating = [1,2,3,4]\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\tn == rating.length\n\t3 &lt;= n &lt;= 1000\n\t1 &lt;= rating[i] &lt;= 105\n\tAll the integers in rating are unique.\n\n",
        "solution_py": "class Solution:\n    def numTeams(self, ratings: List[int]) -> int:\n        upper_dps = [0 for _ in range(len(ratings))]\n        lower_dps = [0 for _ in range(len(ratings))]\n        \n        count = 0\n        for i in range(len(ratings)):\n            for j in range(i):\n                if ratings[j] < ratings[i]:\n                    count += upper_dps[j]\n                    upper_dps[i] += 1\n                else:\n                    count += lower_dps[j]\n                    lower_dps[i] += 1\n                    \n        return count",
        "solution_js": "// counting bigger / smaller elements\n// if after rating[i] has X bigger elements,\n// and each element has Y bigger elements after them\n// hence total elements that has i < j < k and rating[i] < rating[j] < rating[k]\n// same for the number of smaller elements\n// so the key point here is to know how many elements\n// that smaller and bigger than the current number\nvar numTeams = function(rating) {\n    // save total number of elements after i\n    // that smaller than rating[i]\n    let big = new Array(rating.length).fill(0)\n\n    let n = rating.length;\n    for (let i = 0; i < n - 1; i++) {\n        for (let j = i + 1; j < n; j++) {\n            if (rating[j] > rating[i]) big[i]++;\n        }\n    }\n\n    let count = 0;\n    for (let i = 0; i < n - 1; i++) {\n        for (let j = i + 1; j < n; j++) {\n            if (rating[j] > rating[i]) count += big[j]\n\n            // because all elements are unique, so\n            // we don't need to calculate the number of smaller elements\n            // because if there are X bigger elements after rating[i]\n            // then there are (n - i - 1 - X) smaller elements after rating[i]\n            // or small = n - i - 1 - big\n            else count += n - j - 1 - big[j];\n        }\n    }\n\n    return count;\n}",
        "solution_java": "// Smaller * Larger Solution\n// sum of #smaller * #larger\n// Time complexity: O(N^2)\n// Space complexity: O(1)\nclass Solution {\n    public int numTeams(int[] rating) {\n        final int N = rating.length;\n        int res = 0;\n        for (int i = 1; i < N; i++) {\n            res += smaller(rating, i, -1) * larger(rating, i, 1);\n            res += larger(rating, i, -1) * smaller(rating, i, 1);\n        }\n        return res;\n    }\n    \n    private int smaller(int[] rating, int i, int diff) {\n        int t = rating[i], count = 0;\n        i += diff;\n        while (i >= 0 && i < rating.length) {\n            if (rating[i] < t) count++;\n            i += diff;\n        }\n        return count;\n    }\n    \n    private int larger(int[] rating, int i, int diff) {\n        int t = rating[i], count = 0;\n        i += diff;\n        while (i >= 0 && i < rating.length) {\n            if (rating[i] > t) count++;\n            i += diff;\n        }\n        return count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int numTeams(vector<int>& rating) {\n\n        int i, j, n = rating.size(), ans = 0;\n        vector<int> grt(n, 0), les(n, 0);\n        for(i=0;i<n;i++)\n        {\n            for(j=i+1;j<n;j++)\n            {\n                if(rating[j] > rating[i])\n                    grt[i] += 1;\n                else\n                    les[i] += 1;\n            }\n        }\n\n        for(i=0;i<n;i++)\n        {\n            for(j=i+1;j<n;j++)\n            {\n                if(rating[j] > rating[i])\n                    ans += grt[j];\n                else\n                    ans += les[j];\n            }\n        }\n        return ans;\n    }\n};"
    },
    {
        "title": "Remove One Element to Make the Array Strictly Increasing",
        "algo_input": "Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.\n\nThe array nums is strictly increasing if nums[i - 1] &lt; nums[i] for each index (1 &lt;= i &lt; nums.length).\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,10,5,7]\nOutput: true\nExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.\n\n\nExample 2:\n\nInput: nums = [2,3,1,2]\nOutput: false\nExplanation:\n[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.\n\nExample 3:\n\nInput: nums = [1,1,1]\nOutput: false\nExplanation: The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i] &lt;= 1000\n\n",
        "solution_py": "class Solution:\n    def canBeIncreasing(self, nums: List[int]) -> bool:\n        indx = -1\n        count = 0\n        n = len(nums)\n        \n        # count the number of non-increasing elements\n        for i in range(n-1):\n            if nums[i] >= nums[i+1]:\n                indx = i\n                count += 1\n        \n        #the cases explained above\n        if count==0:\n            return True\n        \n        if count == 1:\n            if indx == 0 or indx == n-2:\n                return True\n            if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]):\n                return True\n            \n        return False",
        "solution_js": "var canBeIncreasing = function(nums) {\n  for (let i = 1, used = false, prev = nums[0]; i < nums.length; i++) {\n    if (nums[i] > prev) { prev = nums[i]; continue }\n    if (used) return false;\n    used = true;\n    (i === 1 || nums[i] > nums[i - 2]) && (prev = nums[i]);\n  }\n  return true;\n};",
        "solution_java": "class Solution {\n    public boolean canBeIncreasing(int[] nums) {\n        int count=0;\n        int p=0;\n        for(int i=0;i<nums.length-1;i++){\n            if(nums[i]>nums[i+1] || nums[i]==nums[i+1]) {\n                count++;\n                p=i;\n            }\n        }\n        if(count>1) return false;\n        else if(count==1){\n            if(p==0 || p== nums.length-2) return true;\n            if(nums[p+1]>nums[p-1] || nums[p+2]>nums[p]) return true;\n            else return false;\n        }\n        return true;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    bool canBeIncreasing(vector<int>& nums) {\nint count = 0;\n        for (int i = 1; i < nums.size(); ++i) {\n            if (nums[i] <= nums[i - 1]) {\n                if (count == 1)\n                    return false;\n                count++;\n                if (i > 1 && nums[i] <= nums[i - 2] )\n                    nums[i] = nums[i - 1];\n            }\n        }\n        return true;\n    }\n};"
    },
    {
        "title": "Count Number of Texts",
        "algo_input": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.\n\nIn order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.\n\n\n\tFor example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.\n\tNote that the digits '0' and '1' do not map to any letters, so Alice does not use them.\n\n\nHowever, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.\n\n\n\tFor example, when Alice sent the message \"bob\", Bob received the string \"2266622\".\n\n\nGiven a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.\n\nSince the answer may be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: pressedKeys = \"22233\"\nOutput: 8\nExplanation:\nThe possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.\n\n\nExample 2:\n\nInput: pressedKeys = \"222222222222222222222222222222222222\"\nOutput: 82876089\nExplanation:\nThere are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= pressedKeys.length &lt;= 105\n\tpressedKeys only consists of digits from '2' - '9'.\n\n",
        "solution_py": "class Solution(object):\n    def countTexts(self, pressedKeys):\n        \"\"\"\n        :type pressedKeys: str\n        :rtype: int\n        \"\"\"\n        dp = [1] + [0]*len(pressedKeys)\n        mod = 10**9 + 7\n        for i, n in enumerate(pressedKeys):\n            dp[i+1] = dp[i]\n            # check if is continous\n            if i >= 1 and pressedKeys[i-1] == n:\n                dp[i+1] += dp[i-1]\n                dp[i+1] %= mod\n                if i >= 2 and pressedKeys[i-2] == n:\n                    dp[i+1] += dp[i-2]\n                    dp[i+1] %= mod\n                    # Special case for '7' and '9' that can have 4 characters combination\n                    if i >= 3 and pressedKeys[i-3] == n and (n == \"7\" or n == \"9\"):\n                        dp[i+1] += dp[i-3]\n                        dp[i+1] %= mod\n        return dp[-1]",
        "solution_js": "var countTexts = function(pressedKeys) {\n    const MOD = 1e9 + 7;\n    const n = pressedKeys.length;\n    const dp = new Array(n + 1).fill(0);\n\n    dp[0] = 1;\n\n    let lastChar = \"\";\n    let repeatCount = 0;\n\n    for (let i = 1; i <= n; ++i) {\n        const currChar = pressedKeys[i - 1];\n\n        if (currChar != lastChar) repeatCount = 0;\n\n        lastChar = currChar;\n        repeatCount += 1;\n\n        dp[i] = (dp[i] + dp[i - 1]) % MOD;\n\n        if (i >= 2 && repeatCount >= 2) dp[i] = (dp[i] + dp[i - 2]) % MOD;\n        if (i >= 3 && repeatCount >= 3) dp[i] = (dp[i] + dp[i - 3]) % MOD;\n        if ((currChar == \"7\" || currChar == \"9\") && i >= 4 && repeatCount >= 4) dp[i] = (dp[i] + dp[i - 4]) % MOD;\n     }\n\n    return dp[n];\n};",
        "solution_java": "class Solution {\n    int mod = (1000000007);\n\n    public int countTexts(String pressedKeys) {\n        int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 };\n        int n = pressedKeys.length();\n        return solve(0,pressedKeys,key);\n    }\n\n    public int solve(int ind, String s, int[] key) {\n        if (ind == s.length()) {\n            return 1;\n        }\n        int count = 0;\n        int num = s.charAt(ind) - '0';\n        int rep = key[num];\n        for (int i = 0; i < rep && ind + i < s.length() && s.charAt(ind) == s.charAt(ind + i); i++) {\n            count += solve(ind + 1 + i, s, key);\n            count %= mod;\n        }\n        return  count;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int mod = 1e9+7;\n    int solve(string &str, int idx) {\n        if(idx == str.length()) return 1;\n        int maxKeyPress = (str[idx] == '7' || str[idx] == '9') ? 4 : 3;\n        long long currIndex = idx, pressFrequency = 1, ans = 0;\n        while(pressFrequency <= maxKeyPress && str[currIndex] == str[idx]) {\n            ++currIndex;\n            ++pressFrequency;\n            ans += solve(str, currIndex) % mod;\n        }\n        return ans%mod;\n    }\n    int countTexts(string pressedKeys) {\n        return solve(pressedKeys, 0) % mod;\n    }\n};"
    },
    {
        "title": "Minimum Number of Steps to Make Two Strings Anagram",
        "algo_input": "You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.\n\nReturn the minimum number of steps to make t an anagram of s.\n\nAn Anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n\n&nbsp;\nExample 1:\n\nInput: s = \"bab\", t = \"aba\"\nOutput: 1\nExplanation: Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.\n\n\nExample 2:\n\nInput: s = \"leetcode\", t = \"practice\"\nOutput: 5\nExplanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.\n\n\nExample 3:\n\nInput: s = \"anagram\", t = \"mangaar\"\nOutput: 0\nExplanation: \"anagram\" and \"mangaar\" are anagrams. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 5 * 104\n\ts.length == t.length\n\ts and t consist of lowercase English letters only.\n\n",
        "solution_py": "class Solution:\n    def minSteps(self, s: str, t: str) -> int:\n        for ch in s:\n\t\t    # Find and replace only one occurence of this character in t\n            t = t.replace(ch, '', 1)\n            \n        return len(t)",
        "solution_js": "var minSteps = function(s, t) {\n\n    let hash1 = hash(s);\n    let hash2 = hash(t);\n    let steps = 0;\n\n    for(let key of Object.keys(hash1)) {\n        if( hash2[key]) {\n            hash1[key] = hash1[key] - hash2[key];\n        }\n        if( hash1[key] > 0 ) {\n            steps += hash1[key];\n        }\n    }\n\n    return steps;\n};\n\nfunction hash(str) {\n    let hash = {};\n    for(let i=0; i<str.length; i++) {\n        let letter = str[i];\n        if( hash[letter] ) {\n            hash[letter]++;\n        } else {\n            hash[letter] = 1;\n        }\n    }\n\n    return hash;\n}",
        "solution_java": "//find the frequency of every letter and check diffrence between the frequency of each letter then divide it by 2 to calculate the minimum number of letter to be changed.\nclass Solution {\n    public int minSteps(String s, String t) {\n        int sf[]=new int[26];\n        int tf[]=new int[26];\n        int diff=0;\n        for(char c:s.toCharArray()){\n            sf[c-'a']++;\n        }\n        for(char c:t.toCharArray()){\n            tf[c-'a']++;\n        }\n        for(int i=0;i<26;i++){\n            diff+=(int)Math.abs(sf[i]-tf[i]);\n        }\n        return diff/2;\n    }\n}",
        "solution_c": "class Solution {\npublic:\n    int minSteps(string s, string t) {\n        int count = 0, length = s.length();\n        vector<int> vec1(26, 0), vec2(26, 0);\n        for(int i = 0; i < length; ++i){\n            vec1[s[i] - 'a']++;\n            vec2[t[i] - 'a']++;\n        }\n        for(int i = 0; i < 26; ++i){\n            if(vec1[i] > vec2[i])\n                count += vec1[i] - vec2[i];\n        }\n        return count;\n    }\n};"
    }
]